-
-
Notifications
You must be signed in to change notification settings - Fork 184
Expand file tree
/
Copy pathJavaScriptEngine.java
More file actions
1610 lines (1421 loc) · 63.7 KB
/
JavaScriptEngine.java
File metadata and controls
1610 lines (1421 loc) · 63.7 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) 2002-2026 Gargoyle Software Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.htmlunit.javascript;
import static org.htmlunit.BrowserVersionFeatures.JS_ERROR_STACK_TRACE_LIMIT;
import static org.htmlunit.BrowserVersionFeatures.JS_WINDOW_INSTALL_TRIGGER_NULL;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Consumer;
import org.apache.commons.lang3.ObjectUtils.Null;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlunit.BrowserVersion;
import org.htmlunit.Page;
import org.htmlunit.ScriptException;
import org.htmlunit.WebAssert;
import org.htmlunit.WebClient;
import org.htmlunit.WebWindow;
import org.htmlunit.corejs.javascript.AbstractEcmaObjectOperations;
import org.htmlunit.corejs.javascript.BaseFunction;
import org.htmlunit.corejs.javascript.Callable;
import org.htmlunit.corejs.javascript.ClassDescriptor;
import org.htmlunit.corejs.javascript.Context;
import org.htmlunit.corejs.javascript.ContextAction;
import org.htmlunit.corejs.javascript.ContextFactory;
import org.htmlunit.corejs.javascript.EcmaError;
import org.htmlunit.corejs.javascript.Function;
import org.htmlunit.corejs.javascript.FunctionObject;
import org.htmlunit.corejs.javascript.JSFunction;
import org.htmlunit.corejs.javascript.JavaScriptException;
import org.htmlunit.corejs.javascript.NativeArray;
import org.htmlunit.corejs.javascript.NativeArrayIterator;
import org.htmlunit.corejs.javascript.NativeConsole;
import org.htmlunit.corejs.javascript.NativeObject;
import org.htmlunit.corejs.javascript.RhinoException;
import org.htmlunit.corejs.javascript.Script;
import org.htmlunit.corejs.javascript.ScriptRuntime;
import org.htmlunit.corejs.javascript.Scriptable;
import org.htmlunit.corejs.javascript.ScriptableObject;
import org.htmlunit.corejs.javascript.StackStyle;
import org.htmlunit.corejs.javascript.Symbol;
import org.htmlunit.corejs.javascript.SymbolKey;
import org.htmlunit.corejs.javascript.TopLevel;
import org.htmlunit.corejs.javascript.VarScope;
import org.htmlunit.corejs.javascript.WithScope;
import org.htmlunit.corejs.javascript.typedarrays.NativeArrayBuffer;
import org.htmlunit.corejs.javascript.typedarrays.NativeUint8Array;
import org.htmlunit.html.DomNode;
import org.htmlunit.html.HtmlElement;
import org.htmlunit.html.HtmlForm;
import org.htmlunit.html.HtmlPage;
import org.htmlunit.html.SubmittableElement;
import org.htmlunit.javascript.background.BackgroundJavaScriptFactory;
import org.htmlunit.javascript.background.JavaScriptExecutor;
import org.htmlunit.javascript.configuration.AbstractJavaScriptConfiguration;
import org.htmlunit.javascript.configuration.ClassConfiguration;
import org.htmlunit.javascript.configuration.ClassConfiguration.ConstantInfo;
import org.htmlunit.javascript.configuration.ClassConfiguration.PropertyInfo;
import org.htmlunit.javascript.configuration.JavaScriptConfiguration;
import org.htmlunit.javascript.configuration.ProxyAutoConfigJavaScriptConfiguration;
import org.htmlunit.javascript.host.ConsoleCustom;
import org.htmlunit.javascript.host.URLSearchParams;
import org.htmlunit.javascript.host.Window;
import org.htmlunit.javascript.host.WindowOrWorkerGlobalScope;
import org.htmlunit.javascript.host.dom.DOMException;
import org.htmlunit.javascript.host.html.HTMLElement;
import org.htmlunit.javascript.host.html.HTMLImageElement;
import org.htmlunit.javascript.host.html.HTMLOptionElement;
import org.htmlunit.javascript.host.intl.Intl;
import org.htmlunit.javascript.host.worker.WorkerGlobalScope;
import org.htmlunit.javascript.host.xml.FormData;
import org.htmlunit.javascript.polyfill.Polyfill;
import org.htmlunit.util.StringUtils;
/**
* A wrapper for the <a href="http://www.mozilla.org/rhino">Rhino JavaScript engine</a>
* that provides browser specific features.
*
* <p>Like all classes in this package, this class is not intended for direct use
* and may change without notice.</p>
*
* @author Mike Bowler
* @author Chen Jun
* @author David K. Taylor
* @author Chris Erskine
* @author Ben Curren
* @author David D. Kilzer
* @author Marc Guillemot
* @author Daniel Gredler
* @author Ahmed Ashour
* @author Amit Manjhi
* @author Ronald Brill
* @author Frank Danek
* @author Lai Quang Duong
* @author Sven Strickroth
*
* @see <a href="http://groups-beta.google.com/group/netscape.public.mozilla.jseng/browse_thread/thread/b4edac57329cf49f/069e9307ec89111f">
* Rhino and Java Browser</a>
*/
public class JavaScriptEngine implements AbstractJavaScriptEngine<Script> {
private static final Log LOG = LogFactory.getLog(JavaScriptEngine.class);
/** ScriptRuntime.emptyArgs. */
public static final Object[] EMPTY_ARGS = ScriptRuntime.emptyArgs;
/** org.htmlunit.corejs.javascript.Undefined.instance. */
public static final Object UNDEFINED = org.htmlunit.corejs.javascript.Undefined.instance;
private WebClient webClient_;
private HtmlUnitContextFactory contextFactory_;
private JavaScriptConfiguration jsConfig_;
private transient ThreadLocal<Boolean> javaScriptRunning_;
private transient ThreadLocal<List<PostponedAction>> postponedActions_;
private transient boolean holdPostponedActions_;
private transient boolean shutdownPending_;
/** The JavaScriptExecutor corresponding to all windows of this Web client */
private transient JavaScriptExecutor javaScriptExecutor_;
/**
* Key used to place the {@link HtmlPage} for which the JavaScript code is executed
* as thread local attribute in current context.
*/
public static final String KEY_STARTING_PAGE = "startingPage";
/**
* Creates an instance for the specified {@link WebClient}.
*
* @param webClient the client that will own this engine
*/
public JavaScriptEngine(final WebClient webClient) {
if (webClient == null) {
throw new IllegalArgumentException("JavaScriptEngine ctor requires a webClient");
}
webClient_ = webClient;
contextFactory_ = new HtmlUnitContextFactory(webClient);
initTransientFields();
jsConfig_ = JavaScriptConfiguration.getInstance(webClient.getBrowserVersion());
RhinoException.setStackStyle(StackStyle.MOZILLA_LF);
}
/**
* Returns the web client that this engine is associated with.
* @return the web client
*/
private WebClient getWebClient() {
return webClient_;
}
/**
* {@inheritDoc}
*/
@Override
public HtmlUnitContextFactory getContextFactory() {
return contextFactory_;
}
/**
* Performs initialization for the given webWindow.
* @param webWindow the web window to initialize for
*/
@Override
public void initialize(final WebWindow webWindow, final Page page) {
WebAssert.notNull("webWindow", webWindow);
if (shutdownPending_) {
return;
}
getContextFactory().call(cx -> {
try {
init(webWindow, page, cx);
}
catch (final Exception e) {
LOG.error("Exception while initializing JavaScript for the page", e);
throw new ScriptException(null, e); // BUG: null is not useful.
}
return null;
});
}
/**
* Returns the JavaScriptExecutor.
* @return the JavaScriptExecutor or null if javascript is disabled
* or no executor was required so far.
*/
public JavaScriptExecutor getJavaScriptExecutor() {
return javaScriptExecutor_;
}
/**
* Initializes all the JS stuff for the window.
* @param webWindow the web window
* @param cx the current context
* @throws Exception if something goes wrong
*/
private void init(final WebWindow webWindow, final Page page, final Context cx) throws Exception {
final WebClient webClient = getWebClient();
final BrowserVersion browserVersion = webClient.getBrowserVersion();
final Window jsWindow = new Window();
jsWindow.setClassName("Window");
final TopLevel scope = cx.initSafeStandardObjects(new TopLevel(jsWindow));
jsWindow.setParentScope(scope);
configureRhino(webClient, browserVersion, scope, jsWindow);
final Map<Class<? extends Scriptable>, Scriptable> prototypes = new HashMap<>();
final Map<String, Scriptable> prototypesPerJSName = new HashMap<>();
final ClassConfiguration windowConfig = jsConfig_.getWindowClassConfiguration();
final FunctionObject functionObject = new FunctionObject(jsWindow.getClassName(), windowConfig.getJsConstructor().getValue(), scope);
ScriptableObject.defineProperty(jsWindow, "constructor", functionObject,
ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
configureConstantsPropertiesAndFunctions(windowConfig, scope, jsWindow);
final HtmlUnitScriptable windowPrototype = configureClass(windowConfig, scope);
jsWindow.setPrototype(windowPrototype);
prototypes.put(windowConfig.getHostClass(), windowPrototype);
prototypesPerJSName.put(windowConfig.getClassName(), windowPrototype);
configureGlobalThis(scope, jsWindow, windowConfig, functionObject, jsConfig_, browserVersion, prototypes, prototypesPerJSName);
// TODO remove the cast
URLSearchParams.NativeParamsIterator.init(cx, scope, "URLSearchParams Iterator");
FormData.FormDataIterator.init(cx, scope, "FormData Iterator");
// strange but this is the reality for browsers
// because there will be still some sites using this for browser detection the property is
// set to null
// https://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browsers
// https://bugzilla.mozilla.org/show_bug.cgi?id=1442035
if (browserVersion.hasFeature(JS_WINDOW_INSTALL_TRIGGER_NULL)) {
jsWindow.put("InstallTrigger", jsWindow, null);
}
// special handling for image/option
final Method imageCtor = HTMLImageElement.class.getDeclaredMethod("jsConstructorImage");
additionalCtor(scope, jsWindow, prototypesPerJSName.get("HTMLImageElement"), imageCtor, "Image", "HTMLImageElement");
final Method optionCtor = HTMLOptionElement.class.getDeclaredMethod("jsConstructorOption",
Object.class, String.class, boolean.class, boolean.class);
additionalCtor(scope, jsWindow, prototypesPerJSName.get("HTMLOptionElement"), optionCtor, "Option", "HTMLOptionElement");
if (!webClient.getOptions().isWebSocketEnabled()) {
deleteProperties(jsWindow, "WebSocket");
}
jsWindow.setPrototypes(prototypes);
jsWindow.initialize(scope, webWindow, page);
applyPolyfills(webClient, browserVersion, cx, scope, jsWindow);
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
*
* @param scope the scope
* @param globalThis the globalThis to set up
* @param scopeConfig the {@link ClassConfiguration} that is used for the scope
* @param scopeContructorFunctionObject the (already registered) ctor
* @param jsConfig the complete jsConfig
* @param browserVersion the {@link BrowserVersion}
* @param prototypes map of prototypes
* @param prototypesPerJSName map of prototypes with the class name as key
* @throws Exception in case of error
*/
public static void configureGlobalThis(
final TopLevel scope,
final HtmlUnitScriptable globalThis,
final ClassConfiguration scopeConfig,
final FunctionObject scopeContructorFunctionObject,
final AbstractJavaScriptConfiguration jsConfig,
final BrowserVersion browserVersion,
final Map<Class<? extends Scriptable>, Scriptable> prototypes,
final Map<String, Scriptable> prototypesPerJSName) throws Exception {
final Scriptable objectPrototype = ScriptableObject.getObjectPrototype(scope);
final Map<String, Function> ctorPrototypesPerJSName = new HashMap<>();
for (final ClassConfiguration config : jsConfig.getAll()) {
final String jsClassName = config.getClassName();
Scriptable prototype = prototypesPerJSName.get(jsClassName);
final String extendedClassName =
StringUtils.isEmptyOrNull(config.getExtendedClassName()) ? null : config.getExtendedClassName();
// setup the prototypes
if (config == scopeConfig) {
if (extendedClassName == null) {
prototype.setPrototype(objectPrototype);
}
else {
prototype.setPrototype(prototypesPerJSName.get(extendedClassName));
}
// setup constructors
addAsConstructorAndAlias(scopeContructorFunctionObject, scope, globalThis, prototype, config);
configureConstantsStaticPropertiesAndStaticFunctions(config, scope, scopeContructorFunctionObject);
// adjust prototype if needed
if (extendedClassName != null) {
scopeContructorFunctionObject.setPrototype(ctorPrototypesPerJSName.get(extendedClassName));
}
}
else if (config.getDescriptor() != null) {
// Descriptor-based path (ClassDescriptor API)
final HtmlUnitScriptable classPrototype = config.getHostClass().getDeclaredConstructor().newInstance();
classPrototype.setParentScope(scope);
classPrototype.setClassName(jsClassName);
// buildConstructor wires up all methods/properties, sets proto.__proto__ to Object.prototype,
// and registers the constructor in the scope (which routes to globalThis via TopLevel.put)
final JSFunction ctor = config.getDescriptor().buildConstructor(
Context.getCurrentContext(), scope, classPrototype, false);
ctorPrototypesPerJSName.put(jsClassName, ctor);
// Override proto chain after buildConstructor (it defaults to Object.prototype)
if (extendedClassName != null) {
classPrototype.setPrototype(prototypesPerJSName.get(extendedClassName));
ctor.setPrototype(ctorPrototypesPerJSName.get(extendedClassName));
}
prototypes.put(config.getHostClass(), classPrototype);
prototypesPerJSName.put(jsClassName, classPrototype);
// Add Symbol.toStringTag to match the annotation-based setup in process()
ScriptableObject.defineProperty(classPrototype, SymbolKey.TO_STRING_TAG, jsClassName,
ScriptableObject.DONTENUM | ScriptableObject.READONLY);
if (!config.isJsObject()) {
// buildConstructor registers the ctor in the scope (→ globalThis), so remove it
globalThis.delete(jsClassName);
}
final String alias = config.getJsConstructorAlias();
if (alias != null) {
ScriptableObject.defineProperty(globalThis, alias, ctor, ScriptableObject.DONTENUM);
}
}
else {
final HtmlUnitScriptable classPrototype = configureClass(config, scope);
prototypes.put(config.getHostClass(), classPrototype);
prototypesPerJSName.put(jsClassName, classPrototype);
prototype = classPrototype;
if (extendedClassName == null) {
classPrototype.setPrototype(objectPrototype);
}
else {
classPrototype.setPrototype(prototypesPerJSName.get(extendedClassName));
}
// setup constructors
if (prototype != null) {
final Map.Entry<String, Member> jsConstructor = config.getJsConstructor();
if (jsConstructor == null) {
final HtmlUnitScriptable constructor = config.getHostClass().getDeclaredConstructor().newInstance();
constructor.setClassName(jsClassName);
defineConstructor(scope, prototype, constructor);
configureConstantsStaticPropertiesAndStaticFunctions(config, scope, constructor);
if (config.isJsObject()) {
globalThis.defineProperty(jsClassName, constructor, ScriptableObject.DONTENUM);
}
}
else {
final FunctionObject function = new FunctionObject(jsConstructor.getKey(), jsConstructor.getValue(), scope);
ctorPrototypesPerJSName.put(jsClassName, function);
addAsConstructorAndAlias(function, scope, globalThis, prototype, config);
configureConstantsStaticPropertiesAndStaticFunctions(config, scope, function);
if (!config.isJsObject()) {
// addAsConstructorAndAlias(..) calls addAsConstructor() from core-js
// addAsConstructor(..) registeres the ctor in the scope already
// therefore we have to remove here
globalThis.delete(prototype.getClassName());
}
// adjust prototype if needed
if (extendedClassName != null) {
function.setPrototype(ctorPrototypesPerJSName.get(extendedClassName));
}
}
}
}
}
}
private static void addAsConstructorAndAlias(final FunctionObject function,
final VarScope scope,
final HtmlUnitScriptable destination,
final Scriptable prototype,
final ClassConfiguration config) {
try {
function.addAsConstructor(scope, prototype, ScriptableObject.DONTENUM);
final String alias = config.getJsConstructorAlias();
if (alias != null) {
ScriptableObject.defineProperty(destination, alias, function, ScriptableObject.DONTENUM);
}
}
catch (final Exception e) {
// TODO see issue #1897
if (LOG.isWarnEnabled()) {
final String newline = System.lineSeparator();
LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
+ e.getMessage() + newline
+ "prototype: " + prototype.getClassName(), e);
}
}
}
private static void additionalCtor(final VarScope scope, final Window window, final Scriptable proto,
final Method ctorMethod, final String prop, final String clazzName) throws Exception {
final FunctionObject function = new FunctionObject(prop, ctorMethod, scope);
final Object prototypeProperty = ScriptableObject.getProperty(window, clazzName);
try {
function.addAsConstructor(scope, proto, ScriptableObject.DONTENUM);
}
catch (final Exception e) {
// TODO see issue #1897
if (LOG.isWarnEnabled()) {
final String newline = System.lineSeparator();
LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
+ e.getMessage() + newline
+ "prototype: " + proto.getClassName(), e);
}
}
ScriptableObject.defineProperty(window, prop, function, ScriptableObject.DONTENUM);
ScriptableObject.defineProperty(window, clazzName, prototypeProperty, ScriptableObject.DONTENUM);
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
*
* @param webClient the WebClient
* @param browserVersion the BrowserVersion
* @param scope the scope
* @param globalThis the window or the DedicatedWorkerGlobalScope
*/
public static void configureRhino(final WebClient webClient, final BrowserVersion browserVersion,
final TopLevel scope, final HtmlUnitScriptable globalThis) {
// this should be like
// NativeConsole.init(scope, globalThis, false, webClient.getWebConsole());
// but so far both objects are the same
NativeConsole.init(scope, false, webClient.getWebConsole());
// https://developer.mozilla.org/en-US/docs/Web/API/console/timeStamp_static
// this is not standard and therefore not in Rhino
final ScriptableObject console = (ScriptableObject) ScriptableObject.getProperty(globalThis, "console");
console.defineFunctionProperties(scope, new String[] {"timeStamp"}, ConsoleCustom.class, ScriptableObject.DONTENUM);
// remove some objects, that Rhino defines in top scope but that we don't want
deleteProperties(globalThis, "Continuation", "StopIteration", "uneval", "global", "__GeneratorFunction");
// Rhino defines too many methods for us, particularly since implementation of ECMAScript5
final ScriptableObject stringPrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "String");
deleteProperties(stringPrototype, "equals", "equalsIgnoreCase", "toSource");
final ScriptableObject numberPrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "Number");
deleteProperties(numberPrototype, "toSource");
final ScriptableObject datePrototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, "Date");
deleteProperties(datePrototype, "toSource");
removePrototypeProperties(scope, "Object", "toSource");
removePrototypeProperties(scope, "Array", "toSource");
removePrototypeProperties(scope, "Function", "toSource");
deleteProperties(globalThis, "isXMLName");
NativeFunctionToStringFunction.installFix(scope, browserVersion);
final ScriptableObject errorObject = (ScriptableObject) ScriptableObject.getProperty(globalThis, "Error");
if (browserVersion.hasFeature(JS_ERROR_STACK_TRACE_LIMIT)) {
errorObject.defineProperty("stackTraceLimit", 10, ScriptableObject.EMPTY);
}
else {
ScriptableObject.deleteProperty(errorObject, "stackTraceLimit");
}
// add Intl
Intl.init(scope, globalThis, browserVersion);
}
/**
* <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
*
* @param webClient the WebClient
* @param browserVersion the BrowserVersion
* @param context the current context
* @param scope the scope
* @param scriptable the window or the DedicatedWorkerGlobalScope
* @throws IOException in case of problems
*/
public static void applyPolyfills(final WebClient webClient, final BrowserVersion browserVersion,
final Context context, final VarScope scope, final HtmlUnitScriptable scriptable) throws IOException {
if (webClient.getOptions().isFetchPolyfillEnabled()) {
Polyfill.getFetchPolyfill().apply(context, scope, scriptable);
}
}
private static void defineConstructor(final VarScope scope,
final Scriptable prototype, final ScriptableObject constructor) {
constructor.setParentScope(scope);
try {
ScriptableObject.defineProperty(prototype, "constructor", constructor,
ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
catch (final Exception e) {
// TODO see issue #1897
if (LOG.isWarnEnabled()) {
final String newline = System.lineSeparator();
LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
+ e.getMessage() + newline
+ "prototype: " + prototype.getClassName(), e);
}
}
try {
ScriptableObject.defineProperty(constructor, "prototype", prototype,
ScriptableObject.DONTENUM | ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
catch (final Exception e) {
// TODO see issue #1897
if (LOG.isWarnEnabled()) {
final String newline = System.lineSeparator();
LOG.warn("Error during JavaScriptEngine.init(WebWindow, Context)" + newline
+ e.getMessage() + newline
+ "prototype: " + prototype.getClassName(), e);
}
}
}
/**
* Deletes the properties with the provided names.
* @param destination the object from which the properties are to be removed
* @param propertiesToDelete the list of property names
*/
private static void deleteProperties(final Scriptable destination, final String... propertiesToDelete) {
for (final String property : propertiesToDelete) {
destination.delete(property);
}
}
/**
* Removes prototype properties.
* @param scope the scope to search for the prototype
* @param className the class for which properties should be removed
* @param properties the properties to remove
*/
private static void removePrototypeProperties(final VarScope scope, final String className,
final String... properties) {
final ScriptableObject prototype = (ScriptableObject) ScriptableObject.getClassPrototype(scope, className);
for (final String property : properties) {
prototype.delete(property);
}
}
/**
* Configures the specified class for access via JavaScript.
* @param config the configuration settings for the class to be configured
* @param scope the scope to configure within which to configure the class
* @throws InstantiationException if the new class cannot be instantiated
* @throws IllegalAccessException if we don't have access to create the new instance
* @return the created prototype
* @throws Exception in case of errors
*/
public static HtmlUnitScriptable configureClass(final ClassConfiguration config,
final TopLevel scope)
throws Exception {
final HtmlUnitScriptable prototype = config.getHostClass().getDeclaredConstructor().newInstance();
prototype.setParentScope(scope);
prototype.setClassName(config.getClassName());
configureConstantsPropertiesAndFunctions(config, scope, prototype);
return prototype;
}
/**
* Configures constants, static properties and static functions on the object.
* @param config the configuration for the object
* @param scriptable the object to configure
*/
private static void configureConstantsStaticPropertiesAndStaticFunctions(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
configureConstants(config, scriptable);
configureStaticProperties(config, scope, scriptable);
configureStaticFunctions(config, scope, scriptable);
}
/**
* Configures constants, properties and functions on the object.
* @param config the configuration for the object
* @param scope the scope
* @param scriptable the object to configure
*/
private static void configureConstantsPropertiesAndFunctions(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
configureConstants(config, scriptable);
configureProperties(config, scope, scriptable);
configureFunctions(config, scope, scriptable);
configureSymbolConstants(config, scriptable);
configureSymbols(config, scope, scriptable);
}
private static void configureFunctions(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
// the functions
final Map<String, Method> functionMap = config.getFunctionMap();
if (functionMap != null) {
for (final Entry<String, Method> functionInfo : functionMap.entrySet()) {
final String functionName = functionInfo.getKey();
final Method method = functionInfo.getValue();
final FunctionObject functionObject = new FunctionObject(functionName, method, scope);
scriptable.defineProperty(functionName, functionObject, ScriptableObject.EMPTY);
}
}
}
private static void configureConstants(final ClassConfiguration config, final ScriptableObject scriptable) {
final List<ConstantInfo> constants = config.getConstants();
if (constants != null) {
for (final ConstantInfo constantInfo : constants) {
scriptable.defineProperty(constantInfo.getName(), constantInfo.getValue(), constantInfo.getFlag());
}
}
}
private static void configureProperties(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
final Map<String, PropertyInfo> propertyMap = config.getPropertyMap();
if (propertyMap != null) {
for (final Entry<String, PropertyInfo> propertyEntry : propertyMap.entrySet()) {
final PropertyInfo info = propertyEntry.getValue();
final Method readMethod = info.getReadMethod();
final Method writeMethod = info.getWriteMethod();
scriptable.defineProperty(scope, propertyEntry.getKey(), null, readMethod, writeMethod, ScriptableObject.EMPTY);
}
}
}
private static void configureStaticProperties(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
final Map<String, PropertyInfo> staticPropertyMap = config.getStaticPropertyMap();
if (staticPropertyMap != null) {
for (final Entry<String, ClassConfiguration.PropertyInfo> propertyEntry : staticPropertyMap.entrySet()) {
final String propertyName = propertyEntry.getKey();
final Method readMethod = propertyEntry.getValue().getReadMethod();
final Method writeMethod = propertyEntry.getValue().getWriteMethod();
final int flag = ScriptableObject.EMPTY;
scriptable.defineProperty(scope, propertyName, null, readMethod, writeMethod, flag);
}
}
}
private static void configureStaticFunctions(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
final Map<String, Method> staticFunctionMap = config.getStaticFunctionMap();
if (staticFunctionMap != null) {
for (final Entry<String, Method> staticFunctionInfo : staticFunctionMap.entrySet()) {
final String functionName = staticFunctionInfo.getKey();
final Method method = staticFunctionInfo.getValue();
final FunctionObject staticFunctionObject = new FunctionObject(functionName, method, scope);
scriptable.defineProperty(functionName, staticFunctionObject, ScriptableObject.EMPTY);
}
}
}
private static void configureSymbolConstants(final ClassConfiguration config, final ScriptableObject scriptable) {
final Map<Symbol, String> symbolConstantMap = config.getSymbolConstantMap();
if (symbolConstantMap != null) {
for (final Entry<Symbol, String> symbolInfo : symbolConstantMap.entrySet()) {
scriptable.defineProperty(symbolInfo.getKey(), symbolInfo.getValue(), ScriptableObject.DONTENUM | ScriptableObject.READONLY);
}
}
}
private static void configureSymbols(final ClassConfiguration config,
final TopLevel scope, final ScriptableObject scriptable) {
final Map<Symbol, Method> symbolMap = config.getSymbolMap();
if (symbolMap != null) {
for (final Entry<Symbol, Method> symbolInfo : symbolMap.entrySet()) {
final Symbol symbol = symbolInfo.getKey();
final Method method = symbolInfo.getValue();
final String methodName = method.getName();
final Callable symbolFunction;
// a bit strange but this avoid the has call and therefore saves one lookup
final Object property = scriptable.get(methodName, scriptable);
if (property == Scriptable.NOT_FOUND) {
symbolFunction = new FunctionObject(methodName, method, scope);
}
else {
symbolFunction = (Callable) property;
}
scriptable.defineProperty(symbol, symbolFunction, ScriptableObject.DONTENUM);
}
}
}
/**
* Register WebWindow with the JavaScriptExecutor.
* @param webWindow the WebWindow to be registered.
*/
@Override
public synchronized void registerWindowAndMaybeStartEventLoop(final WebWindow webWindow) {
if (shutdownPending_) {
return;
}
final WebClient webClient = getWebClient();
if (webClient != null) {
if (javaScriptExecutor_ == null) {
javaScriptExecutor_ = BackgroundJavaScriptFactory.theFactory().createJavaScriptExecutor(webClient);
}
javaScriptExecutor_.addWindow(webWindow);
}
}
/**
* {@inheritDoc}
*/
@Override
public void prepareShutdown() {
shutdownPending_ = true;
}
/**
* Shutdown the JavaScriptEngine.
*/
@Override
public void shutdown() {
webClient_ = null;
contextFactory_ = null;
jsConfig_ = null;
if (javaScriptExecutor_ != null) {
javaScriptExecutor_.shutdown();
javaScriptExecutor_ = null;
}
if (postponedActions_ != null) {
postponedActions_.remove();
}
if (javaScriptRunning_ != null) {
javaScriptRunning_.remove();
}
holdPostponedActions_ = false;
}
/**
* {@inheritDoc}
*/
@Override
public Script compile(final HtmlPage owningPage, final VarScope scope, final String sourceCode,
final String sourceName, final int startLine) {
WebAssert.notNull("sourceCode", sourceCode);
if (LOG.isTraceEnabled()) {
final String newline = System.lineSeparator();
LOG.trace("Javascript compile " + sourceName + newline + sourceCode + newline);
}
final HtmlUnitCompileContextAction action = new HtmlUnitCompileContextAction(owningPage, sourceCode, sourceName, startLine);
return (Script) getContextFactory().callSecured(action, owningPage);
}
/**
* Forwards this to the {@link HtmlUnitContextFactory} but with checking shutdown handling.
*
* @param <T> return type of the action
* @param action the contextAction
* @param page the page
* @return the result of the call
*/
public final <T> T callSecured(final ContextAction<T> action, final HtmlPage page) {
if (shutdownPending_ || webClient_ == null) {
// shutdown was already called
return null;
}
return getContextFactory().callSecured(action, page);
}
/**
* {@inheritDoc}
*/
@Override
public Object execute(final HtmlPage page,
final VarScope scope,
final String sourceCode,
final String sourceName,
final int startLine) {
final Script script = compile(page, scope, sourceCode, sourceName, startLine);
if (script == null) {
// happens with syntax error + throwExceptionOnScriptError = false
return null;
}
return execute(page, scope, script);
}
/**
* {@inheritDoc}
*/
@Override
public Object execute(final HtmlPage page, final VarScope scope, final Script script) {
if (shutdownPending_ || webClient_ == null) {
// shutdown was already called
return null;
}
final HtmlUnitContextAction action = new HtmlUnitContextAction(page) {
@Override
public Object doRun(final Context cx) {
return script.exec(cx, scope, ScriptableObject.getTopLevelScope(scope).getGlobalThis());
}
@Override
protected String getSourceCode(final Context cx) {
return null;
}
};
return getContextFactory().callSecured(action, page);
}
/**
* Calls a JavaScript function and return the result.
* @param page the page
* @param javaScriptFunction the function to call
* @param thisObject the this object for class method calls
* @param args the list of arguments to pass to the function
* @param node the HTML element that will act as the context
* @return the result of the function call
*/
public Object callFunction(
final HtmlPage page,
final Function javaScriptFunction,
final Scriptable thisObject,
final Object[] args,
final DomNode node) {
VarScope scope = ScriptableObject.getTopLevelScope(thisObject.getParentScope());
if (node != null && node instanceof HtmlElement htmlElement) {
final HTMLElement elem = htmlElement.getScriptableObject();
scope = new WithScope(scope, elem.getOwnerDocument());
if (htmlElement instanceof SubmittableElement) {
final HtmlForm enclosingForm = htmlElement.getEnclosingForm();
if (enclosingForm != null) {
scope = new WithScope(scope, enclosingForm.getScriptableObject());
}
}
scope = new WithScope(scope, node.getScriptableObject());
}
return callFunction(page, javaScriptFunction, scope, thisObject, args);
}
/**
* Calls the given function taking care of synchronization issues.
* @param page the interactive page that caused this script to executed
* @param function the JavaScript function to execute
* @param scope the execution scope
* @param thisObject the 'this' object
* @param args the function's arguments
* @return the function result
*/
public Object callFunction(final HtmlPage page, final Function function,
final VarScope scope, final Scriptable thisObject, final Object[] args) {
if (shutdownPending_ || webClient_ == null) {
// shutdown was already called
return null;
}
final HtmlUnitContextAction action = new HtmlUnitContextAction(page) {
@Override
public Object doRun(final Context cx) {
if (ScriptRuntime.hasTopCall(cx)) {
return function.call(cx, scope, thisObject, args);
}
return ScriptRuntime.doTopCall(function, cx, scope, thisObject, args, cx.isStrictMode());
}
@Override
protected String getSourceCode(final Context cx) {
return cx.decompileFunction(function, 2);
}
};
return getContextFactory().callSecured(action, page);
}
/**
* Indicates if JavaScript is running in current thread.
* <p>This allows code to know if their own evaluation has been triggered by some JS code.
* @return {@code true} if JavaScript is running
*/
@Override
public boolean isScriptRunning() {
return Boolean.TRUE.equals(javaScriptRunning_.get());
}
/**
* Special ContextAction only for compiling. This reduces some code and avoid
* some calls.
*/
private final class HtmlUnitCompileContextAction implements ContextAction<Object> {
private final HtmlPage page_;
private final String sourceCode_;
private final String sourceName_;
private final int startLine_;
HtmlUnitCompileContextAction(final HtmlPage page, final String sourceCode, final String sourceName, final int startLine) {
page_ = page;
sourceCode_ = sourceCode;
sourceName_ = sourceName;
startLine_ = startLine;
}
@Override
public Object run(final Context cx) {
try {
final Object response;
cx.putThreadLocal(KEY_STARTING_PAGE, page_);
synchronized (page_) { // 2 scripts can't be executed in parallel for one page
if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
return null; // page has been unloaded
}
response = cx.compileString(sourceCode_, sourceName_, startLine_, null);
}
return response;
}
catch (final Exception e) {
handleJavaScriptException(new ScriptException(page_, e, sourceCode_), true);
return null;
}
catch (final TimeoutError e) {
handleJavaScriptTimeoutError(page_, e);
return null;
}
}
}
/**
* Facility for ContextAction usage.
* ContextAction should be preferred because according to Rhino doc it
* "guarantees proper association of Context instances with the current thread and is faster".
*/
private abstract class HtmlUnitContextAction implements ContextAction<Object> {
private final HtmlPage page_;
HtmlUnitContextAction(final HtmlPage page) {
page_ = page;
}
@Override
public final Object run(final Context cx) {
final Boolean javaScriptAlreadyRunning = javaScriptRunning_.get();
javaScriptRunning_.set(Boolean.TRUE);
try {
final Object response;
synchronized (page_) { // 2 scripts can't be executed in parallel for one page
if (page_ != page_.getEnclosingWindow().getEnclosedPage()) {
return null; // page has been unloaded
}