-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathV8ScriptEngine.cs
More file actions
2251 lines (1939 loc) · 94.9 KB
/
V8ScriptEngine.cs
File metadata and controls
2251 lines (1939 loc) · 94.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;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ClearScript.JavaScript;
using Microsoft.ClearScript.Util;
using Microsoft.ClearScript.V8.FastProxy;
using Newtonsoft.Json;
namespace Microsoft.ClearScript.V8
{
// ReSharper disable once PartialTypeWithSinglePart
/// <summary>
/// Represents an instance of the V8 JavaScript engine.
/// </summary>
/// <remarks>
/// Unlike <c>WindowsScriptEngine</c> 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 partial class V8ScriptEngine : ScriptEngine, IJavaScriptEngine
{
#region data
private static readonly DocumentInfo initScriptInfo = new(MiscHelpers.FormatInvariant("{0} [internal]", nameof(V8ScriptEngine)));
private readonly V8Runtime runtime;
private readonly bool usingPrivateRuntime;
private readonly V8ContextProxy proxy;
private readonly V8ScriptItem script;
private readonly InterlockedOneWayFlag disposedFlag = new();
private const int continuationInterval = 2000;
private bool inContinuationTimerScope;
private bool? awaitDebuggerAndPause;
private List<string> documentNames;
private bool suppressInstanceMethodEnumeration;
private bool suppressExtensionMethodEnumeration;
private CommonJSManager commonJSManager;
private JsonModuleManager jsonDocumentManager;
#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 is not null) ? runtime.Name + ":" + name : name, "js")
{
if (runtime is not null)
{
this.runtime = runtime;
}
else
{
this.runtime = runtime = new V8Runtime(name, constraints);
usingPrivateRuntime = true;
}
DocumentNameManager = runtime.DocumentNameManager;
HostItemCollateral = runtime.HostItemCollateral;
Flags = flags;
proxy = V8ContextProxy.Create(runtime.IsolateProxy, Name, flags, debugPort);
script = (V8ScriptItem)GetRootItem();
if (flags.HasAllFlags(V8ScriptEngineFlags.EnableStringifyEnhancements))
{
script.SetProperty("toJson", new Func<object, object, string>(new JsonHelper(this).ToJson));
}
Execute(initScriptInfo, initScript);
if (flags.HasAllFlags(V8ScriptEngineFlags.EnableDebugging | V8ScriptEngineFlags.AwaitDebuggerAndPauseOnStart))
{
awaitDebuggerAndPause = true;
}
}
#endregion
#region public members
/// <summary>
/// Resumes script execution if the script engine is waiting for a debugger connection.
/// </summary>
/// <remarks>
/// This method can be called safely from any thread.
/// </remarks>
public void CancelAwaitDebugger()
{
VerifyNotDisposed();
proxy.CancelAwaitDebugger();
}
/// <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 <c><see cref="V8RuntimeConstraints"/></c>). 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
/// <c><see cref="V8RuntimeConstraints.MaxOldSpaceSize"/></c>. Note that enabling heap size
/// monitoring results in slower script execution.
/// </para>
/// <para>
/// Exceeding this limit causes the V8 runtime to behave in accordance with
/// <c><see cref="RuntimeHeapSizeViolationPolicy"/></c>.
/// </para>
/// <para>
/// Note that
/// <c><see href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer">ArrayBuffer</see></c>
/// memory is allocated outside the runtime's heap and is therefore not tracked by heap
/// size monitoring. See <c><see cref="V8RuntimeConstraints.MaxArrayBufferAllocation"/></c> for
/// additional information.
/// </para>
/// </remarks>
public UIntPtr MaxRuntimeHeapSize
{
get
{
VerifyNotDisposed();
return proxy.MaxIsolateHeapSize;
}
set
{
VerifyNotDisposed();
proxy.MaxIsolateHeapSize = 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
/// <c><see cref="MaxRuntimeHeapSize"/></c>).
/// </remarks>
public TimeSpan RuntimeHeapSizeSampleInterval
{
get
{
VerifyNotDisposed();
return proxy.IsolateHeapSizeSampleInterval;
}
set
{
VerifyNotDisposed();
proxy.IsolateHeapSizeSampleInterval = 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.MaxIsolateStackUsage;
}
set
{
VerifyNotDisposed();
proxy.MaxIsolateStackUsage = 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 => 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 <c><see cref="SuppressInstanceMethodEnumeration"/></c> is set
/// to <c>true</c>.
/// </para>
/// </remarks>
public bool SuppressExtensionMethodEnumeration
{
get => suppressExtensionMethodEnumeration;
set
{
suppressExtensionMethodEnumeration = value;
RebuildExtensionMethodSummary();
}
}
/// <summary>
/// Enables or disables interrupt propagation in the V8 runtime.
/// </summary>
/// <remarks>
/// By default, when nested script execution is interrupted via <c><see cref="Interrupt"/></c>, an
/// instance of <c><see cref="ScriptInterruptedException"/></c>, if not handled by the host, is
/// wrapped and delivered to the parent script frame as a normal exception that JavaScript
/// code can catch. Setting this property to <c>true</c> causes the V8 runtime to remain in
/// the interrupted state until its outermost script frame has been processed.
/// </remarks>
public bool EnableRuntimeInterruptPropagation
{
get
{
VerifyNotDisposed();
return proxy.EnableIsolateInterruptPropagation;
}
set
{
VerifyNotDisposed();
proxy.EnableIsolateInterruptPropagation = value;
}
}
/// <summary>
/// Gets or sets the V8 runtime's behavior in response to a violation of the maximum heap size.
/// </summary>
public V8RuntimeViolationPolicy RuntimeHeapSizeViolationPolicy
{
get
{
VerifyNotDisposed();
return proxy.DisableIsolateHeapSizeViolationInterrupt ? V8RuntimeViolationPolicy.Exception : V8RuntimeViolationPolicy.Interrupt;
}
set
{
VerifyNotDisposed();
switch (value)
{
case V8RuntimeViolationPolicy.Interrupt:
proxy.DisableIsolateHeapSizeViolationInterrupt = false;
return;
case V8RuntimeViolationPolicy.Exception:
proxy.DisableIsolateHeapSizeViolationInterrupt = true;
return;
default:
throw new ArgumentException(MiscHelpers.FormatInvariant("Invalid {0} value", nameof(V8RuntimeViolationPolicy)), nameof(value));
}
}
}
/// <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 meta-information.
/// </summary>
/// <param name="documentInfo">A structure containing meta-information for 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(static ctx => ctx.self.CompileInternal(ctx.documentInfo.MakeUnique(ctx.self), ctx.code), (self: this, documentInfo, 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.
/// </remarks>
/// <c><seealso cref="Compile(string, V8CacheKind, byte[], out bool)"/></c>
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.
/// </remarks>
/// <c><seealso cref="Compile(string, string, V8CacheKind, byte[], out bool)"/></c>
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 meta-information, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="documentInfo">A structure containing meta-information for 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.
/// </remarks>
/// <c><seealso cref="Compile(DocumentInfo, string, V8CacheKind, byte[], out bool)"/></c>
public V8Script Compile(DocumentInfo documentInfo, string code, V8CacheKind cacheKind, out byte[] cacheBytes)
{
VerifyNotDisposed();
var ctx = (self: this, documentInfo, code, cacheKind, cacheBytes: (byte[])null);
var tempScript = ScriptInvoke(
static pCtx =>
{
ref var ctx = ref pCtx.AsRef();
return ctx.self.CompileInternal(ctx.documentInfo.MakeUnique(ctx.self), ctx.code, ctx.cacheKind, out ctx.cacheBytes);
},
StructPtr.FromRef(ref ctx)
);
cacheBytes = ctx.cacheBytes;
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 and used to accelerate script compilation, <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. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
/// <c><seealso cref="Compile(string, V8CacheKind, out byte[])"/></c>
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 and used to accelerate script compilation, <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. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
/// <c><seealso cref="Compile(string, string, V8CacheKind, out byte[])"/></c>
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 meta-information for 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 and used to accelerate script compilation, <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. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
/// <c><seealso cref="Compile(DocumentInfo, string, V8CacheKind, out byte[])"/></c>
public V8Script Compile(DocumentInfo documentInfo, string code, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
VerifyNotDisposed();
var ctx = (self: this, documentInfo, code, cacheKind, cacheBytes, cacheAccepted: false);
var tempScript = ScriptInvoke(
static pCtx =>
{
ref var ctx = ref pCtx.AsRef();
return ctx.self.CompileInternal(ctx.documentInfo.MakeUnique(ctx.self), ctx.code, ctx.cacheKind, ctx.cacheBytes, out ctx.cacheAccepted);
},
StructPtr.FromRef(ref ctx)
);
cacheAccepted = ctx.cacheAccepted;
return tempScript;
}
/// <summary>
/// Creates a compiled script, consuming previously generated cache data and updating it if necessary.
/// </summary>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</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. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script Compile(string code, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
return Compile(null, code, cacheKind, ref cacheBytes, out cacheResult);
}
/// <summary>
/// Creates a compiled script with an associated document name, consuming previously generated cache data and updating it if necessary.
/// </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 processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</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. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script Compile(string documentName, string code, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
return Compile(new DocumentInfo(documentName), code, cacheKind, ref cacheBytes, out cacheResult);
}
/// <summary>
/// Creates a compiled script with the specified document meta-information, consuming previously generated cache data and updating it if necessary.
/// </summary>
/// <param name="documentInfo">A structure containing meta-information for the script document.</param>
/// <param name="code">The script code to compile.</param>
/// <param name="cacheKind">The kind of cache data to be processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</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. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script Compile(DocumentInfo documentInfo, string code, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
VerifyNotDisposed();
var ctx = (self: this, documentInfo, code, cacheKind, cacheBytes, cacheResult: V8CacheResult.Disabled);
var tempScript = ScriptInvoke(
static pCtx =>
{
ref var ctx = ref pCtx.AsRef();
return ctx.self.CompileInternal(ctx.documentInfo.MakeUnique(ctx.self), ctx.code, ctx.cacheKind, ref ctx.cacheBytes, out ctx.cacheResult);
},
StructPtr.FromRef(ref ctx)
);
if (ctx.cacheResult == V8CacheResult.Updated)
{
cacheBytes = ctx.cacheBytes;
}
cacheResult = ctx.cacheResult;
return tempScript;
}
/// <summary>
/// Loads and compiles a script document.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
public V8Script CompileDocument(string specifier)
{
return CompileDocument(specifier, null);
}
/// <summary>
/// Loads and compiles a document with the specified category.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
public V8Script CompileDocument(string specifier, DocumentCategory category)
{
return CompileDocument(specifier, category, null);
}
/// <summary>
/// Loads and compiles a document with the specified category and context callback.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <param name="contextCallback">An optional context callback for the requested document.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
public V8Script CompileDocument(string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
MiscHelpers.VerifyNonBlankArgument(specifier, nameof(specifier), "Invalid document specifier");
var document = DocumentSettings.LoadDocument(null, specifier, category, contextCallback);
return Compile(document.Info, document.GetTextContents());
}
/// <summary>
/// Loads and compiles a script document, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</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 by multiple V8 script engine instances.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 runtimes
/// and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, V8CacheKind cacheKind, out byte[] cacheBytes)
{
return CompileDocument(specifier, null, cacheKind, out cacheBytes);
}
/// <summary>
/// Loads and compiles a document with the specified category, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</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 by multiple V8 script engine instances.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 runtimes
/// and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, V8CacheKind cacheKind, out byte[] cacheBytes)
{
return CompileDocument(specifier, category, null, cacheKind, out cacheBytes);
}
/// <summary>
/// Loads and compiles a document with the specified category and context callback, generating cache data for accelerated recompilation.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <param name="contextCallback">An optional context callback for the requested document.</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 by multiple V8 script engine instances.</returns>
/// <remarks>
/// The generated cache data can be stored externally and is usable in other V8 runtimes
/// and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, DocumentContextCallback contextCallback, V8CacheKind cacheKind, out byte[] cacheBytes)
{
MiscHelpers.VerifyNonBlankArgument(specifier, nameof(specifier), "Invalid document specifier");
var document = DocumentSettings.LoadDocument(null, specifier, category, contextCallback);
return Compile(document.Info, document.GetTextContents(), cacheKind, out cacheBytes);
}
/// <summary>
/// Loads and compiles a script document, consuming previously generated cache data.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</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 and used to accelerate script compilation, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
public V8Script CompileDocument(string specifier, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
return CompileDocument(specifier, null, cacheKind, cacheBytes, out cacheAccepted);
}
/// <summary>
/// Loads and compiles a document with the specified category, consuming previously generated cache data.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</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 and used to accelerate script compilation, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
return CompileDocument(specifier, category, null, cacheKind, cacheBytes, out cacheAccepted);
}
/// <summary>
/// Loads and compiles a document with the specified category and context callback, consuming previously generated cache data.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <param name="contextCallback">An optional context callback for the requested document.</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 and used to accelerate script compilation, <c>false</c> otherwise.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. Note that script compilation may be bypassed if a suitable compiled
/// script already exists in the V8 runtime's memory. In that case, the cache data is
/// ignored and <paramref name="cacheAccepted"/> is set to <c>false</c>.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, DocumentContextCallback contextCallback, V8CacheKind cacheKind, byte[] cacheBytes, out bool cacheAccepted)
{
MiscHelpers.VerifyNonBlankArgument(specifier, nameof(specifier), "Invalid document specifier");
var document = DocumentSettings.LoadDocument(null, specifier, category, contextCallback);
return Compile(document.Info, document.GetTextContents(), cacheKind, cacheBytes, out cacheAccepted);
}
/// <summary>
/// Loads and compiles a script document, consuming previously generated cache data and updating it if necessary.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="cacheKind">The kind of cache data to be processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
return CompileDocument(specifier, null, cacheKind, ref cacheBytes, out cacheResult);
}
/// <summary>
/// Loads and compiles a document with the specified category, consuming previously generated cache data and updating it if necessary.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <param name="cacheKind">The kind of cache data to be processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
return CompileDocument(specifier, category, null, cacheKind, ref cacheBytes, out cacheResult);
}
/// <summary>
/// Loads and compiles a document with the specified category and context callback, consuming previously generated cache data and updating it if necessary.
/// </summary>
/// <param name="specifier">A string specifying the document to be loaded and compiled.</param>
/// <param name="category">An optional category for the requested document.</param>
/// <param name="contextCallback">An optional context callback for the requested document.</param>
/// <param name="cacheKind">The kind of cache data to be processed.</param>
/// <param name="cacheBytes">Cache data for accelerated compilation.</param>
/// <param name="cacheResult">The cache data processing result for the operation.</param>
/// <returns>A compiled script that can be executed by multiple V8 script engine instances.</returns>
/// <remarks>
/// To be accepted, the cache data must have been generated for identical script code by
/// the same V8 build. If returned, the updated cache data can be stored externally and is
/// usable in other V8 script engines and application processes.
/// </remarks>
public V8Script CompileDocument(string specifier, DocumentCategory category, DocumentContextCallback contextCallback, V8CacheKind cacheKind, ref byte[] cacheBytes, out V8CacheResult cacheResult)
{
MiscHelpers.VerifyNonBlankArgument(specifier, nameof(specifier), "Invalid document specifier");
var document = DocumentSettings.LoadDocument(null, specifier, category, contextCallback);
return Compile(document.Info, document.GetTextContents(), cacheKind, ref cacheBytes, out cacheResult);
}
// 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
/// <c><see cref="ScriptEngine.Evaluate(string, bool, string)"/></c>.
/// </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 <c><see cref="Evaluate(V8Script)"/></c> 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>
/// Cancels any pending request to interrupt script execution.
/// </summary>
/// <remarks>
/// This method can be called safely from any thread.
/// </remarks>
/// <c><seealso cref="Interrupt"/></c>
public void CancelInterrupt()
{
VerifyNotDisposed();
proxy.CancelInterrupt();
}
/// <summary>
/// Returns memory usage information for the V8 runtime.
/// </summary>
/// <returns>A <c><see cref="V8RuntimeHeapInfo"/></c> object containing memory usage information for the V8 runtime.</returns>
public V8RuntimeHeapInfo GetRuntimeHeapInfo()
{
VerifyNotDisposed();
return proxy.GetIsolateHeapInfo();
}
/// <summary>
/// Begins collecting a new CPU profile.
/// </summary>
/// <param name="name">A name for the profile.</param>
/// <returns><c>True</c> if the profile was created successfully, <c>false</c> otherwise.</returns>
/// <remarks>
/// A V8 script engine can collect multiple CPU profiles simultaneously.
/// </remarks>
public bool BeginCpuProfile(string name)
{
return BeginCpuProfile(name, V8CpuProfileFlags.None);
}
/// <summary>
/// Begins collecting a new CPU profile with the specified options.
/// </summary>
/// <param name="name">A name for the profile.</param>
/// <param name="flags">Options for creating the profile.</param>
/// <returns><c>True</c> if the profile was created successfully, <c>false</c> otherwise.</returns>
/// <remarks>
/// A V8 script engine can collect multiple CPU profiles simultaneously.