-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsscript.cs
1703 lines (1465 loc) · 74.7 KB
/
csscript.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: 17/10/04 Time: 2:33p
// Module: csscript.cs
// Classes: CSExecutor
// ExecuteOptions
//
// This module contains the definition of the CSExecutor class. Which implements
// compiling C# code and executing 'Main' method of compiled assembly
//
// 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;
#if !net1
using System.Linq;
#endif
using System.Reflection;
#if net1
using System.Collections;
#else
using System.Collections.Generic;
#endif
using System.Text;
using System.Windows.Forms;
using CSScriptLibrary;
using System.Runtime.InteropServices;
using System.Threading;
using System.CodeDom.Compiler;
//using System.Windows.Forms;
using System.Globalization;
using System.Diagnostics;
using Microsoft.CSharp;
namespace csscript
{
internal class Profiler
{
static public Stopwatch Stopwatch = new Stopwatch();
}
internal interface IScriptExecutor
{
void ShowHelp();
void ShowVersion();
void ShowPrecompilerSample();
void CreateDefaultConfigFile();
void ShowSample();
ExecuteOptions GetOptions();
}
/// <summary>
/// CSExecutor is an class that implements execution of *.cs files.
/// </summary>
internal class CSExecutor : IScriptExecutor
{
#region Public interface...
/// <summary>
/// Force caught exceptions to be rethrown.
/// </summary>
public bool Rethrow
{
get { return rethrow; }
set { rethrow = value; }
}
#if net1
private Settings GetPersistedSettings(ArrayList appArgs)
#else
private Settings GetPersistedSettings(List<string> appArgs)
#endif
{
//read persistent settings from configuration file
Settings settings = null;
if (options.noConfig)
{
if (options.altConfig != "")
settings = Settings.Load(Path.GetFullPath(options.altConfig));
else
settings = Settings.Load(null, true);
}
else
{
if (!CSSUtils.IsDynamic(Assembly.GetExecutingAssembly()))
settings = Settings.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "css_config.xml"));
}
if (settings != null)
{
options.hideTemp = settings.HideAutoGeneratedFiles;
if (options.preCompilers == "") //it may be set from command-line args, which have higher precedence
options.preCompilers = settings.Precompiler;
options.altCompiler = settings.ExpandUseAlternativeCompiler();
options.defaultRefAssemblies = settings.ExpandDefaultRefAssemblies();
options.postProcessor = settings.ExpandUsePostProcessor();
options.apartmentState = settings.DefaultApartmentState;
options.reportDetailedErrorInfo = settings.ReportDetailedErrorInfo;
options.openEndDirectiveSyntax = settings.OpenEndDirectiveSyntax;
options.cleanupShellCommand = settings.ExpandCleanupShellCommand();
options.doCleanupAfterNumberOfRuns = settings.DoCleanupAfterNumberOfRuns;
options.inMemoryAsm = settings.InMemoryAsssembly;
//options.useSurrogateHostingProcess = settings.UseSurrogateHostingProcess;
options.hideCompilerWarnings = settings.HideCompilerWarnings;
options.TargetFramework = settings.TargetFramework;
//process default command-line arguments
string[] defaultCmdArgs = settings.DefaultArguments.Split(" ".ToCharArray());
defaultCmdArgs = Utils.RemoveEmptyStrings(defaultCmdArgs);
int firstDefaultScriptArg = CSSUtils.ParseAppArgs(defaultCmdArgs, this);
if (firstDefaultScriptArg != defaultCmdArgs.Length)
{
options.scriptFileName = defaultCmdArgs[firstDefaultScriptArg];
for (int i = firstDefaultScriptArg + 1; i < defaultCmdArgs.Length; i++)
if (defaultCmdArgs[i].Trim().Length != 0)
appArgs.Add(defaultCmdArgs[i]);
}
//if (options.suppressExternalHosting)
// options.useSurrogateHostingProcess = settings.UseSurrogateHostingProcess = false;
}
return settings;
}
/// <summary>
/// The main entry point for the application.
/// </summary>
public void Execute(string[] args, PrintDelegate printDelg, string primaryScript)
{
try
{
print = printDelg != null ? printDelg : new PrintDelegate(VoidPrint);
if (args.Length > 0)
{
#region Parse command-line arguments...
//Here we need to separate application arguments from script ones.
//Script engine arguments are always followed by script arguments
//[appArgs][scriptFile][scriptArgs][//x]
#if net1
ArrayList appArgs = new ArrayList();
#else
List<string> appArgs = new List<string>();
#endif
int firstScriptArg = CSSUtils.ParseAppArgs(args, this);
if (!options.processFile)
return; //no further processing is required (e.g. print help)
if (args.Length <= firstScriptArg)
{
Environment.ExitCode = 1;
print("No script file was specified.");
return; //no script, no script arguments
}
//The following will also update corresponding "options" members from "settings" data
Settings settings = GetPersistedSettings(appArgs);
//process original command-line arguments
if (options.scriptFileName == "")
{
options.scriptFileName = args[firstScriptArg];
firstScriptArg++;
}
for (int i = firstScriptArg; i < args.Length; i++)
{
if (args[i].Trim().Length != 0)
{
if (i == args.Length - 1 && string.Compare(args[args.Length - 1], "//x", true, CultureInfo.InvariantCulture) == 0)
{
options.startDebugger = true;
options.DBG = true;
}
else
appArgs.Add(args[i]);
}
}
#if net1
scriptArgs = (string[])appArgs.ToArray(typeof(string));
#else
scriptArgs = appArgs.ToArray();
#endif
//searchDirs[0] is the script file directory. Set it only after
//the script file resolved because it can be:
// dir defined by the absolute/relative script file path
// "%CSSCRIPT_DIR%\lib
// settings.SearchDirs
// CacheDir
#if net1
ArrayList dirs = new ArrayList();
#else
List<string> dirs = new List<string>();
#endif
using (IDisposable currDir = new CurrentDirGuard())
{
if (options.local)
Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName));
foreach (string dir in options.searchDirs) //some directories may be already set from command-line
dirs.Add(Path.GetFullPath(dir));
if (settings != null)
foreach (string dir in Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray()))
if (dir.Trim() != "")
dirs.Add(Path.GetFullPath(dir));
}
dirs.Add(Utils.GetAssemblyDirectoryName(this.GetType().Assembly));
#if net1
options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, (string[])dirs.ToArray(typeof(string)));
#else
options.scriptFileName = FileParser.ResolveFile(options.scriptFileName, dirs.ToArray());
#endif
if (primaryScript != null)
options.scriptFileNamePrimary = primaryScript;
else
options.scriptFileNamePrimary = options.scriptFileName;
if (CSExecutor.ScriptCacheDir == "")
CSExecutor.SetScriptCacheDir(options.scriptFileName);
dirs.Insert(0, Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName)));
if (settings != null && settings.HideAutoGeneratedFiles != Settings.HideOptions.DoNotHide)
dirs.Add(CSExecutor.ScriptCacheDir);
#if net1
options.searchDirs = (string[])dirs.ToArray(typeof(string));
#else
options.searchDirs = dirs.ToArray();
#endif
CSharpParser.CmdScriptInfo[] cmdScripts = new CSharpParser.CmdScriptInfo[0];
//do quick parsing for pre/post scripts, ThreadingModel and embedded script arguments
CSharpParser parser = new CSharpParser(options.scriptFileName, true);
if (parser.HostOptions.Length != 0)
{
if (Environment.Version.Major >= 4)
{
foreach (string optionsSet in parser.HostOptions)
foreach (string option in optionsSet.Split(' '))
if (option == "/platform:x86")
options.compilerOptions += " " + option;
else if (option.StartsWith("/version:"))
options.TargetFramework = option.Replace("/version:", "");
options.useSurrogateHostingProcess = true;
}
}
else
{
#if fork_x86
////x86 process forking only supported for .NET 4.0+
////This is because earlier versions of CLR would require different "platform build" runasm32.exe
//if (Environment.Version.Major >= 4)
//{
// foreach (string option in parser.CompilerOptions)
// if (option == "/platform:x86" && Environment.Is64BitProcess)
// throw new Surrogate86ProcessRequiredException();
// foreach (string arg in Utils.Concat(args, parser.Args))
// if (arg.StartsWith(CSSUtils.cmdFlagPrefix + "co:"))
// foreach (string option in arg.Split('/'))
// if (option == "platform:x86" && Environment.Is64BitProcess)
// throw new Surrogate86ProcessRequiredException();
//}
#endif
}
//analyse ThreadingModel to use it with execution thread
if (File.Exists(options.scriptFileName))
{
if (parser.ThreadingModel != ApartmentState.Unknown)
options.apartmentState = parser.ThreadingModel;
#if net1
ArrayList preScripts = new ArrayList(parser.CmdScripts);
foreach (CSharpParser.ImportInfo info in parser.Imports)
{
try
{
string file = FileParser.ResolveFile(info.file, options.searchDirs);
if (file.IndexOf(".g.cs") == -1) //non auto-generated file
preScripts.AddRange(new CSharpParser(file, true).CmdScripts);
}
catch { } //some files may not be generated yet
}
cmdScripts = (CSharpParser.CmdScriptInfo[])preScripts.ToArray(typeof(CSharpParser.CmdScriptInfo));
#else
List<string> newSearchDirs = new List<string>(options.searchDirs);
using (IDisposable currDir = new CurrentDirGuard())
{
Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName));
foreach (string dir in parser.ExtraSearchDirs)
newSearchDirs.Add(Path.GetFullPath(dir));
foreach (string file in parser.RefAssemblies)
{
string path = file.Replace("\"", "");
string dir = Path.GetDirectoryName(path);
if (dir != "")
newSearchDirs.Add(Path.GetFullPath(dir));
}
options.searchDirs = newSearchDirs.ToArray();
}
List<CSharpParser.CmdScriptInfo> preScripts = new List<CSharpParser.CmdScriptInfo>(parser.CmdScripts);
foreach (CSharpParser.ImportInfo info in parser.Imports)
{
try
{
string file = FileParser.ResolveFile(info.file, options.searchDirs);
if (file.IndexOf(".g.cs") == -1) //non auto-generated file
{
using (IDisposable currDir = new CurrentDirGuard())
{
CSharpParser impParser = new CSharpParser(file, true, options.searchDirs);
Environment.CurrentDirectory = Path.GetDirectoryName(file);
foreach (string dir in impParser.ExtraSearchDirs)
newSearchDirs.Add(Path.GetFullPath(dir));
options.searchDirs = newSearchDirs.ToArray();
}
preScripts.AddRange(new CSharpParser(file, true).CmdScripts);
}
}
catch { } //some files may not be generated yet
}
cmdScripts = preScripts.ToArray();
#endif
if (primaryScript == null)//this is a primary script
{
int firstEmbeddedScriptArg = CSSUtils.ParseAppArgs(parser.Args, this);
if (firstEmbeddedScriptArg != -1)
{
for (int i = firstEmbeddedScriptArg; i < parser.Args.Length; i++)
appArgs.Add(parser.Args[i]);
}
#if net1
scriptArgs = (string[])appArgs.ToArray(typeof(string));
#else
scriptArgs = appArgs.ToArray();
#endif
}
}
#endregion Parse command-line arguments...
ExecuteOptions originalOptions = (ExecuteOptions)options.Clone(); //preserve master script options
string originalCurrDir = Environment.CurrentDirectory;
//run prescripts
//Note: during the secondary script execution static options will be modified (this is required for
//browsing in CSSEnvironment with reflection). So reset it back with originalOptions after the execution is completed
foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
if (info.preScript)
{
Environment.CurrentDirectory = originalCurrDir;
info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);
CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);
if (originalOptions.DBG)
{
#if net1
ArrayList newArgs = new ArrayList();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "dbg");
info.args = (string[])newArgs.ToArray(typeof(string));
#else
List<string> newArgs = new List<string>();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "dbg");
info.args = newArgs.ToArray();
#endif
}
if (originalOptions.verbose)
{
#if net1
ArrayList newArgs = new ArrayList();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "verbose");
info.args = (string[])newArgs.ToArray(typeof(string));
#else
List<string> newArgs = new List<string>();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "verbose");
info.args = newArgs.ToArray();
#endif
}
if (info.abortOnError)
exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
else
exec.Execute(info.args, null, originalOptions.scriptFileName);
}
options = originalOptions;
ExecuteOptions.options = originalOptions; //update static members as well
Environment.CurrentDirectory = originalCurrDir;
options.compilationContext = CSSUtils.GenerateCompilationContext(parser, options);
//Run main script
//We need to start the execution in a new thread as it is the only way
//to set desired ApartmentState under .NET 2.0
Thread newThread = new Thread(new ThreadStart(this.ExecuteImpl));
#if net1
newThread.ApartmentState = options.apartmentState;
#else
newThread.SetApartmentState(options.apartmentState);
#endif
newThread.Start();
newThread.Join();
if (lastException != null)
if (lastException is SurrogateHostProcessRequiredException)
throw lastException;
else
throw new ApplicationException("Script " + options.scriptFileName + " cannot be executed.", lastException);
//run postscripts
foreach (CSharpParser.CmdScriptInfo info in cmdScripts)
if (!info.preScript)
{
Environment.CurrentDirectory = originalCurrDir;
info.args[1] = FileParser.ResolveFile(info.args[1], originalOptions.searchDirs);
CSExecutor exec = new CSExecutor(info.abortOnError, originalOptions);
if (originalOptions.DBG)
{
#if net1
ArrayList newArgs = new ArrayList();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "dbg");
info.args = (string[])newArgs.ToArray(typeof(string));
#else
List<string> newArgs = new List<string>();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "dbg");
info.args = newArgs.ToArray();
#endif
}
if (originalOptions.verbose)
{
#if net1
ArrayList newArgs = new ArrayList();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "verbose");
info.args = (string[])newArgs.ToArray(typeof(string));
#else
List<string> newArgs = new List<string>();
newArgs.AddRange(info.args);
newArgs.Insert(0, CSSUtils.cmdFlagPrefix + "verbose");
info.args = newArgs.ToArray();
#endif
}
if (info.abortOnError)
{
exec.Rethrow = true;
exec.Execute(info.args, printDelg, originalOptions.scriptFileName);
}
else
exec.Execute(info.args, null, originalOptions.scriptFileName);
}
}
else
{
ShowHelp();
}
}
catch (Surrogate86ProcessRequiredException)
{
throw;
}
catch (SurrogateHostProcessRequiredException)
{
throw;
}
catch (Exception e)
{
Exception ex = e;
if (e is System.Reflection.TargetInvocationException)
ex = e.InnerException;
if (rethrow)
{
throw ex;
}
else
{
Environment.ExitCode = 1;
if (!CSSUtils.IsRuntimeErrorReportingSupressed)
{
if (options.reportDetailedErrorInfo)
print(ex.ToString());
else
print(ex.Message); //Mono friendly
}
}
}
}
/// <summary>
/// Returns custom application config file.
/// </summary>
internal string GetCustomAppConfig(string[] args)
{
try
{
if (args.Length > 0)
{
int firstScriptArg = CSSUtils.ParseAppArgs(args, this);
if (args.Length > firstScriptArg)
{
Settings settings = null;
if (options.noConfig)
{
if (options.altConfig != "")
settings = Settings.Load(Path.GetFullPath(options.altConfig)); //read persistent settings from configuration file
}
else
{
if (!string.IsNullOrEmpty(Assembly.GetExecutingAssembly().Location))
settings = Settings.Load(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "css_config.xml"));
}
if (!options.useScriptConfig && (settings == null || settings.DefaultArguments.IndexOf(CSSUtils.cmdFlagPrefix + "sconfig") == -1))
return "";
string script = args[firstScriptArg];
#if net1
ArrayList dirs = new ArrayList();
#else
List<string> dirs = new List<string>();
#endif
string libDir = Environment.ExpandEnvironmentVariables("%CSSCRIPT_DIR%" + Path.DirectorySeparatorChar + "lib");
if (!libDir.StartsWith("%"))
dirs.Add(libDir);
if (settings != null)
dirs.AddRange(Environment.ExpandEnvironmentVariables(settings.SearchDirs).Split(",;".ToCharArray()));
dirs.Add(Utils.GetAssemblyDirectoryName(Assembly.GetExecutingAssembly()));
#if net1
string[] searchDirs = (string[])dirs.ToArray(typeof(string));
#else
string[] searchDirs = dirs.ToArray();
#endif
script = FileParser.ResolveFile(script, searchDirs);
if (options.customConfigFileName != "")
return Path.Combine(Path.GetDirectoryName(script), options.customConfigFileName);
if (File.Exists(script + ".config"))
return script + ".config";
else if (File.Exists(Path.ChangeExtension(script, ".exe.config")))
return Path.ChangeExtension(script, ".exe.config");
}
}
}
catch
{
//ignore the exception because it will be raised (again) and handled by the Execute method
}
return "";
}
/// <summary>
/// Dummy 'print' to suppress displaying application messages.
/// </summary>
private static void VoidPrint(string msg)
{
}
/// <summary>
/// This method implements compiling and execution of the script.
/// </summary>
public Exception lastException;
/// <summary>
/// This method implements compiling and execution of the script.
/// </summary>
private void ExecuteImpl()
{
try
{
//System.Diagnostics.Debug.Assert(false);
if (options.processFile)
{
if (options.local)
Environment.CurrentDirectory = Path.GetDirectoryName(Path.GetFullPath(options.scriptFileName));
if (!options.noLogo)
{
Console.WriteLine(AppInfo.appLogo);
}
if (Environment.GetEnvironmentVariable("EntryScript") == null)
Environment.SetEnvironmentVariable("EntryScript", Path.GetFullPath(options.scriptFileName));
{
CSSUtils.VerbosePrint("> ----------------", options);
CSSUtils.VerbosePrint(" TragetFramework: " + options.TargetFramework, options);
CSSUtils.VerbosePrint(" CurrentDirectory: " + Environment.CurrentDirectory, options);
CSSUtils.VerbosePrint(" Executing: " + Path.GetFullPath(options.scriptFileName), options);
CSSUtils.VerbosePrint(" Script arguments: ", options);
for (int i = 0; i < scriptArgs.Length; i++)
CSSUtils.VerbosePrint(" " + i + " - " + scriptArgs[i], options);
CSSUtils.VerbosePrint(" SearchDirectories: ", options);
for (int i = 0; i < options.searchDirs.Length; i++)
CSSUtils.VerbosePrint(" " + i + " - " + options.searchDirs[i], options);
CSSUtils.VerbosePrint("> ----------------", options);
CSSUtils.VerbosePrint("", options);
}
bool fileUnlocked = false;
//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.
using (Mutex fileLock = new Mutex(false, "Process." + CSSUtils.GetHashCodeEx(options.scriptFileName).ToString()))
try
{
int start = Environment.TickCount;
//infinite is not good here as it may block forever but continuing while the file is still locked will
//throw a nice informative exception
fileLock.WaitOne(3000, false); //let other thread/process (if any) to finish loading/compiling the same file; 3 seconds should be enough, if you need more use more sophisticated synchronization
//Trace.WriteLine(">>> Waited " + (Environment.TickCount - start));
//compile
string assemblyFileName = options.useCompiled ? GetAvailableAssembly(options.scriptFileName) : null;
if (options.useCompiled && options.useSmartCaching)
{
if (assemblyFileName != null)
{
if (MetaDataItems.IsOutOfDate(options.scriptFileName, assemblyFileName))
{
assemblyFileName = null;
}
}
}
if (options.forceCompile && assemblyFileName != null)
{
Utils.FileDelete(assemblyFileName, true);
assemblyFileName = null;
}
//add searchDirs to PATH to support search path for native dlls
//need to do this before compilation or execution
string path = Environment.GetEnvironmentVariable("PATH");
foreach (string s in options.searchDirs)
path += ";" + s;
#if net1
SetEnvironmentVariable("PATH", path);
#else
Environment.SetEnvironmentVariable("PATH", path);
#endif
//it is possible that there are fully compiled/cached and up to date script but no host compiled yet
string host = ScriptLauncherBuilder.GetLauncherName(assemblyFileName);
bool surrogateHostMissing = (options.useSurrogateHostingProcess &&
(!File.Exists(host) || !CSSUtils.HaveSameTimestamp(host, assemblyFileName)));
if (options.buildExecutable || !options.useCompiled || (options.useCompiled && assemblyFileName == null) || options.forceCompile || surrogateHostMissing)
{
try
{
CSSUtils.VerbosePrint("Compiling script...", options);
CSSUtils.VerbosePrint("", options);
TimeSpan initializationTime = Profiler.Stopwatch.Elapsed;
Profiler.Stopwatch.Reset();
Profiler.Stopwatch.Start();
assemblyFileName = Compile(options.scriptFileName);
if (Profiler.Stopwatch.IsRunning)
{
Profiler.Stopwatch.Stop();
TimeSpan compilationTime = Profiler.Stopwatch.Elapsed;
CSSUtils.VerbosePrint("Initialization time: " + initializationTime.TotalMilliseconds + " msec", options);
CSSUtils.VerbosePrint("Compilation time: " + compilationTime.TotalMilliseconds + " msec", options);
CSSUtils.VerbosePrint("> ----------------", options);
CSSUtils.VerbosePrint("", options);
}
}
catch
{
if (!CSSUtils.IsRuntimeErrorReportingSupressed)
print("Error: Specified file could not be compiled.\n");
throw;
}
finally
{
try { fileLock.ReleaseMutex(); }
catch { }
fileUnlocked = true;
}
}
else
{
Profiler.Stopwatch.Stop();
CSSUtils.VerbosePrint(" Loading script from cache...", options);
CSSUtils.VerbosePrint("", options);
CSSUtils.VerbosePrint(" Cache file: \n " + assemblyFileName, options);
CSSUtils.VerbosePrint("> ----------------", options);
CSSUtils.VerbosePrint("Initialization time: " + Profiler.Stopwatch.Elapsed.TotalMilliseconds + " msec", options);
CSSUtils.VerbosePrint("> ----------------", options);
}
//execute
if (!options.supressExecution)
{
try
{
if (options.useSurrogateHostingProcess)
{
throw new SurrogateHostProcessRequiredException(assemblyFileName, scriptArgs, options.startDebugger);
}
if (options.startDebugger)
{
SaveDebuggingMetadata(options.scriptFileName);
System.Diagnostics.Debugger.Launch();
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
}
if (options.useCompiled || options.cleanupShellCommand != "")
{
AssemblyResolver.CacheProbingResults = true; //it is reasonable safe to do the aggressive probing as we are executing only a single script (standalone execution not a script hosting model)
//despite the name of the class the execution (assembly loading) will be in the current domain
//I am just reusing some functionality of the RemoteExecutor class.
RemoteExecutor executor = new RemoteExecutor(options.searchDirs);
executor.ExecuteAssembly(assemblyFileName, scriptArgs);
}
else
{
//Load and execute assembly in a different domain to make it possible to unload assembly before clean up
AssemblyExecutor executor = new AssemblyExecutor(assemblyFileName, "AsmExecution");
executor.Execute(scriptArgs);
}
}
catch (SurrogateHostProcessRequiredException)
{
throw;
}
catch
{
if (!CSSUtils.IsRuntimeErrorReportingSupressed)
print("Error: Specified file could not be executed.\n");
throw;
}
//cleanup
if (File.Exists(assemblyFileName) && !options.useCompiled && options.cleanupShellCommand == "")
{
Utils.FileDelete(assemblyFileName);
}
//Debug.Assert(false);
if (options.cleanupShellCommand != "")
{
try
{
string counterFile = Path.Combine(GetScriptTempDir(), "counter.txt");
int prevRuns = 0;
if (File.Exists(counterFile))
using (StreamReader sr = new StreamReader(counterFile))
{
prevRuns = int.Parse(sr.ReadToEnd());
}
if (prevRuns > options.doCleanupAfterNumberOfRuns)
{
prevRuns = 1;
string[] cmd = options.ExtractShellCommand(options.cleanupShellCommand);
if (cmd.Length > 1)
Process.Start(cmd[0], cmd[1]);
else
Process.Start(cmd[0]);
}
else
prevRuns++;
using (StreamWriter sw = new StreamWriter(counterFile))
sw.Write(prevRuns);
}
catch { }
}
}
}
finally
{
try { if (!fileUnlocked) fileLock.ReleaseMutex(); } //using fileUnlocked to avoid throwing unnecessary exception
catch { }
}
}
}
catch (Exception e)
{
Exception ex = e;
if (e is System.Reflection.TargetInvocationException)
ex = e.InnerException;
if (rethrow || e is SurrogateHostProcessRequiredException)
{
lastException = ex;
}
else
{
Environment.ExitCode = 1;
if (!CSSUtils.IsRuntimeErrorReportingSupressed)
{
if (options.reportDetailedErrorInfo)
print(ex.ToString());
else
print(ex.Message); //Mono friendly
}
}
}
}
static void SaveDebuggingMetadata(string scriptFile)
{
#if !net1
var dir = Path.Combine(GetScriptTempDir(), "DbgAttach");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
string dataFile = Path.Combine(dir, Process.GetCurrentProcess().Id.ToString() + ".txt");
File.WriteAllText(dataFile, "source:" + scriptFile);
//clean old files
var runningProcesses = Process.GetProcesses().Select(p => p.Id);
foreach (string file in Directory.GetFiles(dir, "*.txt"))
{
int procId = -1;
if (int.TryParse(Path.GetFileNameWithoutExtension(file), out procId))
{
try
{
if (!runningProcesses.Contains(procId))
Utils.FileDelete(file);
}
catch { }
}
}
#endif
}
/// <summary>
/// Compiles C# script file into assembly.
/// </summary>
public string Compile(string scriptFile, string assemblyFile, bool debugBuild)
{
if (assemblyFile != null)
options.forceOutputAssembly = assemblyFile;
else
{
string cacheFile = Path.Combine(CSExecutor.GetCacheDirectory(scriptFile), Path.GetFileName(scriptFile) + ".compiled");
options.forceOutputAssembly = cacheFile;
}
if (debugBuild)
options.DBG = true;
return Compile(scriptFile);
}
#endregion Public interface...
#region Class data...
/// <summary>
/// C# Script arguments array (sub array of application arguments array).
/// </summary>
string[] scriptArgs;
/// <summary>
/// Callback to print application messages to appropriate output.
/// </summary>
static PrintDelegate print;
/// <summary>
/// Container for parsed command line arguments
/// </summary>
static internal ExecuteOptions options = new ExecuteOptions();
/// <summary>
/// Flag to force to rethrow critical exceptions
/// </summary>
bool rethrow;
#endregion Class data...
#region Class methods...
/// <summary>
/// Constructor
/// </summary>
public CSExecutor()
{
rethrow = false;
options = new ExecuteOptions();
}
/// <summary>
/// Constructor
/// </summary>
public CSExecutor(bool rethrow, ExecuteOptions optionsBase)
{
this.rethrow = rethrow;
options = new ExecuteOptions();
//force to read all relative options data from the config file
options.noConfig = optionsBase.noConfig;
options.altConfig = optionsBase.altConfig;
}
public ExecuteOptions GetOptions()
{
return options;
}
/// <summary>
/// Checks/returns if compiled C# script file (ScriptName + ".compiled") available and valid.
/// </summary>
internal string GetAvailableAssembly(string scripFileName)
{
string retval = null;
string asmFileName = options.hideTemp != Settings.HideOptions.DoNotHide ? Path.Combine(CSExecutor.ScriptCacheDir, Path.GetFileName(scripFileName) + ".compiled") : scripFileName + ".c";
if (File.Exists(asmFileName) && File.Exists(scripFileName))
{
FileInfo scriptFile = new FileInfo(scripFileName);
FileInfo asmFile = new FileInfo(asmFileName);