forked from classilla/tenfourfox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjsscript.cpp
More file actions
4590 lines (3986 loc) · 149 KB
/
jsscript.cpp
File metadata and controls
4590 lines (3986 loc) · 149 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
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* JS script operations.
*/
#include "jsscriptinlines.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/MathAlgorithms.h"
#include "mozilla/MemoryReporting.h"
#include "mozilla/PodOperations.h"
#include "mozilla/Vector.h"
#include <algorithm>
#include <string.h>
#include "jsapi.h"
#include "jsatom.h"
#include "jscntxt.h"
#include "jsfun.h"
#include "jsgc.h"
#include "jsobj.h"
#include "jsopcode.h"
#include "jsprf.h"
#include "jstypes.h"
#include "jsutil.h"
#include "jswrapper.h"
#include "frontend/BytecodeCompiler.h"
#include "frontend/BytecodeEmitter.h"
#include "frontend/SharedContext.h"
#include "gc/Marking.h"
#include "jit/BaselineJIT.h"
#include "jit/Ion.h"
#include "jit/IonCode.h"
#include "js/MemoryMetrics.h"
#include "js/Utility.h"
#include "vm/ArgumentsObject.h"
#include "vm/Compression.h"
#include "vm/Debugger.h"
#include "vm/Opcodes.h"
#include "vm/SelfHosting.h"
#include "vm/Shape.h"
#include "vm/Xdr.h"
#include "jsfuninlines.h"
#include "jsobjinlines.h"
#include "vm/ScopeObject-inl.h"
#include "vm/Stack-inl.h"
using namespace js;
using namespace js::gc;
using namespace js::frontend;
using mozilla::PodCopy;
using mozilla::PodZero;
using mozilla::RotateLeft;
static BindingIter
GetBinding(HandleScript script, HandlePropertyName name)
{
BindingIter bi(script);
while (bi->name() != name)
bi++;
return bi;
}
/* static */ BindingIter
Bindings::argumentsBinding(ExclusiveContext* cx, HandleScript script)
{
return GetBinding(script, cx->names().arguments);
}
/* static */ BindingIter
Bindings::thisBinding(ExclusiveContext* cx, HandleScript script)
{
return GetBinding(script, cx->names().dotThis);
}
bool
Bindings::initWithTemporaryStorage(ExclusiveContext* cx, MutableHandle<Bindings> self,
uint32_t numArgs, uint32_t numVars,
uint32_t numBodyLevelLexicals, uint32_t numBlockScoped,
uint32_t numUnaliasedVars, uint32_t numUnaliasedBodyLevelLexicals,
const Binding* bindingArray, bool isModule /* = false */)
{
MOZ_ASSERT(!self.callObjShape());
MOZ_ASSERT(self.bindingArrayUsingTemporaryStorage());
MOZ_ASSERT(!self.bindingArray());
MOZ_ASSERT(!(uintptr_t(bindingArray) & TEMPORARY_STORAGE_BIT));
MOZ_ASSERT(numArgs <= ARGC_LIMIT);
MOZ_ASSERT(numVars <= LOCALNO_LIMIT);
MOZ_ASSERT(numBlockScoped <= LOCALNO_LIMIT);
MOZ_ASSERT(numBodyLevelLexicals <= LOCALNO_LIMIT);
mozilla::DebugOnly<uint64_t> totalSlots = uint64_t(numVars) +
uint64_t(numBodyLevelLexicals) +
uint64_t(numBlockScoped);
MOZ_ASSERT(totalSlots <= LOCALNO_LIMIT);
MOZ_ASSERT(UINT32_MAX - numArgs >= totalSlots);
MOZ_ASSERT(numUnaliasedVars <= numVars);
MOZ_ASSERT(numUnaliasedBodyLevelLexicals <= numBodyLevelLexicals);
self.setBindingArray(bindingArray, TEMPORARY_STORAGE_BIT);
self.setNumArgs(numArgs);
self.setNumVars(numVars);
self.setNumBodyLevelLexicals(numBodyLevelLexicals);
self.setNumBlockScoped(numBlockScoped);
self.setNumUnaliasedVars(numUnaliasedVars);
self.setNumUnaliasedBodyLevelLexicals(numUnaliasedBodyLevelLexicals);
// Get the initial shape to use when creating CallObjects for this script.
// After creation, a CallObject's shape may change completely (via direct eval() or
// other operations that mutate the lexical scope). However, since the
// lexical bindings added to the initial shape are permanent and the
// allocKind/nfixed of a CallObject cannot change, one may assume that the
// slot location (whether in the fixed or dynamic slots) of a variable is
// the same as in the initial shape. (This is assumed by the interpreter and
// JITs when interpreting/compiling aliasedvar ops.)
// Since unaliased variables are, by definition, only accessed by local
// operations and never through the scope chain, only give shapes to
// aliased variables. While the debugger may observe any scope object at
// any time, such accesses are mediated by DebugScopeProxy (see
// DebugScopeProxy::handleUnaliasedAccess).
uint32_t nslots = CallObject::RESERVED_SLOTS;
// Unless there are aliased body-level lexical bindings at all, set the
// begin index to an impossible slot number.
uint32_t aliasedBodyLevelLexicalBegin = LOCALNO_LIMIT;
for (BindingIter bi(self); bi; bi++) {
if (bi->aliased()) {
// Per ES6, lexical bindings cannot be accessed until
// initialized. Remember the first aliased slot that is a
// body-level lexical, so that they may be initialized to sentinel
// magic values.
if (numBodyLevelLexicals > 0 &&
nslots < aliasedBodyLevelLexicalBegin &&
bi.isBodyLevelLexical() &&
bi.localIndex() >= numVars)
{
aliasedBodyLevelLexicalBegin = nslots;
}
nslots++;
}
}
self.setAliasedBodyLevelLexicalBegin(aliasedBodyLevelLexicalBegin);
// Put as many of nslots inline into the object header as possible.
uint32_t nfixed = gc::GetGCKindSlots(gc::GetGCObjectKind(nslots));
// Start with the empty shape and then append one shape per aliased binding.
const Class* cls = isModule ? &ModuleEnvironmentObject::class_ : &CallObject::class_;
uint32_t baseShapeFlags = BaseShape::QUALIFIED_VAROBJ | BaseShape::DELEGATE;
if (isModule)
baseShapeFlags |= BaseShape::NOT_EXTENSIBLE; // Module code is always strict.
RootedShape shape(cx,
EmptyShape::getInitialShape(cx, cls, TaggedProto(nullptr), nfixed, baseShapeFlags));
if (!shape)
return false;
#ifdef DEBUG
HashSet<PropertyName*> added(cx);
if (!added.init()) {
ReportOutOfMemory(cx);
return false;
}
#endif
uint32_t slot = CallObject::RESERVED_SLOTS;
for (BindingIter bi(self); bi; bi++) {
MOZ_ASSERT_IF(isModule, bi->aliased());
if (!bi->aliased())
continue;
#ifdef DEBUG
// The caller ensures no duplicate aliased names.
MOZ_ASSERT(!added.has(bi->name()));
if (!added.put(bi->name())) {
ReportOutOfMemory(cx);
return false;
}
#endif
StackBaseShape stackBase(cx, cls, baseShapeFlags);
UnownedBaseShape* base = BaseShape::getUnowned(cx, stackBase);
if (!base)
return false;
unsigned attrs = JSPROP_PERMANENT |
JSPROP_ENUMERATE |
(bi->kind() == Binding::CONSTANT ? JSPROP_READONLY : 0);
Rooted<StackShape> child(cx, StackShape(base, NameToId(bi->name()), slot, attrs, 0));
shape = cx->compartment()->propertyTree.getChild(cx, shape, child);
if (!shape)
return false;
MOZ_ASSERT(slot < nslots);
slot++;
}
MOZ_ASSERT(slot == nslots);
MOZ_ASSERT(!shape->inDictionary());
self.setCallObjShape(shape);
return true;
}
bool
Bindings::initTrivial(ExclusiveContext* cx)
{
Shape* shape = EmptyShape::getInitialShape(cx, &CallObject::class_, TaggedProto(nullptr),
CallObject::RESERVED_SLOTS,
BaseShape::QUALIFIED_VAROBJ | BaseShape::DELEGATE);
if (!shape)
return false;
callObjShape_.init(shape);
return true;
}
uint8_t*
Bindings::switchToScriptStorage(Binding* newBindingArray)
{
MOZ_ASSERT(bindingArrayUsingTemporaryStorage());
MOZ_ASSERT(!(uintptr_t(newBindingArray) & TEMPORARY_STORAGE_BIT));
if (count() > 0)
PodCopy(newBindingArray, bindingArray(), count());
bindingArrayAndFlag_ = uintptr_t(newBindingArray);
return reinterpret_cast<uint8_t*>(newBindingArray + count());
}
/* static */ bool
Bindings::clone(JSContext* cx, MutableHandle<Bindings> self,
uint8_t* dstScriptData, HandleScript srcScript)
{
/* The clone has the same bindingArray_ offset as 'src'. */
Handle<Bindings> src = Handle<Bindings>::fromMarkedLocation(&srcScript->bindings);
ptrdiff_t off = (uint8_t*)src.bindingArray() - srcScript->data;
MOZ_ASSERT(off >= 0);
MOZ_ASSERT(size_t(off) <= srcScript->dataSize());
Binding* dstPackedBindings = (Binding*)(dstScriptData + off);
/*
* Since atoms are shareable throughout the runtime, we can simply copy
* the source's bindingArray directly.
*/
if (!initWithTemporaryStorage(cx, self, src.numArgs(), src.numVars(),
src.numBodyLevelLexicals(),
src.numBlockScoped(),
src.numUnaliasedVars(),
src.numUnaliasedBodyLevelLexicals(),
src.bindingArray()))
{
return false;
}
self.switchToScriptStorage(dstPackedBindings);
return true;
}
template<XDRMode mode>
static bool
XDRScriptBindings(XDRState<mode>* xdr, LifoAllocScope& las, uint16_t numArgs, uint32_t numVars,
uint16_t numBodyLevelLexicals, uint16_t numBlockScoped,
uint32_t numUnaliasedVars, uint16_t numUnaliasedBodyLevelLexicals,
HandleScript script)
{
JSContext* cx = xdr->cx();
if (mode == XDR_ENCODE) {
for (BindingIter bi(script); bi; bi++) {
RootedAtom atom(cx, bi->name());
if (!XDRAtom(xdr, &atom))
return false;
}
for (BindingIter bi(script); bi; bi++) {
uint8_t u8 = (uint8_t(bi->kind()) << 1) | uint8_t(bi->aliased());
if (!xdr->codeUint8(&u8))
return false;
}
} else {
uint32_t nameCount = numArgs + numVars + numBodyLevelLexicals;
AutoValueVector atoms(cx);
if (!atoms.resize(nameCount))
return false;
for (uint32_t i = 0; i < nameCount; i++) {
RootedAtom atom(cx);
if (!XDRAtom(xdr, &atom))
return false;
atoms[i].setString(atom);
}
Binding* bindingArray = las.alloc().newArrayUninitialized<Binding>(nameCount);
if (!bindingArray)
return false;
for (uint32_t i = 0; i < nameCount; i++) {
uint8_t u8;
if (!xdr->codeUint8(&u8))
return false;
PropertyName* name = atoms[i].toString()->asAtom().asPropertyName();
Binding::Kind kind = Binding::Kind(u8 >> 1);
bool aliased = bool(u8 & 1);
bindingArray[i] = Binding(name, kind, aliased);
}
Rooted<Bindings> bindings(cx, script->bindings);
if (!Bindings::initWithTemporaryStorage(cx, &bindings, numArgs, numVars,
numBodyLevelLexicals, numBlockScoped,
numUnaliasedVars, numUnaliasedBodyLevelLexicals,
bindingArray))
{
return false;
}
script->bindings = bindings;
}
return true;
}
bool
Bindings::bindingIsAliased(uint32_t bindingIndex)
{
MOZ_ASSERT(bindingIndex < count());
return bindingArray()[bindingIndex].aliased();
}
void
Binding::trace(JSTracer* trc)
{
PropertyName* name = this->name();
TraceManuallyBarrieredEdge(trc, &name, "binding");
}
void
Bindings::trace(JSTracer* trc)
{
if (callObjShape_)
TraceEdge(trc, &callObjShape_, "callObjShape");
/*
* As the comment in Bindings explains, bindingsArray may point into freed
* storage when bindingArrayUsingTemporaryStorage so we don't mark it.
* Note: during compilation, atoms are already kept alive by gcKeepAtoms.
*/
if (bindingArrayUsingTemporaryStorage())
return;
for (Binding& b : *this)
b.trace(trc);
}
template<XDRMode mode>
bool
js::XDRScriptConst(XDRState<mode>* xdr, MutableHandleValue vp)
{
JSContext* cx = xdr->cx();
/*
* A script constant can be an arbitrary primitive value as they are used
* to implement JSOP_LOOKUPSWITCH. But they cannot be objects, see
* bug 407186.
*/
enum ConstTag {
SCRIPT_INT = 0,
SCRIPT_DOUBLE = 1,
SCRIPT_ATOM = 2,
SCRIPT_TRUE = 3,
SCRIPT_FALSE = 4,
SCRIPT_NULL = 5,
SCRIPT_OBJECT = 6,
SCRIPT_VOID = 7,
SCRIPT_HOLE = 8
};
uint32_t tag;
if (mode == XDR_ENCODE) {
if (vp.isInt32()) {
tag = SCRIPT_INT;
} else if (vp.isDouble()) {
tag = SCRIPT_DOUBLE;
} else if (vp.isString()) {
tag = SCRIPT_ATOM;
} else if (vp.isTrue()) {
tag = SCRIPT_TRUE;
} else if (vp.isFalse()) {
tag = SCRIPT_FALSE;
} else if (vp.isNull()) {
tag = SCRIPT_NULL;
} else if (vp.isObject()) {
tag = SCRIPT_OBJECT;
} else if (vp.isMagic(JS_ELEMENTS_HOLE)) {
tag = SCRIPT_HOLE;
} else {
MOZ_ASSERT(vp.isUndefined());
tag = SCRIPT_VOID;
}
}
if (!xdr->codeUint32(&tag))
return false;
switch (tag) {
case SCRIPT_INT: {
uint32_t i;
if (mode == XDR_ENCODE)
i = uint32_t(vp.toInt32());
if (!xdr->codeUint32(&i))
return false;
if (mode == XDR_DECODE)
vp.set(Int32Value(int32_t(i)));
break;
}
case SCRIPT_DOUBLE: {
double d;
if (mode == XDR_ENCODE)
d = vp.toDouble();
if (!xdr->codeDouble(&d))
return false;
if (mode == XDR_DECODE)
vp.set(DoubleValue(d));
break;
}
case SCRIPT_ATOM: {
RootedAtom atom(cx);
if (mode == XDR_ENCODE)
atom = &vp.toString()->asAtom();
if (!XDRAtom(xdr, &atom))
return false;
if (mode == XDR_DECODE)
vp.set(StringValue(atom));
break;
}
case SCRIPT_TRUE:
if (mode == XDR_DECODE)
vp.set(BooleanValue(true));
break;
case SCRIPT_FALSE:
if (mode == XDR_DECODE)
vp.set(BooleanValue(false));
break;
case SCRIPT_NULL:
if (mode == XDR_DECODE)
vp.set(NullValue());
break;
case SCRIPT_OBJECT: {
RootedObject obj(cx);
if (mode == XDR_ENCODE)
obj = &vp.toObject();
if (!XDRObjectLiteral(xdr, &obj))
return false;
if (mode == XDR_DECODE)
vp.setObject(*obj);
break;
}
case SCRIPT_VOID:
if (mode == XDR_DECODE)
vp.set(UndefinedValue());
break;
case SCRIPT_HOLE:
if (mode == XDR_DECODE)
vp.setMagic(JS_ELEMENTS_HOLE);
break;
}
return true;
}
template bool
js::XDRScriptConst(XDRState<XDR_ENCODE>*, MutableHandleValue);
template bool
js::XDRScriptConst(XDRState<XDR_DECODE>*, MutableHandleValue);
// Code LazyScript's free variables.
template<XDRMode mode>
static bool
XDRLazyFreeVariables(XDRState<mode>* xdr, MutableHandle<LazyScript*> lazy)
{
JSContext* cx = xdr->cx();
RootedAtom atom(cx);
uint8_t isHoistedUse;
LazyScript::FreeVariable* freeVariables = lazy->freeVariables();
size_t numFreeVariables = lazy->numFreeVariables();
for (size_t i = 0; i < numFreeVariables; i++) {
if (mode == XDR_ENCODE) {
atom = freeVariables[i].atom();
isHoistedUse = freeVariables[i].isHoistedUse();
}
if (!XDRAtom(xdr, &atom))
return false;
if (!xdr->codeUint8(&isHoistedUse))
return false;
if (mode == XDR_DECODE) {
freeVariables[i] = LazyScript::FreeVariable(atom);
if (isHoistedUse)
freeVariables[i].setIsHoistedUse();
}
}
return true;
}
// Code the missing part needed to re-create a LazyScript from a JSScript.
template<XDRMode mode>
static bool
XDRRelazificationInfo(XDRState<mode>* xdr, HandleFunction fun, HandleScript script,
HandleObject enclosingScope, MutableHandle<LazyScript*> lazy)
{
MOZ_ASSERT_IF(mode == XDR_ENCODE, script->isRelazifiable() && script->maybeLazyScript());
MOZ_ASSERT_IF(mode == XDR_ENCODE, !lazy->numInnerFunctions());
JSContext* cx = xdr->cx();
uint64_t packedFields;
{
uint32_t begin = script->sourceStart();
uint32_t end = script->sourceEnd();
uint32_t lineno = script->lineno();
uint32_t column = script->column();
if (mode == XDR_ENCODE) {
packedFields = lazy->packedFields();
MOZ_ASSERT(begin == lazy->begin());
MOZ_ASSERT(end == lazy->end());
MOZ_ASSERT(lineno == lazy->lineno());
MOZ_ASSERT(column == lazy->column());
// We can assert we have no inner functions because we don't
// relazify scripts with inner functions. See
// JSFunction::createScriptForLazilyInterpretedFunction.
MOZ_ASSERT(lazy->numInnerFunctions() == 0);
}
if (!xdr->codeUint64(&packedFields))
return false;
if (mode == XDR_DECODE) {
lazy.set(LazyScript::Create(cx, fun, script, enclosingScope, script,
packedFields, begin, end, lineno, column));
// As opposed to XDRLazyScript, we need to restore the runtime bits
// of the script, as we are trying to match the fact this function
// has already been parsed and that it would need to be re-lazified.
lazy->initRuntimeFields(packedFields);
}
}
// Code free variables.
if (!XDRLazyFreeVariables(xdr, lazy))
return false;
// No need to do anything with inner functions, since we asserted we don't
// have any.
return true;
}
static inline uint32_t
FindScopeObjectIndex(JSScript* script, NestedScopeObject& scope)
{
ObjectArray* objects = script->objects();
HeapPtrObject* vector = objects->vector;
unsigned length = objects->length;
for (unsigned i = 0; i < length; ++i) {
if (vector[i] == &scope)
return i;
}
MOZ_CRASH("Scope not found");
}
static bool
SaveSharedScriptData(ExclusiveContext*, Handle<JSScript*>, SharedScriptData*, uint32_t);
enum XDRClassKind {
CK_BlockObject = 0,
CK_WithObject = 1,
CK_JSFunction = 2,
CK_JSObject = 3
};
template<XDRMode mode>
bool
js::XDRScript(XDRState<mode>* xdr, HandleObject enclosingScopeArg, HandleScript enclosingScript,
HandleFunction fun, MutableHandleScript scriptp)
{
/* NB: Keep this in sync with CopyScript. */
MOZ_ASSERT(enclosingScopeArg);
enum ScriptBits {
NoScriptRval,
SavedCallerFun,
Strict,
ContainsDynamicNameAccess,
FunHasExtensibleScope,
FunNeedsDeclEnvObject,
FunHasAnyAliasedFormal,
ArgumentsHasVarBinding,
NeedsArgsObj,
HasMappedArgsObj,
FunctionHasThisBinding,
IsGeneratorExp,
IsLegacyGenerator,
IsStarGenerator,
OwnSource,
ExplicitUseStrict,
SelfHosted,
HasSingleton,
TreatAsRunOnce,
HasLazyScript,
HasNonSyntacticScope,
HasInnerFunctions,
NeedsHomeObject,
IsDerivedClassConstructor,
};
uint32_t length, lineno, column, nslots;
uint32_t natoms, nsrcnotes, i;
uint32_t nconsts, nobjects, nregexps, ntrynotes, nblockscopes, nyieldoffsets;
uint32_t prologueLength, version;
uint32_t funLength = 0;
uint32_t nTypeSets = 0;
uint32_t scriptBits = 0;
JSContext* cx = xdr->cx();
RootedScript script(cx);
RootedObject enclosingScope(cx, enclosingScopeArg);
natoms = nsrcnotes = 0;
nconsts = nobjects = nregexps = ntrynotes = nblockscopes = nyieldoffsets = 0;
/* XDR arguments and vars. */
uint16_t nargs = 0;
uint16_t nblocklocals = 0;
uint16_t nbodylevellexicals = 0;
uint32_t nvars = 0;
uint32_t nunaliasedvars = 0;
uint16_t nunaliasedbodylevellexicals = 0;
if (mode == XDR_ENCODE) {
script = scriptp.get();
MOZ_ASSERT_IF(enclosingScript, enclosingScript->compartment() == script->compartment());
MOZ_ASSERT(script->functionNonDelazifying() == fun);
if (!fun && script->treatAsRunOnce()) {
// This is a toplevel or eval script that's runOnce. We want to
// make sure that we're not XDR-saving an object we emitted for
// JSOP_OBJECT that then got modified. So throw if we're not
// cloning in JSOP_OBJECT or if we ever didn't clone in it in the
// past.
const JS::CompartmentOptions& opts = JS::CompartmentOptionsRef(cx);
if (!opts.cloneSingletons() || !opts.getSingletonsAsTemplates()) {
JS_ReportError(cx,
"Can't serialize a run-once non-function script "
"when we're not doing singleton cloning");
return false;
}
}
nargs = script->bindings.numArgs();
nblocklocals = script->bindings.numBlockScoped();
nbodylevellexicals = script->bindings.numBodyLevelLexicals();
nvars = script->bindings.numVars();
nunaliasedvars = script->bindings.numUnaliasedVars();
nunaliasedbodylevellexicals = script->bindings.numUnaliasedBodyLevelLexicals();
}
if (!xdr->codeUint16(&nargs))
return false;
if (!xdr->codeUint16(&nblocklocals))
return false;
if (!xdr->codeUint16(&nbodylevellexicals))
return false;
if (!xdr->codeUint32(&nvars))
return false;
if (!xdr->codeUint32(&nunaliasedvars))
return false;
if (!xdr->codeUint16(&nunaliasedbodylevellexicals))
return false;
if (mode == XDR_ENCODE)
length = script->length();
if (!xdr->codeUint32(&length))
return false;
if (mode == XDR_ENCODE) {
prologueLength = script->mainOffset();
MOZ_ASSERT(script->getVersion() != JSVERSION_UNKNOWN);
version = script->getVersion();
lineno = script->lineno();
column = script->column();
nslots = script->nslots();
natoms = script->natoms();
nsrcnotes = script->numNotes();
if (script->hasConsts())
nconsts = script->consts()->length;
if (script->hasObjects())
nobjects = script->objects()->length;
if (script->hasRegexps())
nregexps = script->regexps()->length;
if (script->hasTrynotes())
ntrynotes = script->trynotes()->length;
if (script->hasBlockScopes())
nblockscopes = script->blockScopes()->length;
if (script->hasYieldOffsets())
nyieldoffsets = script->yieldOffsets().length();
nTypeSets = script->nTypeSets();
funLength = script->funLength();
if (script->noScriptRval())
scriptBits |= (1 << NoScriptRval);
if (script->savedCallerFun())
scriptBits |= (1 << SavedCallerFun);
if (script->strict())
scriptBits |= (1 << Strict);
if (script->explicitUseStrict())
scriptBits |= (1 << ExplicitUseStrict);
if (script->selfHosted())
scriptBits |= (1 << SelfHosted);
if (script->bindingsAccessedDynamically())
scriptBits |= (1 << ContainsDynamicNameAccess);
if (script->funHasExtensibleScope())
scriptBits |= (1 << FunHasExtensibleScope);
if (script->funNeedsDeclEnvObject())
scriptBits |= (1 << FunNeedsDeclEnvObject);
if (script->funHasAnyAliasedFormal())
scriptBits |= (1 << FunHasAnyAliasedFormal);
if (script->argumentsHasVarBinding())
scriptBits |= (1 << ArgumentsHasVarBinding);
if (script->analyzedArgsUsage() && script->needsArgsObj())
scriptBits |= (1 << NeedsArgsObj);
if (script->hasMappedArgsObj())
scriptBits |= (1 << HasMappedArgsObj);
if (script->functionHasThisBinding())
scriptBits |= (1 << FunctionHasThisBinding);
if (!enclosingScript || enclosingScript->scriptSource() != script->scriptSource())
scriptBits |= (1 << OwnSource);
if (script->isGeneratorExp())
scriptBits |= (1 << IsGeneratorExp);
if (script->isLegacyGenerator())
scriptBits |= (1 << IsLegacyGenerator);
if (script->isStarGenerator())
scriptBits |= (1 << IsStarGenerator);
if (script->hasSingletons())
scriptBits |= (1 << HasSingleton);
if (script->treatAsRunOnce())
scriptBits |= (1 << TreatAsRunOnce);
if (script->isRelazifiable())
scriptBits |= (1 << HasLazyScript);
if (script->hasNonSyntacticScope())
scriptBits |= (1 << HasNonSyntacticScope);
if (script->hasInnerFunctions())
scriptBits |= (1 << HasInnerFunctions);
if (script->needsHomeObject())
scriptBits |= (1 << NeedsHomeObject);
if (script->isDerivedClassConstructor())
scriptBits |= (1 << IsDerivedClassConstructor);
}
if (!xdr->codeUint32(&prologueLength))
return false;
if (!xdr->codeUint32(&version))
return false;
// To fuse allocations, we need lengths of all embedded arrays early.
if (!xdr->codeUint32(&natoms))
return false;
if (!xdr->codeUint32(&nsrcnotes))
return false;
if (!xdr->codeUint32(&nconsts))
return false;
if (!xdr->codeUint32(&nobjects))
return false;
if (!xdr->codeUint32(&nregexps))
return false;
if (!xdr->codeUint32(&ntrynotes))
return false;
if (!xdr->codeUint32(&nblockscopes))
return false;
if (!xdr->codeUint32(&nyieldoffsets))
return false;
if (!xdr->codeUint32(&nTypeSets))
return false;
if (!xdr->codeUint32(&funLength))
return false;
if (!xdr->codeUint32(&scriptBits))
return false;
if (mode == XDR_DECODE) {
JSVersion version_ = JSVersion(version);
MOZ_ASSERT((version_ & VersionFlags::MASK) == unsigned(version_));
CompileOptions options(cx);
options.setVersion(version_)
.setNoScriptRval(!!(scriptBits & (1 << NoScriptRval)))
.setSelfHostingMode(!!(scriptBits & (1 << SelfHosted)));
RootedScriptSource sourceObject(cx);
if (scriptBits & (1 << OwnSource)) {
ScriptSource* ss = cx->new_<ScriptSource>();
if (!ss)
return false;
ScriptSourceHolder ssHolder(ss);
/*
* We use this CompileOptions only to initialize the
* ScriptSourceObject. Most CompileOptions fields aren't used by
* ScriptSourceObject, and those that are (element; elementAttributeName)
* aren't preserved by XDR. So this can be simple.
*/
CompileOptions options(cx);
ss->initFromOptions(cx, options);
sourceObject = ScriptSourceObject::create(cx, ss);
if (!sourceObject ||
!ScriptSourceObject::initFromOptions(cx, sourceObject, options))
return false;
} else {
MOZ_ASSERT(enclosingScript);
// When decoding, all the scripts and the script source object
// are in the same compartment, so the script's source object
// should never be a cross-compartment wrapper.
MOZ_ASSERT(enclosingScript->sourceObject()->is<ScriptSourceObject>());
sourceObject = &enclosingScript->sourceObject()->as<ScriptSourceObject>();
}
// If the outermost script has a non-syntactic scope, reflect that on
// the static scope chain.
if (scriptBits & (1 << HasNonSyntacticScope) &&
IsStaticGlobalLexicalScope(enclosingScope))
{
enclosingScope = StaticNonSyntacticScopeObjects::create(cx, enclosingScope);
if (!enclosingScope)
return false;
}
script = JSScript::Create(cx, enclosingScope, !!(scriptBits & (1 << SavedCallerFun)),
options, sourceObject, 0, 0);
if (!script)
return false;
// Set the script in its function now so that inner scripts to be
// decoded may iterate the static scope chain.
if (fun) {
fun->initScript(script);
script->setFunction(fun);
}
}
/* JSScript::partiallyInit assumes script->bindings is fully initialized. */
LifoAllocScope las(&cx->tempLifoAlloc());
if (!XDRScriptBindings(xdr, las, nargs, nvars, nbodylevellexicals, nblocklocals,
nunaliasedvars, nunaliasedbodylevellexicals, script))
return false;
if (mode == XDR_DECODE) {
/* XXX: AsyncFunction and isAsync not implemented. */
if (!JSScript::partiallyInit(cx, script, nconsts, nobjects, nregexps, ntrynotes,
nblockscopes, nyieldoffsets, nTypeSets))
{
return false;
}
MOZ_ASSERT(!script->mainOffset());
script->mainOffset_ = prologueLength;
script->setLength(length);
script->funLength_ = funLength;
scriptp.set(script);
if (scriptBits & (1 << Strict))
script->strict_ = true;
if (scriptBits & (1 << ExplicitUseStrict))
script->explicitUseStrict_ = true;
if (scriptBits & (1 << ContainsDynamicNameAccess))
script->bindingsAccessedDynamically_ = true;
if (scriptBits & (1 << FunHasExtensibleScope))
script->funHasExtensibleScope_ = true;
if (scriptBits & (1 << FunNeedsDeclEnvObject))
script->funNeedsDeclEnvObject_ = true;
if (scriptBits & (1 << FunHasAnyAliasedFormal))
script->funHasAnyAliasedFormal_ = true;
if (scriptBits & (1 << ArgumentsHasVarBinding))
script->setArgumentsHasVarBinding();
if (scriptBits & (1 << NeedsArgsObj))
script->setNeedsArgsObj(true);
if (scriptBits & (1 << HasMappedArgsObj))
script->hasMappedArgsObj_ = true;
if (scriptBits & (1 << FunctionHasThisBinding))
script->functionHasThisBinding_ = true;
if (scriptBits & (1 << IsGeneratorExp))
script->isGeneratorExp_ = true;
if (scriptBits & (1 << HasSingleton))
script->hasSingletons_ = true;
if (scriptBits & (1 << TreatAsRunOnce))
script->treatAsRunOnce_ = true;
if (scriptBits & (1 << HasNonSyntacticScope))
script->hasNonSyntacticScope_ = true;
if (scriptBits & (1 << HasInnerFunctions))
script->hasInnerFunctions_ = true;
if (scriptBits & (1 << NeedsHomeObject))
script->needsHomeObject_ = true;
if (scriptBits & (1 << IsDerivedClassConstructor))
script->isDerivedClassConstructor_ = true;
if (scriptBits & (1 << IsLegacyGenerator)) {
MOZ_ASSERT(!(scriptBits & (1 << IsStarGenerator)));
script->setGeneratorKind(LegacyGenerator);
} else if (scriptBits & (1 << IsStarGenerator))
script->setGeneratorKind(StarGenerator);
}
JS_STATIC_ASSERT(sizeof(jsbytecode) == 1);
JS_STATIC_ASSERT(sizeof(jssrcnote) == 1);
if (scriptBits & (1 << OwnSource)) {
if (!script->scriptSource()->performXDR<mode>(xdr))
return false;
}
if (!xdr->codeUint32(&script->sourceStart_))
return false;
if (!xdr->codeUint32(&script->sourceEnd_))
return false;
if (!xdr->codeUint32(&lineno) ||
!xdr->codeUint32(&column) ||
!xdr->codeUint32(&nslots))
{
return false;
}
if (mode == XDR_DECODE) {
script->lineno_ = lineno;
script->column_ = column;
script->nslots_ = nslots;
}
jsbytecode* code = script->code();
SharedScriptData* ssd;
if (mode == XDR_DECODE) {
ssd = SharedScriptData::new_(cx, length, nsrcnotes, natoms);
if (!ssd)
return false;
code = ssd->data;
if (natoms != 0) {
script->natoms_ = natoms;
script->atoms = ssd->atoms();
}
}
if (!xdr->codeBytes(code, length) || !xdr->codeBytes(code + length, nsrcnotes)) {
if (mode == XDR_DECODE)
js_free(ssd);
return false;
}
for (i = 0; i != natoms; ++i) {
if (mode == XDR_DECODE) {
RootedAtom tmp(cx);
if (!XDRAtom(xdr, &tmp))
return false;
script->atoms[i].init(tmp);
} else {
RootedAtom tmp(cx, script->atoms[i]);
if (!XDRAtom(xdr, &tmp))
return false;
}
}
if (mode == XDR_DECODE) {
if (!SaveSharedScriptData(cx, script, ssd, nsrcnotes))
return false;
}
if (nconsts) {
HeapValue* vector = script->consts()->vector;
RootedValue val(cx);
for (i = 0; i != nconsts; ++i) {
if (mode == XDR_ENCODE)
val = vector[i];
if (!XDRScriptConst(xdr, &val))
return false;
if (mode == XDR_DECODE)
vector[i].init(val);
}
}