/
Program.cs
351 lines (276 loc) · 11.5 KB
/
Program.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
using System;
using System.IO;
using ChakraHost.Hosting;
namespace ChakraHost
{
public static class Program
{
private struct CommandLineArguments
{
public bool Debug;
public bool Profile;
public int ArgumentsStart;
};
private static JavaScriptSourceContext currentSourceContext = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
// We have to hold on to the delegates on the managed side of things so that the
// delegates aren't collected while the script is running.
private static readonly JavaScriptNativeFunction echoDelegate = Echo;
private static readonly JavaScriptNativeFunction runScriptDelegate = RunScript;
private static CommandLineArguments ProcessArguments(string[] arguments)
{
var commandLineArguments = new CommandLineArguments();
int current = 0;
for (; current < arguments.Length; current++)
{
string argument = arguments[current];
if (argument.Length > 0 && (argument[0] == '/' || argument[0] == '-'))
{
string argumentFlag = argument.Substring(1);
if (argumentFlag == "debug")
{
commandLineArguments.Debug = true;
}
else if (argumentFlag == "profile")
{
commandLineArguments.Profile = true;
}
else
{
break;
}
}
else
{
break;
}
}
commandLineArguments.ArgumentsStart = current;
return commandLineArguments;
}
private static void ThrowException(string errorString)
{
// We ignore error since we're already in an error state.
JavaScriptValue errorValue = JavaScriptValue.FromString(errorString);
JavaScriptValue errorObject = JavaScriptValue.CreateError(errorValue);
JavaScriptContext.SetException(errorObject);
}
private static JavaScriptValue Echo(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
{
for (uint index = 1; index < argumentCount; index++)
{
if (index > 1)
{
Console.Write(" ");
}
Console.Write(arguments[index].ConvertToString().ToString());
}
Console.WriteLine();
return JavaScriptValue.Invalid;
}
private static void StartDebugging()
{
JavaScriptContext.StartDebugging();
}
private static JavaScriptValue RunScript(JavaScriptValue callee, bool isConstructCall, JavaScriptValue[] arguments, ushort argumentCount, IntPtr callbackData)
{
if (argumentCount < 2)
{
ThrowException("not enough arguments");
return JavaScriptValue.Invalid;
}
//
// Convert filename.
//
string filename = arguments[1].ToString();
//
// Load the script from the disk.
//
string script = File.ReadAllText(filename);
if (string.IsNullOrEmpty(script))
{
ThrowException("invalid script");
return JavaScriptValue.Invalid;
}
//
// Run the script.
//
return JavaScriptContext.RunScript(script, currentSourceContext++, filename);
}
private static void DefineHostCallback(JavaScriptValue globalObject, string callbackName, JavaScriptNativeFunction callback, IntPtr callbackData)
{
//
// Get property ID.
//
JavaScriptPropertyId propertyId = JavaScriptPropertyId.FromString(callbackName);
//
// Create a function
//
JavaScriptValue function = JavaScriptValue.CreateFunction(callback, callbackData);
//
// Set the property
//
globalObject.SetProperty(propertyId, function, true);
}
private static JavaScriptContext CreateHostContext(JavaScriptRuntime runtime, string[] arguments, int argumentsStart)
{
//
// Create the context. Note that if we had wanted to start debugging from the very
// beginning, we would have called JsStartDebugging right after context is created.
//
JavaScriptContext context = runtime.CreateContext();
//
// Now set the execution context as being the current one on this thread.
//
using (new JavaScriptContext.Scope(context))
{
//
// Create the host object the script will use.
//
JavaScriptValue hostObject = JavaScriptValue.CreateObject();
//
// Get the global object
//
JavaScriptValue globalObject = JavaScriptValue.GlobalObject;
//
// Get the name of the property ("host") that we're going to set on the global object.
//
JavaScriptPropertyId hostPropertyId = JavaScriptPropertyId.FromString("host");
//
// Set the property.
//
globalObject.SetProperty(hostPropertyId, hostObject, true);
//
// Now create the host callbacks that we're going to expose to the script.
//
DefineHostCallback(hostObject, "echo", echoDelegate, IntPtr.Zero);
DefineHostCallback(hostObject, "runScript", runScriptDelegate, IntPtr.Zero);
//
// Create an array for arguments.
//
JavaScriptValue hostArguments = JavaScriptValue.CreateArray((uint)(arguments.Length - argumentsStart));
for (int index = argumentsStart; index < arguments.Length; index++)
{
//
// Create the argument value.
//
JavaScriptValue argument = JavaScriptValue.FromString(arguments[index]);
//
// Create the index.
//
JavaScriptValue indexValue = JavaScriptValue.FromInt32(index - argumentsStart);
//
// Set the value.
//
hostArguments.SetIndexedProperty(indexValue, argument);
}
//
// Get the name of the property that we're going to set on the host object.
//
JavaScriptPropertyId argumentsPropertyId = JavaScriptPropertyId.FromString("arguments");
//
// Set the arguments property.
//
hostObject.SetProperty(argumentsPropertyId, hostArguments, true);
}
return context;
}
private static void PrintScriptException(JavaScriptValue exception)
{
//
// Get message.
//
JavaScriptPropertyId messageName = JavaScriptPropertyId.FromString("message");
JavaScriptValue messageValue = exception.GetProperty(messageName);
string message = messageValue.ToString();
Console.Error.WriteLine("chakrahost: exception: {0}", message);
}
//
// The main entry point for the host.
//
public static int Main(string[] arguments)
{
int returnValue = 1;
CommandLineArguments commandLineArguments = ProcessArguments(arguments);
if (arguments.Length - commandLineArguments.ArgumentsStart < 1)
{
Console.Error.WriteLine("usage: chakrahost [-debug] [-profile] <script name> <arguments>");
return returnValue;
}
try
{
//
// Create the runtime. We're only going to use one runtime for this host.
//
using (JavaScriptRuntime runtime = JavaScriptRuntime.Create())
{
//
// Similarly, create a single execution context. Note that we're putting it on the stack here,
// so it will stay alive through the entire run.
//
JavaScriptContext context = CreateHostContext(runtime, arguments, commandLineArguments.ArgumentsStart);
//
// Now set the execution context as being the current one on this thread.
//
using (new JavaScriptContext.Scope(context))
{
//
// Start debugging if requested.
//
if (commandLineArguments.Debug)
{
StartDebugging();
}
//
// Start profiling if requested.
//
if (commandLineArguments.Profile)
{
var profiler = new Profiler();
JavaScriptContext.StartProfiling(profiler, Native.ProfilerEventMask.TraceAll, 0);
}
//
// Load the script from the disk.
//
string script = File.ReadAllText(arguments[commandLineArguments.ArgumentsStart]);
//
// Run the script.
//
JavaScriptValue result;
try
{
result = JavaScriptContext.RunScript(script, currentSourceContext++, arguments[commandLineArguments.ArgumentsStart]);
}
catch (JavaScriptScriptException e)
{
PrintScriptException(e.Error);
return 1;
}
catch (Exception e)
{
Console.Error.WriteLine("chakrahost: failed to run script: {0}", e.Message);
return 1;
}
//
// Convert the return value.
//
JavaScriptValue numberResult = result.ConvertToNumber();
double doubleResult = numberResult.ToDouble();
returnValue = (int)doubleResult;
//
// Stop profiling.
//
if (commandLineArguments.Profile)
{
JavaScriptContext.StopProfiling(0);
}
}
}
}
catch (Exception e)
{
Console.Error.WriteLine("chakrahost: fatal error: internal error: {0}.", e.Message);
}
return returnValue;
}
}
}