-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtils.cs
1652 lines (1471 loc) · 73.2 KB
/
Utils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region Licence...
//-----------------------------------------------------------------------------
// Date: 25/10/10
// Module: Utils.cs
// Classes: ...
//
// This module contains the definition of the utility classes used by CS-Script modules
//
// Written by Oleg Shilo ([email protected])
//----------------------------------------------
// The MIT License (MIT)
// Copyright (c) 2014 Oleg Shilo
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//----------------------------------------------
#endregion Licence...
using System;
using System.IO;
using System.Reflection;
#if !net1
using System.Collections.Generic;
using System.Linq;
#endif
using System.Text;
using CSScriptLibrary;
using System.Runtime.InteropServices;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Globalization;
using System.Threading;
using System.Collections;
using System.Text.RegularExpressions;
namespace csscript
{
internal class CurrentDirGuard : IDisposable
{
string currentDir = Environment.CurrentDirectory;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
Environment.CurrentDirectory = currentDir;
disposed = true;
}
~CurrentDirGuard()
{
Dispose(false);
}
bool disposed = false;
}
internal class Utils
{
//unfortunately LINQ is not available for .NET 1.1 compilations
public static string[] Concat(string[] array1, string[] array2)
{
string[] retval = new string[array1.Length + array2.Length];
Array.Copy(array1, 0, retval, 0, array1.Length);
Array.Copy(array2, 0, retval, array1.Length, array2.Length);
return retval;
}
public static string[] Concat(string[] array1, string item)
{
string[] retval = new string[array1.Length + 1];
Array.Copy(array1, 0, retval, 0, array1.Length);
retval[retval.Length - 1] = item;
return retval;
}
public static string[] Except(string[] array1, string[] array2)
{
System.Collections.ArrayList retval = new System.Collections.ArrayList();
foreach (string item1 in array1)
{
bool found = false;
foreach (string item2 in array2)
if (item2 == item1)
{
found = true;
break;
}
if (!found)
retval.Add(item1);
}
return (string[])retval.ToArray(typeof(string));
}
public static string[] RemovePathDuplicates(string[] list)
{
System.Collections.ArrayList retval = new System.Collections.ArrayList();
foreach (string item in list)
{
string path = Path.GetFullPath(item.Trim());
bool found = false;
foreach (string pathItem in retval)
if (Utils.IsSamePath(pathItem, path))
{
found = true;
break;
}
if (!found)
retval.Add(path);
}
return (string[])retval.ToArray(typeof(string));
}
public static string[] RemoveDuplicates(string[] list)
{
System.Collections.ArrayList retval = new System.Collections.ArrayList();
foreach (string item in list)
{
if (item.Trim() != "")
{
if (!retval.Contains(item))
retval.Add(item);
}
}
return (string[])retval.ToArray(typeof(string));
}
public static string[] RemoveEmptyStrings(string[] list)
{
System.Collections.ArrayList retval = new System.Collections.ArrayList();
foreach (string item in list)
{
if (item.Trim() != "")
retval.Add(item);
}
return (string[])retval.ToArray(typeof(string));
}
//to avoid throwing the exception
public static string GetAssemblyDirectoryName(Assembly asm)
{
if (CSSUtils.IsDynamic(asm))
return "";
else
return Path.GetDirectoryName(asm.Location);
}
//to avoid throwing the exception
public static string GetAssemblyFileName(Assembly asm)
{
if (CSSUtils.IsDynamic(asm))
return "";
else
return Path.GetFileName(asm.Location);
}
public static string RemoveAssemblyExtension(string asmName)
{
#if net1
if (asmName.ToLower().EndsWith(".dll") || asmName.ToLower().EndsWith(".exe"))
#else
if (asmName.EndsWith(".dll", StringComparison.CurrentCultureIgnoreCase) || asmName.EndsWith(".exe", StringComparison.CurrentCultureIgnoreCase))
#endif
return asmName.Substring(0, asmName.Length - 4);
else
return asmName;
}
public static int PathCompare(string path1, string path2)
{
if (Utils.IsLinux())
return string.Compare(path1, path2);
else
return string.Compare(path1, path2, true);
}
public static bool IsSamePath(string path1, string path2)
{
return PathCompare(path1, path2) == 0;
}
public static void FileDelete(string path)
{
FileDelete(path, false);
}
public static void FileDelete(string path, bool rethrow)
{
//There are the reports about
//anti viruses preventing file deletion
//See 18 Feb message in this thread https://groups.google.com/forum/#!topic/cs-script/5Tn32RXBmRE
for (int i = 0; i < 3; i++)
{
try
{
if (File.Exists(path))
File.Delete(path);
break;
}
catch
{
if (rethrow && i == 2)
throw;
}
Thread.Sleep(200);
}
}
public static bool IsLinux()
{
return (Environment.OSVersion.Platform == PlatformID.Unix);
}
public static bool ContainsPath(string path, string subPath)
{
return PathCompare(path.Substring(0, subPath.Length), subPath) == 0;
}
public static bool IsNullOrWhiteSpace(string text)
{
#if net4
return string.IsNullOrWhiteSpace(text);
#else
return text == null || text.Trim() == "";
#endif
}
/// <summary>
/// Adds compiler options to the CompilerParameters in a manner that it does separate every option by the space character
/// </summary>
static public void AddCompilerOptions(CompilerParameters compilerParams, string option)
{
compilerParams.CompilerOptions += option + " ";
}
///// <summary>
///// More reliable version of the Path.GetTempFileName().
///// It is required because it was some reports about non unique names returned by Path.GetTempFileName()
///// when running in multi-threaded environment.
///// (it is not used yet as I did not give up on PInvoke GetTempFileName())
///// </summary>
///// <returns>Temporary file name.</returns>
//string PathGetTempFileName()
//{
// return Path.GetTempPath() + Guid.NewGuid().ToString() + ".tmp";
//}
}
internal class CSSUtils
{
internal static void VerbosePrint(string message, ExecuteOptions options)
{
if (options.verbose)
Console.WriteLine(message);
}
internal static string GetScriptedCodeAttributeInjectionCode(string scriptFileName)
{
using (Mutex fileLock = new Mutex(false, "GetScriptedCodeAttributeInjectionCode." + CSSUtils.GetHashCodeEx(scriptFileName).ToString()))
{
//Infinite timeout is not good choice here as it may block forever but continuing while the file is still locked will
//throw a nice informative exception.
fileLock.WaitOne(1000, false);
string code = string.Format("[assembly: System.Reflection.AssemblyDescriptionAttribute(@\"{0}\")]", scriptFileName);
string currentCode = "";
string file = Path.Combine(CSExecutor.GetCacheDirectory(scriptFileName), Path.GetFileNameWithoutExtension(scriptFileName) + ".attr.g.cs");
if (File.Exists(file))
using (StreamReader sr = new StreamReader(file))
currentCode = sr.ReadToEnd();
if (currentCode != code)
{
string dir = Path.GetDirectoryName(file);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
for (int i = 0; i < 3; i++)
{
try
{
using (StreamWriter sw = new StreamWriter(file)) //there were reports about the files being locked. Possibly by csc.exe so allow retry
{
sw.Write(code);
}
break;
}
catch { }
Thread.Sleep(200);
}
}
return file;
}
}
public static bool HaveSameTimestamp(string file1, string file2)
{
FileInfo info1 = new FileInfo(file1);
FileInfo info2 = new FileInfo(file2);
return (info2.LastWriteTime == info1.LastWriteTime &&
info2.LastWriteTimeUtc == info1.LastWriteTimeUtc);
}
public static void SetTimestamp(string fileDest, string fileSrc)
{
FileInfo info1 = new FileInfo(fileSrc);
FileInfo info2 = new FileInfo(fileDest);
info2.LastWriteTime = info1.LastWriteTime;
info2.LastWriteTimeUtc = info1.LastWriteTimeUtc;
}
public delegate void ShowDocumentHandler();
static internal string cmdFlagPrefix
{
get
{
if (Utils.IsLinux())
return "-";
else
return "/";
}
}
static internal string[] GetDirectories(string workingDir, string rootDir)
{
if (!Path.IsPathRooted(rootDir))
rootDir = Path.Combine(workingDir, rootDir); //cannot use Path.GetFullPath as it crashes if '*' or '?' are present
#if net1
return new string [] { rootDir };
#else
List<string> result = new List<string>();
if (rootDir.Contains("*") || rootDir.Contains("?"))
{
if (rootDir.EndsWith("**"))
{
foreach (string dir in Directory.GetDirectories(rootDir.Remove(rootDir.Length - 2), "*", SearchOption.AllDirectories))
result.Add(dir);
}
else
{
string pattern = ConvertSimpleExpToRegExp(rootDir);
Regex wildcard = new Regex(pattern, RegexOptions.IgnoreCase);
int pos = rootDir.IndexOfAny(new char[] { '*', '?' });
string newRootDir = rootDir.Remove(pos);
pos = newRootDir.LastIndexOf(Path.DirectorySeparatorChar);
newRootDir = rootDir.Remove(pos);
foreach (string dir in Directory.GetDirectories(newRootDir, "*", SearchOption.AllDirectories))
if (wildcard.IsMatch(dir))
result.Add(dir);
}
}
else
result.Add(rootDir);
return result.ToArray();
#endif
}
//Credit to MDbg team: https://github.com/SymbolSource/Microsoft.Samples.Debugging/blob/master/src/debugger/mdbg/mdbgCommands.cs
public static string ConvertSimpleExpToRegExp(string simpleExp)
{
StringBuilder sb = new StringBuilder();
sb.Append("^");
foreach (char c in simpleExp)
{
switch (c)
{
case '\\':
case '{':
case '|':
case '+':
case '[':
case '(':
case ')':
case '^':
case '$':
case '.':
case '#':
case ' ':
sb.Append('\\').Append(c);
break;
case '*':
sb.Append(".*");
break;
case '?':
sb.Append(".");
break;
default:
sb.Append(c);
break;
}
}
sb.Append("$");
return sb.ToString();
}
/// <summary>
/// Parses application (script engine) arguments.
/// </summary>
/// <param name="args">Arguments</param>
/// <param name="executor">Script executor instance</param>
/// <returns>Index of the first script argument.</returns>
static internal int ParseAppArgs(string[] args, IScriptExecutor executor)
{
ExecuteOptions options = executor.GetOptions();
//Debug.Assert(false);
for (int i = 0; i < args.Length; i++)
{
if (File.Exists(args[i]))
return i; //on Linux '/' may indicate dir but not command
if (args[i].StartsWith(cmdFlagPrefix))
{
if (args[i] == cmdFlagPrefix + "nl") // -nl
{
options.noLogo = true;
}
else if (args[i] == cmdFlagPrefix + "c" && (!options.supressExecution)) // -c
{
options.useCompiled = true;
}
else if (args[i] == cmdFlagPrefix + "sconfig")// -sconfig
{
options.useScriptConfig = true;
}
else if (args[i].StartsWith(cmdFlagPrefix + "sconfig:")) // -sconfig:file
{
options.useScriptConfig = true;
options.customConfigFileName = args[i].Substring((cmdFlagPrefix + "sconfig:").Length);
}
else if (args[i] == cmdFlagPrefix + "verbose")
{
options.verbose = true;
}
else if (args[i].StartsWith(cmdFlagPrefix + "dir:")) // -dir:path1,path2
{
foreach (string dir in args[i].Substring((cmdFlagPrefix + "dir:").Length).Split(','))
options.AddSearchDir(dir.Trim());
}
else if (args[i].StartsWith(cmdFlagPrefix + "precompiler"))
{
if (args[i].StartsWith(cmdFlagPrefix + "precompiler:")) // -precompiler:file1,file2
{
options.preCompilers = args[i].Substring((cmdFlagPrefix + "precompiler:").Length);
}
else
{
executor.ShowPrecompilerSample();
options.processFile = false;
}
}
else if (args[i].StartsWith(cmdFlagPrefix + "pc:")) // -pc:
{
options.preCompilers = args[i].Substring((cmdFlagPrefix + "pc:").Length);
}
else if (args[i].StartsWith(cmdFlagPrefix + "noconfig"))// -noconfig:file
{
options.noConfig = true;
if (args[i].StartsWith(cmdFlagPrefix + "noconfig:"))
{
if (args[i] == (cmdFlagPrefix + "noconfig:out"))
{
executor.CreateDefaultConfigFile();
options.processFile = false;
}
else
options.altConfig = args[i].Substring((cmdFlagPrefix + "noconfig:").Length);
}
}
else if (args[i] == cmdFlagPrefix + "autoclass" || args[i] == cmdFlagPrefix + "ac") // -autoclass -ac
{
options.autoClass = true;
}
else if (args[i] == cmdFlagPrefix + "nathash")
{
//-nathash //native hashing; by default it is deterministic but slower custom string hashing algorithm
//it is a hidden option for the cases when faster hashing is desired
options.customHashing = false;
}
else if (args[i].StartsWith(cmdFlagPrefix + "ca")) // -ca
{
options.useCompiled = true;
options.forceCompile = true;
options.supressExecution = true;
}
else if (args[i].StartsWith(cmdFlagPrefix + "co:")) // -co
{
options.compilerOptions = args[i].Substring((cmdFlagPrefix + "co:").Length);
}
else if (args[i].StartsWith(cmdFlagPrefix + "cd")) // -cd
{
options.supressExecution = true;
options.DLLExtension = true;
}
else if (args[i] == cmdFlagPrefix + "dbg" || args[i] == cmdFlagPrefix + "d") // -dbg -d
{
options.DBG = true;
}
else if (args[i] == cmdFlagPrefix + "l")
{
options.local = true;
}
else if (args[i] == cmdFlagPrefix + "v" || args[i] == cmdFlagPrefix + "V") // -v
{
executor.ShowVersion();
options.processFile = false;
options.versionOnly = true;
}
else if (args[i].StartsWith(cmdFlagPrefix + "r:")) // -r:file1,file2
{
string[] assemblies = args[i].Remove(0, 3).Split(",;".ToCharArray()); //important change
options.refAssemblies = assemblies;
}
else if (args[i].StartsWith(cmdFlagPrefix + "e") && !options.buildExecutable) // -e
{
options.buildExecutable = true;
options.supressExecution = true;
options.buildWinExecutable = args[i].StartsWith(cmdFlagPrefix + "ew"); // -ew
}
else if (args[0] == cmdFlagPrefix + "?" || args[0] == cmdFlagPrefix + "help") // -? -help
{
executor.ShowHelp();
options.processFile = false;
break;
}
else if (args[0] == cmdFlagPrefix + "s") // -s
{
executor.ShowSample();
options.processFile = false;
break;
}
}
else
{
return i;
}
}
return args.Length;
}
private delegate bool CompileMethod(ref string content, string scriptFile, bool IsPrimaryScript, Hashtable context);
internal static PrecompilationContext Precompile(string scriptFile, string[] filesToCompile, ExecuteOptions options)
{
PrecompilationContext context = new PrecompilationContext();
context.SearchDirs = options.searchDirs;
Hashtable contextData = new Hashtable();
contextData["NewDependencies"] = context.NewDependencies;
contextData["NewSearchDirs"] = context.NewSearchDirs;
contextData["NewReferences"] = context.NewReferences;
contextData["NewIncludes"] = context.NewIncludes;
contextData["SearchDirs"] = context.SearchDirs;
#if net1
System.Collections.Hashtable precompilers = CSSUtils.LoadPrecompilers(options);
#else
Dictionary<string, List<object>> precompilers = CSSUtils.LoadPrecompilers(options);
#endif
if (precompilers.Count != 0)
{
for (int i = 0; i < filesToCompile.Length; i++)
{
string content = File.ReadAllText(filesToCompile[i]);
bool modified = false;
foreach (string precompilerFile in precompilers.Keys)
{
#if net1
foreach (object precompiler in precompilers[precompilerFile] as ArrayList)
#else
foreach (object precompiler in precompilers[precompilerFile])
#endif
{
if (options.verbose && i == 0)
{
CSSUtils.VerbosePrint(" Precompilers: ", options);
int index = 0;
foreach (string file in filesToCompile)
CSSUtils.VerbosePrint(" " + index++ + " - " + precompiler.GetType() + "\n " + precompilerFile, options);
CSSUtils.VerbosePrint("", options);
}
MethodInfo method = precompiler.GetType().GetMethod("Compile");
CompileMethod compile = (CompileMethod)Delegate.CreateDelegate(typeof(CompileMethod), method);
bool result = compile(ref content,
filesToCompile[i],
filesToCompile[i] == scriptFile,
contextData);
if (result)
{
context.NewDependencies.Add(precompilerFile);
modified = true;
}
}
}
if (modified)
{
filesToCompile[i] = CSSUtils.SaveAsAutogeneratedScript(content, filesToCompile[i]);
}
}
}
options.searchDirs = Utils.Concat(options.searchDirs, context.NewSearchDirs.ToArray());
foreach (string asm in context.NewReferences)
options.defaultRefAssemblies += "," + asm; //the easiest way to inject extra references is to merge them with the extra assemblies already specified by user
return context;
}
internal const string noDefaultPrecompilerSwitch = "nodefault";
#if net1
public static System.Collections.Hashtable LoadPrecompilers(ExecuteOptions options)
{
System.Collections.Hashtable retval = new System.Collections.Hashtable();
if (!options.preCompilers.StartsWith(noDefaultPrecompilerSwitch)) //no defaults
{
ArrayList compilers = new ArrayList();
compilers.Add(new DefaultPrecompiler());
retval.Add(Assembly.GetExecutingAssembly().Location, compilers);
}
if (options.autoClass)
{
if (retval.ContainsKey(Assembly.GetExecutingAssembly().Location))
(retval[Assembly.GetExecutingAssembly().Location] as ArrayList).Add(new AutoclassPrecompiler());
else
{
ArrayList compilers = new ArrayList();
compilers.Add(new AutoclassPrecompiler());
retval.Add(Assembly.GetExecutingAssembly().Location, compilers);
}
}
#else
internal static Dictionary<string, List<object>> LoadPrecompilers(ExecuteOptions options)
{
Dictionary<string, List<object>> retval = new Dictionary<string, List<object>>();
if (!options.preCompilers.StartsWith(noDefaultPrecompilerSwitch)) //no defaults
retval.Add(Assembly.GetExecutingAssembly().Location, new List<object>() { new DefaultPrecompiler() });
if (options.autoClass)
{
if (retval.ContainsKey(Assembly.GetExecutingAssembly().Location))
retval[Assembly.GetExecutingAssembly().Location].Add(new AutoclassPrecompiler());
else
retval.Add(Assembly.GetExecutingAssembly().Location, new List<object>() { new AutoclassPrecompiler() });
}
#endif
foreach (string precompiler in Utils.RemoveDuplicates((options.preCompilers).Split(new char[] { ',' })))
{
string precompilerFile = precompiler.Trim();
if (precompilerFile != "" && precompilerFile != noDefaultPrecompilerSwitch)
{
string sourceFile = FindImlementationFile(precompilerFile, options.searchDirs);
if (sourceFile == null)
throw new ApplicationException("Cannot find Precompiler file " + precompilerFile);
Assembly asm;
if (sourceFile.EndsWith(".dll", true, CultureInfo.InvariantCulture))
asm = Assembly.LoadFrom(sourceFile);
else
asm = CompilePrecompilerScript(sourceFile, options.searchDirs);
//string typeName = typeof(IPrecompiler).Name;
object precompilerObj = null;
foreach (Module m in asm.GetModules())
{
if (precompilerObj != null)
break;
foreach (Type t in m.GetTypes())
{
if (t.Name.EndsWith("Precompiler"))
{
precompilerObj = asm.CreateInstance(t.Name);
if (precompilerObj == null)
throw new Exception("Precompiler " + sourceFile + " cannot be loaded. CreateInstance returned null.");
break;
}
}
}
#if net1
if (precompilerObj != null)
{
ArrayList compilers = new ArrayList();
compilers.Add(precompilerObj);
retval.Add(sourceFile, compilers);
}
#else
if (precompilerObj != null)
retval.Add(sourceFile, new List<object>() { precompilerObj });
#endif
}
}
return retval;
}
public static string FindFile(string file, string[] searchDirs)
{
if (File.Exists(file))
{
return Path.GetFullPath(file);
}
else if (!Path.IsPathRooted(file))
{
foreach (string dir in searchDirs)
if (File.Exists(Path.Combine(dir, file)))
return Path.Combine(dir, file);
}
return null;
}
public static string FindImlementationFile(string file, string[] searchDirs)
{
string retval = FindFile(file, searchDirs);
if (retval == null && !Path.HasExtension(file))
{
retval = FindFile(file + ".cs", searchDirs);
if (retval == null)
retval = FindFile(file + ".dll", searchDirs);
}
return retval;
}
internal static string[] CollectPrecompillers(CSharpParser parser, ExecuteOptions options)
{
#if net1
ArrayList allPrecompillers = new ArrayList();
#else
List<string> allPrecompillers = new List<string>();
#endif
allPrecompillers.AddRange(options.preCompilers.Split(','));
foreach (string item in parser.Precompilers)
allPrecompillers.AddRange(item.Split(','));
#if net1
return Utils.RemoveDuplicates((string[])allPrecompillers.ToArray(typeof(string)));
#else
return Utils.RemoveDuplicates(allPrecompillers.ToArray());
#endif
}
internal static int GenerateCompilationContext(CSharpParser parser, ExecuteOptions options)
{
string[] allPrecompillers = CollectPrecompillers(parser, options);
StringBuilder sb = new StringBuilder();
foreach (string file in allPrecompillers)
{
if (file != "")
{
sb.Append(FindImlementationFile(file, options.searchDirs));
sb.Append(",");
}
}
return CSSUtils.GetHashCodeEx(sb.ToString());
}
#if !net1
public static string[] GetAppDomainAssemblies()
{
return (from a in AppDomain.CurrentDomain.GetAssemblies()
where !CSSUtils.IsDynamic(a) && !a.GlobalAssemblyCache
select a.Location).ToArray();
}
#endif
public static bool IsDynamic(Assembly asm)
{
//http://bloggingabout.net/blogs/vagif/archive/2010/07/02/net-4-0-and-notsupportedexception-complaining-about-dynamic-assemblies.aspx
//Will cover both System.Reflection.Emit.AssemblyBuilder and System.Reflection.Emit.InternalAssemblyBuilder
return asm.GetType().FullName.EndsWith("AssemblyBuilder") || asm.Location == null || asm.Location == "";
}
public static Assembly CompilePrecompilerScript(string sourceFile, string[] searchDirs)
{
try
{
string precompilerAsm = Path.Combine(CSExecutor.GetCacheDirectory(sourceFile), Path.GetFileName(sourceFile) + ".compiled");
using (Mutex fileLock = new Mutex(false, "CSSPrecompiling." + CSSUtils.GetHashCodeEx(precompilerAsm))) //have to use hash code as path delimiters are illegal in the mutex name
{
//let other thread/process (if any) to finish loading/compiling the same file; 3 seconds should be enough
//if not we will just fail to compile as precompilerAsm will still be locked.
//Infinite timeout is not good choice here as it may block forever but continuing while the file is still locked will
//throw a nice informative exception.
fileLock.WaitOne(3000, false);
if (File.Exists(precompilerAsm))
{
if (File.GetLastWriteTimeUtc(sourceFile) <= File.GetLastWriteTimeUtc(precompilerAsm))
return Assembly.LoadFrom(precompilerAsm);
Utils.FileDelete(precompilerAsm, true);
}
ScriptParser parser = new ScriptParser(sourceFile, searchDirs);
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.IncludeDebugInformation = true;
compilerParams.GenerateExecutable = false;
compilerParams.GenerateInMemory = false;
compilerParams.OutputAssembly = precompilerAsm;
#if net1
ArrayList refAssemblies = new ArrayList();
#else
List<string> refAssemblies = new List<string>();
#endif
//add local and global assemblies (if found) that have the same assembly name as a namespace
foreach (string nmSpace in parser.ReferencedNamespaces)
foreach (string asm in AssemblyResolver.FindAssembly(nmSpace, searchDirs))
refAssemblies.Add(asm);
//add assemblies referenced from code
foreach (string asmName in parser.ReferencedAssemblies)
if (asmName.StartsWith("\"") && asmName.EndsWith("\"")) //absolute path
{
//not-searchable assemblies
string asm = asmName.Replace("\"", "");
refAssemblies.Add(asm);
}
else
{
string nameSpace = Utils.RemoveAssemblyExtension(asmName);
string[] files = AssemblyResolver.FindAssembly(nameSpace, searchDirs);
if (files.Length > 0)
foreach (string asm in files)
refAssemblies.Add(asm);
else
refAssemblies.Add(nameSpace + ".dll");
}
////////////////////////////////////////
#if net1
foreach (string asm in Utils.RemovePathDuplicates((string[])refAssemblies.ToArray(typeof(string))))
#else
foreach (string asm in Utils.RemovePathDuplicates(refAssemblies.ToArray()))
#endif
{
compilerParams.ReferencedAssemblies.Add(asm);
}
#pragma warning disable 618
CompilerResults result = new CSharpCodeProvider().CreateCompiler().CompileAssemblyFromFile(compilerParams, sourceFile);
#pragma warning restore 618
if (result.Errors.Count != 0)
throw CompilerException.Create(result.Errors, true);
if (!File.Exists(precompilerAsm))
throw new Exception("Unknown building error");
File.SetLastWriteTimeUtc(precompilerAsm, File.GetLastWriteTimeUtc(sourceFile));
Assembly retval = Assembly.LoadFrom(precompilerAsm);
return retval;
}
}
catch (Exception e)
{
throw new ApplicationException("Cannot load precompiler " + sourceFile + ": " + e.Message);
}
}
static public bool IsRuntimeErrorReportingSupressed
{
get
{
return Environment.GetEnvironmentVariable("CSS_IsRuntimeErrorReportingSupressed") != null;
}
}
public static int GetHashCodeEx(string s)
{
//during the script first compilation GetHashCodeEx is called ~10 times
//during the cached execution ~5 times only
//and for hosted scenarios it is twice less
//The following profiling demonstrates that in the worst case scenario hashing would
//only add ~2 microseconds to the execution time
//Native executions cost (milliseconds)=> 100000: 7; 10 : 0.0007
//Custom Safe executions cost (milliseconds)=> 100000: 40; 10: 0.004
//Custom Unsafe executions cost (milliseconds)=> 100000: 13; 10: 0.0013
if (ExecuteOptions.options.customHashing)
{
//deterministic GetHashCode; useful for integration with thidr party products (e.g. CS-Script.Npp)
return GetHashCode32(s);
}
else
{
return s.GetHashCode();
}
}
//needed to have reliable HASH as x64 and x32 have different algorithms; This leads to the inability of script clients calculate cache directory correctly
static int GetHashCode32(string s)
{
char[] chars = s.ToCharArray();
int lastCharInd = chars.Length - 1;
int num1 = 0x15051505;
int num2 = num1;
int ind = 0;
while (ind <= lastCharInd)
{
char ch = chars[ind];
char nextCh = ++ind > lastCharInd ? '\0' : chars[ind];
num1 = (((num1 << 5) + num1) + (num1 >> 0x1b)) ^ (nextCh << 16 | ch);
if (++ind > lastCharInd)
break;
ch = chars[ind];
nextCh = ++ind > lastCharInd ? '\0' : chars[ind++];
num2 = (((num2 << 5) + num2) + (num2 >> 0x1b)) ^ (nextCh << 16 | ch);
}
return num1 + num2 * 0x5d588b65;
}
//public static unsafe int GetHashCode32Unsafe(string s)
//{
// fixed (char* str = s.ToCharArray())
// {
// char* chPtr = str;
// int num = 0x15051505;
// int num2 = num;
// int* numPtr = (int*)chPtr;
// for (int i = s.Length; i > 0; i -= 4)
// {
// num = (((num << 5) + num) + (num >> 0x1b)) ^ numPtr[0];