-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptLauncherBuilder.cs
258 lines (224 loc) · 9.19 KB
/
ScriptLauncherBuilder.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
#region Licence...
//-----------------------------------------------------------------------------
// Date: 30/10/10 Time: 8:21
// Module: ScriptLauncherBuilder.cs
// Classes: ScriptLauncherBuilder
//
// This module contains the definition of the ScriptLauncherBuilder class. Which implements
// compiling light-weigh host application for the script execution.
//
// 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;
#else
using System.Collections.Generic;
#endif
using System.Text;
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 ScriptLauncherBuilder
{
public static string GetLauncherName(string assembly)
{
return assembly + ".host.exe";
}
// UnitTest
// Make Surrogate scenario to compile conditionally
// + check and delete the exe before building
// + set Appartment state
// + update all ExecutionClients incliding csslib
// + when starting remove css and //x args
//+ try to solve limitations with console Input redurectionlimi
//+ ensure launcher is not build when building dll/exe without execution
public string BuildSurrogateLauncher(string scriptAssembly, string tragetFramework, CompilerParameters compilerParams, ApartmentState appartmentState)
{
//string
#if !net4
throw new ApplicationException("Cannot build surrogate host application because this script engine is build against early version of CLR.");
#else
var provider = CodeDomProvider.CreateProvider("C#", new Dictionary<string, string> { { "CompilerVersion", tragetFramework } });
compilerParams.OutputAssembly = GetLauncherName(scriptAssembly);
compilerParams.GenerateExecutable = true;
compilerParams.GenerateInMemory = false;
compilerParams.IncludeDebugInformation = false;
try
{
Utils.FileDelete(compilerParams.OutputAssembly, true);
}
catch (Exception e)
{
throw new ApplicationException("Cannot build surrogate host application", e);
}
if (compilerParams.CompilerOptions != null)
compilerParams.CompilerOptions = compilerParams.CompilerOptions.Replace("/d:TRACE", "")
.Replace("/d:DEBUG", "");
if (!AppInfo.appConsole)
compilerParams.CompilerOptions += " /target:winexe";
string refAssemblies = "";
string appartment = "[STAThread]";
if (appartmentState == ApartmentState.MTA)
appartment = "[" + appartmentState + "Thread]";
else if (appartmentState == ApartmentState.Unknown)
appartment = "";
foreach (string asm in compilerParams.ReferencedAssemblies)
if (File.Exists(asm)) //ignore GAC (not full path) assemblies
refAssemblies += Assembly.ReflectionOnlyLoadFrom(asm).FullName + ":" + asm + ";";
string code = launcherCode
.Replace("${REF_ASSEMBLIES}", refAssemblies)
.Replace("${APPARTMENT}", appartment)
.Replace("${ASM_MANE}", Path.GetFileName(scriptAssembly));
CompilerResults retval;
bool debugLauncher = false;
if (debugLauncher)
{
compilerParams.IncludeDebugInformation = true;
compilerParams.CompilerOptions += " /d:DEBUG";
//string launcherFile = @"C:\Users\OSH\Desktop\New folder (2)\script.launcher.cs";
string launcherFile = Path.GetTempFileName();
File.WriteAllText(launcherFile, code);
retval = provider.CompileAssemblyFromFile(compilerParams, launcherFile);
}
else
retval = provider.CompileAssemblyFromSource(compilerParams, code);
if (retval.Errors.Count != 0)
throw CompilerException.Create(retval.Errors, true);
CSSUtils.SetTimestamp(compilerParams.OutputAssembly, scriptAssembly);
return compilerParams.OutputAssembly;
#endif
}
const string launcherCode =
@"using System;
using System.Collections;
using System.IO;
using System.Reflection;
class Script
{
${APPARTMENT}
static public int Main(string[] args)
{
try
{
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
MainImpl(args);
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
return 1;
}
return Environment.ExitCode;
}
static public void MainImpl(string[] args)
{
System.Diagnostics.Debug.Assert(false);
string scriptAssembly = """";
bool debug = false;
ArrayList newArgs = new ArrayList();
foreach (string arg in args)
if (arg.StartsWith(""/css_host_dbg:""))
debug = (arg == ""/css_host_dbg:true"");
else if (arg.StartsWith(""/css_host_asm:""))
scriptAssembly = arg.Substring(""/css_host_asm:"".Length);
else
newArgs.Add(arg);
if (debug)
{
System.Diagnostics.Debugger.Launch();
if (System.Diagnostics.Debugger.IsAttached)
System.Diagnostics.Debugger.Break();
}
if (scriptAssembly == """")
{
scriptAssembly = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ""${ASM_MANE}"");
}
InvokeStaticMain(Assembly.LoadFrom(scriptAssembly), (string[])newArgs.ToArray(typeof(string)));
}
static void InvokeStaticMain(Assembly compiledAssembly, string[] scriptArgs)
{
MethodInfo method = null;
foreach (Module m in compiledAssembly.GetModules())
{
foreach (Type t in m.GetTypes())
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.InvokeMethod | BindingFlags.Static;
foreach (MemberInfo mi in t.GetMembers(bf))
{
if (mi.Name == ""Main"")
{
method = t.GetMethod(mi.Name, bf);
}
if (method != null)
break;
}
if (method != null)
break;
}
if (method != null)
break;
}
if (method != null)
{
object retval = null;
if (method.GetParameters().Length != 0)
retval = method.Invoke(new object(), new object[] { (Object)scriptArgs });
else
retval = method.Invoke(new object(), null);
if (retval != null)
{
try
{
Environment.ExitCode = int.Parse(retval.ToString());
}
catch { }
}
}
else
{
throw new ApplicationException(""Cannot find entry point. Make sure script file contains method: 'public static Main(...)'"");
}
}
static string refAssemblies = @""${REF_ASSEMBLIES}"";
static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
if (refAssemblies != """")
{
foreach (string asm in refAssemblies.Split(';'))
if (asm.StartsWith(args.Name))
return Assembly.LoadFrom(asm.Substring(args.Name.Length + 1));
}
return null;
}
}";
}
}