forked from ClearFoundry/ClearScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathV8ScriptEngine.cs
More file actions
1077 lines (948 loc) · 43.9 KB
/
V8ScriptEngine.cs
File metadata and controls
1077 lines (948 loc) · 43.9 KB
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.ClearScript.Util;
using Microsoft.ClearScript.Windows;
namespace Microsoft.ClearScript.V8
{
/// <summary>
/// Represents an instance of the V8 JavaScript engine.
/// </summary>
/// <remarks>
/// Unlike <see cref="WindowsScriptEngine"/> instances, V8ScriptEngine instances do not have
/// thread affinity. The underlying script engine is not thread-safe, however, so this class
/// uses internal locks to automatically serialize all script code execution for a given
/// instance. Script delegates and event handlers are invoked on the calling thread without
/// marshaling.
/// </remarks>
public sealed class V8ScriptEngine : ScriptEngine
{
#region data
private readonly V8ScriptEngineFlags engineFlags;
private readonly V8ContextProxy proxy;
private readonly object script;
private readonly InterlockedOneWayFlag disposedFlag = new InterlockedOneWayFlag();
private const int continuationInterval = 2000;
private bool inContinuationTimerScope;
private bool awaitDebuggerAndPause;
private readonly HostItemCollateral hostItemCollateral;
private readonly IUniqueNameManager documentNameManager = new UniqueFileNameManager();
private List<string> documentNames;
private bool suppressInstanceMethodEnumeration;
private bool suppressExtensionMethodEnumeration;
#endregion
#region constructors
/// <summary>
/// Initializes a new V8 script engine instance.
/// </summary>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine()
: this(null, null)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name)
: this(name, null)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified resource constraints.
/// </summary>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(V8RuntimeConstraints constraints)
: this(null, constraints)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name and resource constraints.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name, V8RuntimeConstraints constraints)
: this(name, constraints, V8ScriptEngineFlags.None)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified options.
/// </summary>
/// <param name="flags">A value that selects options for the operation.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(V8ScriptEngineFlags flags)
: this(flags, 0)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified options and debug port.
/// </summary>
/// <param name="flags">A value that selects options for the operation.</param>
/// <param name="debugPort">A TCP port on which to listen for a debugger connection.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(V8ScriptEngineFlags flags, int debugPort)
: this(null, null, flags, debugPort)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name and options.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name, V8ScriptEngineFlags flags)
: this(name, flags, 0)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name, options, and debug port.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <param name="debugPort">A TCP port on which to listen for a debugger connection.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name, V8ScriptEngineFlags flags, int debugPort)
: this(name, null, flags, debugPort)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified resource constraints and options.
/// </summary>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(V8RuntimeConstraints constraints, V8ScriptEngineFlags flags)
: this(constraints, flags, 0)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified resource constraints, options, and debug port.
/// </summary>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <param name="debugPort">A TCP port on which to listen for a debugger connection.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, int debugPort)
: this(null, constraints, flags, debugPort)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name, resource constraints, and options.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags)
: this(name, constraints, flags, 0)
{
}
/// <summary>
/// Initializes a new V8 script engine instance with the specified name, resource constraints, options, and debug port.
/// </summary>
/// <param name="name">A name to associate with the instance. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="constraints">Resource constraints for the V8 runtime (see remarks).</param>
/// <param name="flags">A value that selects options for the operation.</param>
/// <param name="debugPort">A TCP port on which to listen for a debugger connection.</param>
/// <remarks>
/// A separate V8 runtime is created for the new script engine instance.
/// </remarks>
public V8ScriptEngine(string name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, int debugPort)
: this(null, name, constraints, flags, debugPort)
{
}
internal V8ScriptEngine(V8Runtime runtime, string name, V8RuntimeConstraints constraints, V8ScriptEngineFlags flags, int debugPort)
: base((runtime != null) ? runtime.Name + ":" + name : name)
{
using (var localRuntime = (runtime != null) ? null : new V8Runtime(name, constraints))
{
var activeRuntime = runtime ?? localRuntime;
hostItemCollateral = activeRuntime.HostItemCollateral;
engineFlags = flags;
proxy = V8ContextProxy.Create(activeRuntime.IsolateProxy, Name, flags, debugPort);
script = GetRootItem();
var engineInternal = Evaluate(
MiscHelpers.FormatInvariant("{0} [internal]", GetType().Name),
false,
@"
EngineInternal = (function () {
function convertArgs(args) {
var result = [];
var count = args.Length;
for (var i = 0; i < count; i++) {
result.push(args[i]);
}
return result;
}
function construct(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15) {
return new this(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14, arg15);
}
var isHostObjectKey = this.isHostObjectKey;
delete this.isHostObjectKey;
return {
getCommandResult: function (value) {
if (value == null) {
return value;
}
if (typeof(value.hasOwnProperty) != 'function') {
return '[external]';
}
if (value[isHostObjectKey] === true) {
return value;
}
if (typeof(value.toString) != 'function') {
return '[' + typeof(value) + ']';
}
return value.toString();
},
invokeConstructor: function (constructor, args) {
if (typeof(constructor) != 'function') {
throw new Error('Function expected');
}
return construct.apply(constructor, convertArgs(args));
},
invokeMethod: function (target, method, args) {
if (typeof(method) != 'function') {
throw new Error('Function expected');
}
return method.apply(target, convertArgs(args));
},
getStackTrace: function () {
try {
throw new Error('[stack trace]');
}
catch (exception) {
return exception.stack;
}
return '';
}
};
})();
"
);
((IDisposable)engineInternal).Dispose();
if (flags.HasFlag(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.AwaitDebuggerAndPauseOnStart))
{
awaitDebuggerAndPause = true;
}
}
}
#endregion
#region public members
/// <summary>
/// Gets or sets a soft limit for the size of the V8 runtime's heap.
/// </summary>
/// <remarks>
/// <para>
/// This property is specified in bytes. When it is set to the default value, heap size
/// monitoring is disabled, and scripts with memory leaks or excessive memory usage
/// can cause unrecoverable errors and process termination.
/// </para>
/// <para>
/// A V8 runtime unconditionally terminates the process when it exceeds its resource
/// constraints (see <see cref="V8RuntimeConstraints"/>). This property enables external
/// heap size monitoring that can prevent termination in some scenarios. To be effective,
/// it should be set to a value that is significantly lower than
/// <see cref="V8RuntimeConstraints.MaxOldSpaceSize"/>. Note that enabling heap size
/// monitoring results in slower script execution.
/// </para>
/// <para>
/// Exceeding this limit causes the V8 runtime to interrupt script execution and throw an
/// exception. To re-enable script execution, set this property to a new value.
/// </para>
/// </remarks>
public UIntPtr MaxRuntimeHeapSize
{
get
{
VerifyNotDisposed();
return proxy.MaxRuntimeHeapSize;
}
set
{
VerifyNotDisposed();
proxy.MaxRuntimeHeapSize = value;
}
}
/// <summary>
/// Gets or sets the minimum time interval between consecutive heap size samples.
/// </summary>
/// <remarks>
/// This property is effective only when heap size monitoring is enabled (see
/// <see cref="MaxRuntimeHeapSize"/>).
/// </remarks>
public TimeSpan RuntimeHeapSizeSampleInterval
{
get
{
VerifyNotDisposed();
return proxy.RuntimeHeapSizeSampleInterval;
}
set
{
VerifyNotDisposed();
proxy.RuntimeHeapSizeSampleInterval = value;
}
}
/// <summary>
/// Gets or sets the maximum amount by which the V8 runtime is permitted to grow the stack during script execution.
/// </summary>
/// <remarks>
/// <para>
/// This property is specified in bytes. When it is set to the default value, no stack
/// usage limit is enforced, and scripts with unchecked recursion or other excessive stack
/// usage can cause unrecoverable errors and process termination.
/// </para>
/// <para>
/// Note that the V8 runtime does not monitor stack usage while a host call is in progress.
/// Monitoring is resumed when control returns to the runtime.
/// </para>
/// </remarks>
public UIntPtr MaxRuntimeStackUsage
{
get
{
VerifyNotDisposed();
return proxy.MaxRuntimeStackUsage;
}
set
{
VerifyNotDisposed();
proxy.MaxRuntimeStackUsage = value;
}
}
/// <summary>
/// Enables or disables instance method enumeration.
/// </summary>
/// <remarks>
/// By default, a host object's instance methods are exposed as enumerable properties.
/// Setting this property to <c>true</c> causes instance methods to be excluded from
/// property enumeration. This affects all host objects exposed in the current script
/// engine. Note that instance methods remain both retrievable and invocable regardless of
/// this property's value.
/// </remarks>
public bool SuppressInstanceMethodEnumeration
{
get { return suppressInstanceMethodEnumeration; }
set
{
suppressInstanceMethodEnumeration = value;
OnEnumerationSettingsChanged();
}
}
/// <summary>
/// Enables or disables extension method enumeration.
/// </summary>
/// <remarks>
/// <para>
/// By default, all exposed extension methods appear as enumerable properties of all host
/// objects, regardless of type. Setting this property to <c>true</c> causes extension
/// methods to be excluded from property enumeration. This affects all host objects exposed
/// in the current script engine. Note that extension methods remain both retrievable and
/// invocable regardless of this property's value.
/// </para>
/// <para>
/// This property has no effect if <see cref="SuppressInstanceMethodEnumeration"/> is set
/// to <c>true</c>.
/// </para>
/// </remarks>
public bool SuppressExtensionMethodEnumeration
{
get { return suppressExtensionMethodEnumeration; }
set
{
suppressExtensionMethodEnumeration = value;
RebuildExtensionMethodSummary();
}
}
/// <summary>
/// Creates a compiled script.
/// </summary>
/// <param name="code">The script code to compile.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
public V8Script Compile(string code)
{
return Compile(null, code);
}
/// <summary>
/// Creates a compiled script with an associated document name.
/// </summary>
/// <param name="documentName">A document name for the compiled script. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="code">The script code to compile.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
public V8Script Compile(string documentName, string code)
{
return Compile(new DocumentInfo(documentName), code);
}
/// <summary>
/// Creates a compiled script with the specified document information.
/// </summary>
/// <param name="documentInfo">A structure containing information about the script document.</param>
/// <param name="code">The script code to compile.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
public V8Script Compile(DocumentInfo documentInfo, string code)
{
VerifyNotDisposed();
return ScriptInvoke(() =>
{
documentInfo.UniqueName = documentNameManager.GetUniqueName(documentInfo.Name, DocumentInfo.DefaultName);
return proxy.Compile(documentInfo, FormatCode ? MiscHelpers.FormatCode(code) : code);
});
}
/// <summary>
/// Creates a compiled script, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be generated.</param>
/// <param name="cacheBytes">Cache data for accelerated recompilation.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 script
/// engines and application processes. V8 script engines with debugging enabled cannot
/// generate cache data.
/// </remarks>
/// <seealso cref="Compile(string, V8CacheKind, byte[], out bool)"/>
public V8Script Compile(string code, V8CacheKind cacheKind, out byte[] cacheBytes)
{
return Compile(null, code, cacheKind, out cacheBytes);
}
/// <summary>
/// Creates a compiled script with an associated document name, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="documentName">A document name for the compiled script. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be generated.</param>
/// <param name="cacheBytes">Cache data for accelerated recompilation.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 script
/// engines and application processes. V8 script engines with debugging enabled cannot
/// generate cache data.
/// </remarks>
/// <seealso cref="Compile(string, string, V8CacheKind, byte[], out bool)"/>
public V8Script Compile(string documentName, string code, V8CacheKind cacheKind, out byte[] cacheBytes)
{
return Compile(new DocumentInfo(documentName), code, cacheKind, out cacheBytes);
}
/// <summary>
/// Creates a compiled script with the specified document information, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="documentInfo">A structure containing information about the script document.</param>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be generated.</param>
/// <param name="cacheBytes">Cache data for accelerated recompilation.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 script
/// engines and application processes. V8 script engines with debugging enabled cannot
/// generate cache data.
/// </remarks>
/// <seealso cref="Compile(DocumentInfo, string, V8CacheKind, byte[], out bool)"/>
public V8Script Compile(DocumentInfo documentInfo, string code, V8CacheKind cacheKind, out byte[] cacheBytes)
{
VerifyNotDisposed();
V8Script tempScript = null;
cacheBytes = ScriptInvoke(() =>
{
byte[] tempCacheBytes;
documentInfo.UniqueName = documentNameManager.GetUniqueName(documentInfo.Name, DocumentInfo.DefaultName);
tempScript = proxy.Compile(documentInfo, FormatCode ? MiscHelpers.FormatCode(code) : code, cacheKind, out tempCacheBytes);
return tempCacheBytes;
});
return tempScript;
}
/// <summary>
/// Creates a compiled script, consuming previously generated cache data.
/// </summary>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be consumed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheAccepted"><c>True</c> if <paramref name="cacheBytes"/> was accepted, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. V8 script engines with debugging enabled cannot consume cache data.
/// </remarks>
/// <seealso cref="Compile(string, V8CacheKind, out byte[])"/>
public V8Script Compile(string code, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
return Compile(null, code, cacheKind, cacheBytes, out cacheAccepted);
}
/// <summary>
/// Creates a compiled script with an associated document name, consuming previously generated cache data.
/// </summary>
/// <param name="documentName">A document name for the compiled script. Currently this name is used only as a label in presentation contexts such as debugger user interfaces.</param>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be consumed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheAccepted"><c>True</c> if <paramref name="cacheBytes"/> was accepted, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. V8 script engines with debugging enabled cannot consume cache data.
/// </remarks>
/// <seealso cref="Compile(string, string, V8CacheKind, out byte[])"/>
public V8Script Compile(string documentName, string code, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
return Compile(new DocumentInfo(documentName), code, cacheKind, cacheBytes, out cacheAccepted);
}
/// <summary>
/// Creates a compiled script with an associated document name, consuming previously generated cache data.
/// </summary>
/// <param name="documentInfo">A structure containing information about the script document.</param>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be consumed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheAccepted"><c>True</c> if <paramref name="cacheBytes"/> was accepted, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed multiple times without recompilation.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. V8 script engines with debugging enabled cannot consume cache data.
/// </remarks>
/// <seealso cref="Compile(DocumentInfo, string, V8CacheKind, out byte[])"/>
public V8Script Compile(DocumentInfo documentInfo, string code, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
VerifyNotDisposed();
V8Script tempScript = null;
cacheAccepted = ScriptInvoke(() =>
{
bool tempCacheAccepted;
documentInfo.UniqueName = documentNameManager.GetUniqueName(documentInfo.Name, DocumentInfo.DefaultName);
tempScript = proxy.Compile(documentInfo, FormatCode ? MiscHelpers.FormatCode(code) : code, cacheKind, cacheBytes, out tempCacheAccepted);
return tempCacheAccepted;
});
return tempScript;
}
// ReSharper disable ParameterHidesMember
/// <summary>
/// Evaluates a compiled script.
/// </summary>
/// <param name="script">The compiled script to evaluate.</param>
/// <returns>The result value.</returns>
/// <remarks>
/// For information about the types of result values that script code can return, see
/// <see cref="ScriptEngine.Evaluate(string, bool, string)"/>.
/// </remarks>
public object Evaluate(V8Script script)
{
return Execute(script, true);
}
/// <summary>
/// Executes a compiled script.
/// </summary>
/// <param name="script">The compiled script to execute.</param>
/// <remarks>
/// This method is similar to <see cref="Evaluate(V8Script)"/> with the exception that it
/// does not marshal a result value to the host. It can provide a performance advantage
/// when the result value is not needed.
/// </remarks>
public void Execute(V8Script script)
{
Execute(script, false);
}
// ReSharper restore ParameterHidesMember
/// <summary>
/// Returns memory usage information for the V8 runtime.
/// </summary>
/// <returns>A <see cref="V8RuntimeHeapInfo"/> object containing memory usage information for the V8 runtime.</returns>
public V8RuntimeHeapInfo GetRuntimeHeapInfo()
{
VerifyNotDisposed();
return proxy.GetRuntimeHeapInfo();
}
#endregion
#region internal members
private object GetRootItem()
{
return MarshalToHost(ScriptInvoke(() => proxy.GetRootItem()), false);
}
private void VerifyNotDisposed()
{
if (disposedFlag.IsSet)
{
throw new ObjectDisposedException(ToString());
}
}
// ReSharper disable ParameterHidesMember
private object Execute(V8Script script, bool evaluate)
{
MiscHelpers.VerifyNonNullArgument(script, "script");
VerifyNotDisposed();
return MarshalToHost(ScriptInvoke(() =>
{
if (inContinuationTimerScope || (ContinuationCallback == null))
{
if (MiscHelpers.Exchange(ref awaitDebuggerAndPause, false))
{
proxy.AwaitDebuggerAndPause();
}
return proxy.Execute(script, evaluate);
}
var state = new Timer[] { null };
using (state[0] = new Timer(unused => OnContinuationTimer(state[0]), null, Timeout.Infinite, Timeout.Infinite))
{
inContinuationTimerScope = true;
try
{
state[0].Change(continuationInterval, Timeout.Infinite);
if (MiscHelpers.Exchange(ref awaitDebuggerAndPause, false))
{
proxy.AwaitDebuggerAndPause();
}
return proxy.Execute(script, evaluate);
}
finally
{
inContinuationTimerScope = false;
}
}
}), false);
}
// ReSharper restore ParameterHidesMember
private void OnContinuationTimer(Timer timer)
{
try
{
var callback = ContinuationCallback;
if ((callback != null) && !callback())
{
Interrupt();
}
else
{
timer.Change(continuationInterval, Timeout.Infinite);
}
}
catch (ObjectDisposedException)
{
}
}
#endregion
#region ScriptEngine overrides (public members)
/// <summary>
/// Gets the script engine's recommended file name extension for script files.
/// </summary>
/// <remarks>
/// <see cref="V8ScriptEngine"/> instances return "js" for this property.
/// </remarks>
public override string FileNameExtension
{
get { return "js"; }
}
/// <summary>
/// Allows the host to access script resources directly.
/// </summary>
/// <remarks>
/// The value of this property is an object that is bound to the script engine's root
/// namespace. It dynamically supports properties and methods that correspond to global
/// script objects and functions.
/// </remarks>
public override dynamic Script
{
get
{
VerifyNotDisposed();
return script;
}
}
/// <summary>
/// Executes script code as a command.
/// </summary>
/// <param name="command">The script command to execute.</param>
/// <returns>The command output.</returns>
/// <remarks>
/// <para>
/// This method is similar to <see cref="ScriptEngine.Evaluate(string)"/> but optimized for
/// command consoles. The specified command must be limited to a single expression or
/// statement. Script engines can override this method to customize command execution as
/// well as the process of converting the result to a string for console output.
/// </para>
/// <para>
/// The <see cref="V8ScriptEngine"/> version of this method attempts to use
/// <see href="http://msdn.microsoft.com/en-us/library/k6xhc6yc(VS.85).aspx">toString</see>
/// to convert the return value.
/// </para>
/// </remarks>
public override string ExecuteCommand(string command)
{
return ScriptInvoke(() =>
{
Script.EngineInternal.command = command;
return base.ExecuteCommand("EngineInternal.getCommandResult(eval(EngineInternal.command))");
});
}
/// <summary>
/// Gets a string representation of the script call stack.
/// </summary>
/// <returns>The script call stack formatted as a string.</returns>
/// <remarks>
/// This method returns an empty string if the script engine is not executing script code.
/// The stack trace text format is defined by the script engine.
/// </remarks>
public override string GetStackTrace()
{
string stackTrace = Script.EngineInternal.getStackTrace();
var lines = stackTrace.Split('\n');
return string.Join("\n", lines.Skip(2));
}
/// <summary>
/// Interrupts script execution and causes the script engine to throw an exception.
/// </summary>
/// <remarks>
/// This method can be called safely from any thread.
/// </remarks>
public override void Interrupt()
{
VerifyNotDisposed();
proxy.Interrupt();
}
/// <summary>
/// Performs garbage collection.
/// </summary>
/// <param name="exhaustive"><c>True</c> to perform exhaustive garbage collection, <c>false</c> to favor speed over completeness.</param>
public override void CollectGarbage(bool exhaustive)
{
VerifyNotDisposed();
proxy.CollectGarbage(exhaustive);
}
#endregion
#region ScriptEngine overrides (internal members)
internal override bool EnumerateInstanceMethods
{
get { return base.EnumerateInstanceMethods && !SuppressInstanceMethodEnumeration; }
}
internal override bool EnumerateExtensionMethods
{
get { return base.EnumerateExtensionMethods && !SuppressExtensionMethodEnumeration; }
}
internal override void AddHostItem(string itemName, HostItemFlags flags, object item)
{
VerifyNotDisposed();
var globalMembers = flags.HasFlag(HostItemFlags.GlobalMembers);
if (globalMembers && engineFlags.HasFlag(V8ScriptEngineFlags.DisableGlobalMembers))
{
throw new InvalidOperationException("GlobalMembers support is disabled in this script engine");
}
MiscHelpers.VerifyNonNullArgument(itemName, "itemName");
Debug.Assert(item != null);
ScriptInvoke(() =>
{
var marshaledItem = MarshalToScript(item, flags);
if (!(marshaledItem is HostItem))
{
throw new InvalidOperationException("Invalid host item");
}
proxy.AddGlobalItem(itemName, marshaledItem, globalMembers);
});
}
internal override object MarshalToScript(object obj, HostItemFlags flags)
{
if (obj == null)
{
return DBNull.Value;
}
if (obj is Undefined)
{
return null;
}
if (obj is Nonexistent)
{
return obj;
}
if (engineFlags.HasFlag(V8ScriptEngineFlags.EnableDateTimeConversion) && (obj is DateTime))
{
return obj;
}
var hostItem = obj as HostItem;
if (hostItem != null)
{
if ((hostItem.Engine == this) && (hostItem.Flags == flags))
{
return obj;
}
obj = hostItem.Target;
}
var hostTarget = obj as HostTarget;
if ((hostTarget != null) && !(hostTarget is IHostVariable))
{
obj = hostTarget.Target;
}
var scriptItem = obj as ScriptItem;
if (scriptItem != null)
{
if (scriptItem.Engine == this)
{
return scriptItem.Unwrap();
}
}
return HostItem.Wrap(this, hostTarget ?? obj, flags);
}
internal override object MarshalToHost(object obj, bool preserveHostTarget)
{
if (obj == null)
{
return Undefined.Value;
}
if (obj is DBNull)
{
return null;
}
object result;
if (MiscHelpers.TryMarshalPrimitiveToHost(obj, out result))
{
return result;
}
var hostTarget = obj as HostTarget;
if (hostTarget != null)
{
return preserveHostTarget ? hostTarget : hostTarget.Target;
}
var hostItem = obj as HostItem;
if (hostItem != null)
{
return preserveHostTarget ? hostItem.Target : hostItem.Unwrap();
}
if (obj is ScriptItem)
{
return obj;
}
return V8ScriptItem.Wrap(this, obj);
}
internal override object Execute(DocumentInfo documentInfo, string code, bool evaluate)
{
VerifyNotDisposed();
return ScriptInvoke(() =>
{
documentInfo.UniqueName = documentNameManager.GetUniqueName(documentInfo.Name, DocumentInfo.DefaultName);
if (documentInfo.Flags.GetValueOrDefault().HasFlag(DocumentFlags.IsTransient))
{
documentInfo.UniqueName += " [temp]";
}
else if (documentNames != null)
{
documentNames.Add(documentInfo.UniqueName);
}
if (inContinuationTimerScope || (ContinuationCallback == null))
{
if (MiscHelpers.Exchange(ref awaitDebuggerAndPause, false))
{
proxy.AwaitDebuggerAndPause();
}
return proxy.Execute(documentInfo, FormatCode ? MiscHelpers.FormatCode(code) : code, evaluate);
}
var state = new Timer[] { null };
using (state[0] = new Timer(unused => OnContinuationTimer(state[0]), null, Timeout.Infinite, Timeout.Infinite))
{
inContinuationTimerScope = true;
try
{
state[0].Change(continuationInterval, Timeout.Infinite);
if (MiscHelpers.Exchange(ref awaitDebuggerAndPause, false))
{
proxy.AwaitDebuggerAndPause();
}
return proxy.Execute(documentInfo, FormatCode ? MiscHelpers.FormatCode(code) : code, evaluate);
}
finally
{
inContinuationTimerScope = false;
}
}
});
}
internal override HostItemCollateral HostItemCollateral
{
get { return hostItemCollateral; }
}