-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathByteCodeSerializer.cpp
More file actions
5158 lines (4477 loc) · 203 KB
/
ByteCodeSerializer.cpp
File metadata and controls
5158 lines (4477 loc) · 203 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. All rights reserved.
// Copyright (c) 2021 ChakraCore Project Contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeByteCodePch.h"
#include "RegexCommon.h"
#include "RegexPattern.h"
#include "Library/Regex/RegexHelper.h"
#include "DataStructures/Option.h"
#include "DataStructures/ImmutableList.h"
#include "DataStructures/BufferBuilder.h"
#include "ByteCode/OpCodeUtilAsmJs.h"
#include "ByteCode/ByteCodeSerializer.h"
#include "Language/AsmJsModule.h"
#include "Library/Array/ES5Array.h"
void ChakraBinaryBuildDateTimeHash(DWORD * buildDateHash, DWORD * buildTimeHash);
namespace Js
{
const int magicConstant = *(int*)"ChBc";
const int majorVersionConstant = 1;
const int minorVersionConstant = 1;
#ifdef BYTE_CODE_MAGIC_CONSTANTS
// These magic constants can be enabled to bracket and check different sections of the serialization
// file. Turn on BYTE_CODE_MAGIC_CONSTANTS in ByteCodeSerializer.h to enable this.
const int magicStartOfFunctionBody = *(int*)"fun[";
const int magicEndOfFunctionBody = *(int*)"]fun";
const int magicStartOfConstantTable = *(int*)"con[";
const int magicEndOfConstantTable = *(int*)"]con";
const int magicStartStringConstant = *(int*)"str[";
const int magicEndStringConstant = *(int*)"]str";
const int magicStartOfCacheIdToPropIdMap = *(int*)"cid[";
const int magicEndOfCacheIdToPropIdMap = *(int*)"]cid";
const int magicStartOfReferencedPropIdMap = *(int*)"rid[";
const int magicEndOfReferencedPropIdMap = *(int*)"]rid";
const int magicStartOfPropertyIdsForScopeSlotArray = *(int*)"scp[";
const int magicEndOfPropertyIdsForScopeSlotArray = *(int*)"]scp";
const int magicStartOfDebuggerScopes = *(int*)"dsc[";
const int magicEndOfDebuggerScopes = *(int*)"]dsc";
const int magicStartOfDebuggerScopeProperties = *(int*)"dsp[";
const int magicEndOfDebuggerScopeProperties = *(int*)"]dsp";
const int magicStartOfAux = *(int*)"aux[";
const int magicEndOfAux = *(int*)"]aux";
const int magicStartOfAuxVarArray = *(int*)"ava[";
const int magicEndOfAuxVarArray = *(int*)"]ava";
const int magicStartOfAuxIntArray = *(int*)"aia[";
const int magicEndOfAuxIntArray = *(int*)"]aia";
const int magicStartOfAuxFltArray = *(int*)"afa[";
const int magicEndOfAuxFltArray = *(int*)"]afa";
const int magicStartOfAuxPropIdArray = *(int*)"api[";
const int magicEndOfAuxPropIdArray = *(int*)"]api";
const int magicStartOfAuxFuncInfoArray = *(int*)"afi[";
const int magicEndOfAuxFuncInfoArray = *(int*)"]afi";
const int magicStartOfAsmJsFuncInfo = *(int*)"aFI[";
const int magicEndOfAsmJsFuncInfo = *(int*)"]aFI";
const int magicStartOfAsmJsModuleInfo = *(int*)"ami[";
const int magicEndOfAsmJsModuleInfo = *(int*)"]ami";
const int magicStartOfPropIdsOfFormals = *(int*)"pif[";
const int magicEndOfPropIdsOfFormals = *(int*)"]pif";
const int magicStartOfSlotIdToNestedIndexArray = *(int*)"sni[";
const int magicEndOfSlotIdToNestedIndexArray = *(int*)"]sni";
const int magicStartOfCallSiteToCallApplyCallSiteArray = *(int*)"cca[";
const int magicEndOfCallSiteToCallApplyCallSiteArray = *(int*)"]cca";
#endif
// Serialized files are architecture specific
#ifndef VALIDATE_SERIALIZED_BYTECODE
#if TARGET_64
const byte magicArchitecture = 64;
#else
const byte magicArchitecture = 32;
#endif
#else
#if _M_AMD64
const int magicArchitecture = *(int*)"amd";
#elif _M_IA64
const int magicArchitecture = *(int*)"ia64";
#elif _M_ARM
const int magicArchitecture = *(int*)"arm";
#elif _M_ARM_64
const int magicArchitecture = *(int*)"arm64";
#else
const int magicArchitecture = *(int*)"x86";
#endif
#endif
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Byte Code Serializer Versioning scheme
// Version number is a GUID (128 bits). There are two versioning modes--Engineering and Release. Engineering mode is for day-to-day development. Every time chakra.dll is built a
// fresh new version is generated by hashing the build date and time. This means that a byte code file saved to disk is exactly tied to the binary that generated it. This works
// well for QA test runs and buddy tests because there is no chance of effects between runs.
//
// Release mode is used when chakra.dll is close to public release where there are actual changes to chakra. The GUID is a fixed number from build-to-build. This number will stay
// the same for releases where there is no change to chakra.dll. The reason for this is that we don't want to invalidate compatible byte code that has already been cached.
enum FileVersionScheme : byte
{
// Currently Chakra and ChakraCore versioning scheme is different.
// Same version number for Chakra and ChakraCore doesn't mean they are the same.
// Give the versioning scheme different value, so that byte code generate from one won't be use in the other.
LibraryByteCodeVersioningScheme = 0,
#ifdef NTBUILD
EngineeringVersioningScheme = 10,
ReleaseVersioningScheme = 20,
#else
EngineeringVersioningScheme = 11,
ReleaseVersioningScheme = 21,
#endif
#if (defined(NTBUILD) && CHAKRA_VERSION_RELEASE) || (!defined(NTBUILD) && CHAKRA_CORE_VERSION_RELEASE)
CurrentFileVersionScheme = ReleaseVersioningScheme
#else
CurrentFileVersionScheme = EngineeringVersioningScheme
#endif
};
// it should be in separate file for testing
#include "ByteCodeCacheReleaseFileVersion.h"
// Used for selective serialization of Function Body fields to make the representation compact
#define DECLARE_SERIALIZABLE_FIELD(type, name, serializableType) bool has_##name : 1
#define DECLARE_SERIALIZABLE_ACCESSOR_FIELD(type, name, serializableType, defaultValue) bool has_##name : 1
#define DEFINE_ALL_FIELDS
struct SerializedFieldList {
#include "SerializableFunctionFields.h"
bool has_m_lineNumber: 1;
bool has_m_columnNumber: 1;
bool has_attributes : 1;
bool has_m_nestedCount: 1;
bool has_loopHeaderArray : 1;
bool has_asmJsInfo : 1;
bool has_auxiliary : 1;
bool has_propertyIdOfFormals: 1;
bool has_slotIdInCachedScopeToNestedIndexArray : 1;
bool has_callSiteToCallApplyCallSiteArray : 1;
bool has_debuggerScopeSlotArray : 1;
bool has_deferredStubs : 1;
bool has_scopeInfo : 1;
bool has_printOffsets : 1;
};
C_ASSERT(sizeof(GUID)==sizeof(DWORD)*4);
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Holds a buffer and size for use by the serializer
struct ByteBuffer
{
uint32 byteCount;
union
{
void * pv;
const char16 * s16;
const char * s8;
};
public:
ByteBuffer(uint32 byteCount, void * pv)
: byteCount(byteCount), pv(pv)
{ }
};
} // namespace Js
template<>
struct DefaultComparer<Js::ByteBuffer*>
{
static bool Equals(Js::ByteBuffer const * str1, Js::ByteBuffer const * str2)
{
if (str1->byteCount != str2->byteCount)
{
return false;
}
return memcmp(str1->pv, str2->pv, str1->byteCount)==0;
}
static hash_t GetHashCode(Js::ByteBuffer const * str)
{
return JsUtil::CharacterBuffer<char>::StaticGetHashCode(str->s8, str->byteCount);
}
};
namespace Js
{
struct IndexEntry
{
BufferBuilderByte* isPropertyRecord;
int id;
};
#pragma pack(push, 1)
struct StringIndexRecord
{
int offset;
bool isPropertyRecord;
};
#pragma pack(pop)
typedef JsUtil::BaseDictionary<ByteBuffer*, IndexEntry, ArenaAllocator, PrimeSizePolicy, DefaultComparer> TString16ToId;
static LocalScopeInfoId InvalidLocalScopeInfoId = 0xFFFFFFFF;
typedef JsUtil::BaseDictionary<Js::ScopeInfo*, LocalScopeInfoId, ArenaAllocator> ScopeInfoToScopeInfoIdMap;
// Boolean flags on the FunctionBody
enum FunctionFlags
{
ffIsDeclaration = 0x0001,
ffHasImplicitArgsIn = 0x0002,
ffIsAccessor = 0x0004,
ffIsGlobalFunc = 0x0008,
ffDontInline = 0x0010,
ffIsFuncRegistered = 0x0020,
ffIsStaticNameFunction = 0x0040,
ffIsStrictMode = 0x0080,
ffDoBackendArgumentsOptimization = 0x0100,
ffIsEval = 0x0200,
ffIsDynamicFunction = 0x0400,
ffhasAllNonLocalReferenced = 0x0800,
ffhasSetIsObject = 0x1000,
ffhasSetCallsEval = 0x2000,
ffIsNameIdentifierRef = 0x4000,
ffChildCallsEval = 0x8000,
ffHasReferenceableBuiltInArguments = 0x10000,
ffIsNamedFunctionExpression = 0x20000,
ffIsAsmJsMode = 0x40000,
ffIsAsmJsFunction = 0x80000,
ffIsAnonymous = 0x100000,
ffUsesArgumentsObject = 0x200000,
ffDoScopeObjectCreation = 0x400000,
ffIsParamAndBodyScopeMerged = 0x800000,
ffIsMethod = 0x1000000,
ffIsClassMember = 0x2000000,
};
enum ScopeInfoFlags : byte
{
sifNone = 0x0,
sifIsDynamic = 0x1,
sifIsObject = 0x2,
sifMustInstantiate = 0x4,
sifIsCached = 0x8,
sifHasLocalInClosure = 0x10,
sifIsGeneratorFunctionBody = 0x20,
sifIsAsyncFunctionBody = 0x40,
};
enum SymbolInfoFlags : byte
{
syifNone = 0x0,
syifHasFuncAssignment = 0x1,
syifIsBlockVariable = 0x2,
syifIsConst = 0x4,
syifIsFuncExpr = 0x8,
syifIsModuleExportStorage = 0x10,
syifIsModuleImport = 0x20,
};
// Kinds of constant
enum ConstantType : byte
{
ctInt8 = 1,
ctInt16 = 2,
ctInt32 = 3,
ctNumber = 4,
ctString16 = 5,
ctPropertyString16 = 6,
ctNull = 7,
ctUndefined = 8,
ctNullDisplay = 9,
ctStrictNullDisplay = 10,
ctTrue = 11,
ctFalse = 12,
ctStringTemplateCallsite = 13,
};
// Try to convert from size_t to uint32. May overflow (and return false) on 64-bit.
bool TryConvertToUInt32(size_t size, uint32 * out)
{
*out = (uint32)size;
if (sizeof(size) == sizeof(uint32))
{
return true;
}
Assert(sizeof(size_t) == sizeof(uint64));
if((uint64)(*out) == size)
{
return true;
}
AssertMsg(false, "Is it really an offset greater than 32 bits?"); // More likely a bug somewhere.
return false;
}
#if VARIABLE_INT_ENCODING
template <typename T>
static const byte * ReadVariableInt(const byte * buffer, size_t remainingBytes, T * value)
{
Assert(remainingBytes >= sizeof(byte));
byte firstByte = *(byte*) buffer;
if (firstByte >= MIN_SENTINEL)
{
Assert(remainingBytes >= sizeof(uint16));
const byte* locationOfValue = buffer + 1;
if (firstByte == TWO_BYTE_SENTINEL)
{
uint16 twoByteValue = *((serialization_alignment uint16*) locationOfValue);
Assert(twoByteValue > ONE_BYTE_MAX);
*value = twoByteValue;
PHASE_PRINT_TESTTRACE1(Js::VariableIntEncodingPhase, _u("TestTrace: VariableIntEncoding (decode)- 2 bytes, value %u\n"), *value);
return buffer + sizeof(uint16) +SENTINEL_BYTE_COUNT;
}
else
{
Assert(remainingBytes >= sizeof(T));
Assert(firstByte == FOUR_BYTE_SENTINEL);
*value = *((serialization_alignment T*) locationOfValue);
Assert(*value > TWO_BYTE_MAX || *value <= 0);
PHASE_PRINT_TESTTRACE1(Js::VariableIntEncodingPhase, _u("TestTrace: VariableIntEncoding (decode) - 4 bytes, value %u\n"), *value);
return buffer + sizeof(T) +SENTINEL_BYTE_COUNT;
}
}
else
{
*value = (T) firstByte;
PHASE_PRINT_TESTTRACE1(Js::VariableIntEncodingPhase, _u("TestTrace: VariableIntEncoding (decode) - 1 byte, value %u\n"), *value);
return buffer + sizeof(byte);
}
}
#endif
// Compile-time-check some invariants that the file format depends on
C_ASSERT(sizeof(PropertyId)==sizeof(int32));
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Byte Code File Header Layout
// Offset Size Name Value
// 0 4 Magic Number "ChBc"
// 4 4 Total File Size
// 8 1 File Version Scheme 10 for engineering 20 for release
// 9 4 Version DWORD 1 jscript minor version GUID quad part 1
// 13 4 Version DWORD 2 jscript major version GUID quad part 2
// 17 4 Version DWORD 3 hash of __DATE__ GUID quad part 3
// 21 4 Version DWORD 4 hash of __TIME__ GUID quad part 4
// 25 4 Expected Architecture "amd"0, "ia64", "arm"0 or "x86"0
// 29 4 Expected Function Body Size
// 33 4 Expected Built In PropertyCount
// 37 4 Expected Op Code Count
// 41 4 Size of Original Source Code
// 45 4 Count of Auxiliary Structures
// 49 4 Smallest Literal Object ID
// 53 4 Largest Literal Object ID
// 57 4 Offset from start of this file
// to Strings Table
// 61 4 Offset to Source Spans
// 65 4 Count of Functions
// 69 4 Offset to Functions
// 73 4 Offset to Auxiliary Structures
// 77 4 Count of Strings
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// This is the serializer
class ByteCodeBufferBuilder
{
// Begin File Layout -------------------------------
ConstantSizedBufferBuilderOf<int32> magic;
ConstantSizedBufferBuilderOf<int32> totalSize; // The size is unknown when the offsets are calculated so just reserve 4 bytes for this for now to avoid doing two passes to calculate the offsets
BufferBuilderByte fileVersionKind; // Engineering or Release
ConstantSizedBufferBuilderOf<int32> V1; // V1-V4 are the parts of the version. It is a fixed version GUID or a per-build version.
ConstantSizedBufferBuilderOf<int32> V2;
ConstantSizedBufferBuilderOf<int32> V3;
ConstantSizedBufferBuilderOf<int32> V4;
BufferBuilderInt32 architecture;
BufferBuilderInt32 expectedFunctionBodySize;
BufferBuilderInt32 expectedBuildInPropertyCount;
BufferBuilderInt32 expectedOpCodeCount;
BufferBuilderInt32 originalSourceSize;
BufferBuilderInt32 originalCharLength;
BufferBuilderRelativeOffset string16sOffset;
BufferBuilderRelativeOffset lineInfoCacheOffset;
BufferBuilderRelativeOffset functionsOffset;
BufferBuilderRelativeOffset scopeInfoOffset;
BufferBuilderInt32 string16Count;
BufferBuilderList string16IndexTable;
BufferBuilderList string16Table;
BufferBuilderAligned alignedString16Table;
BufferBuilderInt32 lineInfoCacheCount;
BufferBuilderRaw lineCharacterOffsetCacheBuffer;
BufferBuilderByte lineInfoHasByteCache;
BufferBuilderRaw lineByteOffsetCacheBuffer;
BufferBuilderInt32 functionCount;
BufferBuilderList functionsTable;
BufferBuilderInt32 scopeInfoCount;
BufferBuilderList scopeInfoTable;
BufferBuilderList scopeInfoRelativeOffsets;
// End File Layout ---------------------------------
ArenaAllocator * alloc;
TString16ToId * string16ToId;
ScopeInfoToScopeInfoIdMap* scopeInfoToScopeInfoIdMap;
int nextString16Id;
int topFunctionId;
LPCUTF8 utf8Source;
ScriptContext * scriptContext;
BufferBuilder * startOfCachedScopeAuxBlock;
DWORD dwFlags;
//Instead of referencing TotalNumberOfBuiltInProperties directly; or PropertyIds::_countJSOnlyProperty we use this.
//For library code this will be set to _countJSOnlyProperty and for normal bytecode this will be TotalNumberOfBuiltInProperties
int builtInPropertyCount;
bool GenerateLibraryByteCode() const
{
return (dwFlags & GENERATE_BYTE_CODE_BUFFER_LIBRARY) != 0;
}
bool GenerateByteCodeForNative() const
{
return (dwFlags & GENERATE_BYTE_CODE_FOR_NATIVE) != 0;
}
bool GenerateParserStateCache() const
{
return (dwFlags & GENERATE_BYTE_CODE_PARSER_STATE) != 0;
}
bool ShouldAllocWithCoTaskMem() const
{
return (dwFlags & GENERATE_BYTE_CODE_COTASKMEMALLOC);
}
bool ShouldAllocWithANew() const
{
return (dwFlags & GENERATE_BYTE_CODE_ALLOC_ANEW);
}
public:
ByteCodeBufferBuilder(uint32 sourceSize, uint32 sourceCharLength, LPCUTF8 utf8Source, Utf8SourceInfo* sourceInfo, ScriptContext * scriptContext, ArenaAllocator * alloc, DWORD dwFlags, int builtInPropertyCount)
: magic(_u("Magic"), magicConstant),
totalSize(_u("Total Size"), 0),
fileVersionKind(_u("FileVersionKind"), 0),
V1(_u("V1"), 0),
V2(_u("V2"), 0),
V3(_u("V3"), 0),
V4(_u("V4"), 0),
architecture(_u("Expected Architecture"), magicArchitecture),
expectedFunctionBodySize(_u("Expected Function Body Size"), sizeof(unaligned FunctionBody)),
expectedBuildInPropertyCount(_u("Expected Built-in Properties"), builtInPropertyCount),
expectedOpCodeCount(_u("Expected Number of OpCodes"), (int)OpCode::Count),
originalSourceSize(_u("Source Size"), sourceSize),
originalCharLength(_u("Source Char Length"), sourceCharLength),
string16sOffset(_u("Offset of String16s"), &string16Count),
lineInfoCacheOffset(_u("Offset of Line Info Cache"), &lineInfoCacheCount),
functionCount(_u("Function Count"), 0),
functionsOffset(_u("Offset of Functions"), &functionCount),
string16Count(_u("String16 Count"), 0),
string16IndexTable(_u("String16 Indexes")),
string16Table(_u("String16 Table")),
alignedString16Table(_u("Alignment for String16 Table"), &string16Table, sizeof(char16)),
lineInfoCacheCount(_u("Line Info Cache"), sourceInfo->GetLineOffsetCache()->GetLineCount()),
lineCharacterOffsetCacheBuffer(_u("Line Info Character Cache"), lineInfoCacheCount.value * sizeof(charcount_t), (byte *)sourceInfo->GetLineOffsetCache()->GetLineCharacterOffsetBuffer()),
lineInfoHasByteCache(_u("Line Info Has Byte Cache"), sourceInfo->GetLineOffsetCache()->GetLineByteOffsetBuffer() != nullptr),
lineByteOffsetCacheBuffer(_u("Line Info Byte Cache"), lineInfoCacheCount.value * sizeof(charcount_t), (byte *)sourceInfo->GetLineOffsetCache()->GetLineByteOffsetBuffer()),
functionsTable(_u("Functions")),
scopeInfoOffset(_u("Offset of ScopeInfos"), &scopeInfoCount),
scopeInfoCount(_u("ScopeInfo Count"), 0),
scopeInfoRelativeOffsets(_u("ScopeInfo Relative Offsets")),
scopeInfoTable(_u("ScopeInfo Table")),
nextString16Id(builtInPropertyCount), // Reserve the built-in property ids
topFunctionId(0),
utf8Source(utf8Source),
scriptContext(scriptContext),
startOfCachedScopeAuxBlock(nullptr),
alloc(alloc),
dwFlags(dwFlags),
builtInPropertyCount(builtInPropertyCount)
{
if (GenerateLibraryByteCode())
{
expectedFunctionBodySize.value = 0;
expectedOpCodeCount.value = 0;
#ifdef ENABLE_TEST_HOOKS
if (scriptContext->GetConfig()->Force32BitByteCode())
{
architecture.value = 32;
}
#endif
}
// Library bytecode uses its own scheme
byte actualFileVersionScheme = GenerateLibraryByteCode() ? LibraryByteCodeVersioningScheme : CurrentFileVersionScheme;
#if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.ForceSerializedBytecodeVersionSchema)
{
actualFileVersionScheme = (byte)Js::Configuration::Global.flags.ForceSerializedBytecodeVersionSchema;
}
#endif
fileVersionKind.value = actualFileVersionScheme;
switch (actualFileVersionScheme)
{
case EngineeringVersioningScheme:
{
Assert(!GenerateLibraryByteCode());
DWORD jscriptMajor, jscriptMinor, buildDateHash, buildTimeHash;
Js::VerifyOkCatastrophic(AutoSystemInfo::GetJscriptFileVersion(&jscriptMajor, &jscriptMinor, &buildDateHash, &buildTimeHash));
V1.value = jscriptMajor;
V2.value = jscriptMinor;
V3.value = buildDateHash;
V4.value = buildTimeHash;
break;
}
case ReleaseVersioningScheme:
{
Assert(!GenerateLibraryByteCode());
auto guidDWORDs = (DWORD*)(&byteCodeCacheReleaseFileVersion);
V1.value = guidDWORDs[0];
V2.value = guidDWORDs[1];
V3.value = guidDWORDs[2];
V4.value = guidDWORDs[3];
break;
}
case LibraryByteCodeVersioningScheme:
{
Assert(GenerateLibraryByteCode());
// To keep consistent library code between Chakra.dll and ChakraCore.dll, use a fixed version.
// This goes hand in hand with the bytecode verification unit tests.
V1.value = 0;
V2.value = 0;
V3.value = 0;
V4.value = 0;
break;
}
default:
Throw::InternalError();
break;
}
#if ENABLE_DEBUG_CONFIG_OPTIONS
if (Js::Configuration::Global.flags.ForceSerializedBytecodeMajorVersion)
{
V1.value = Js::Configuration::Global.flags.ForceSerializedBytecodeMajorVersion;
V2.value = 0;
V3.value = 0;
V4.value = 0;
}
#endif
string16ToId = Anew(alloc, TString16ToId, alloc);
scopeInfoToScopeInfoIdMap = Anew(alloc, ScopeInfoToScopeInfoIdMap, alloc);
}
HRESULT Create(byte ** buffer, DWORD * bufferBytes)
{
BufferBuilderList all(_u("Final"));
// Reverse the lists
string16IndexTable.list = string16IndexTable.list->ReverseCurrentList();
string16Table.list = string16Table.list->ReverseCurrentList();
scopeInfoTable.list = scopeInfoTable.list->ReverseCurrentList();
scopeInfoRelativeOffsets.list = scopeInfoRelativeOffsets.list->ReverseCurrentList();
// Prepend all sections (in reverse order because of prepend)
all.list = regex::ImmutableList<Js::BufferBuilder*>::OfSingle(&scopeInfoTable, alloc);
all.list = all.list->Prepend(&scopeInfoRelativeOffsets, alloc);
all.list = all.list->Prepend(&scopeInfoCount, alloc);
all.list = all.list->Prepend(&functionsTable, alloc);
all.list = all.list->Prepend(&functionCount, alloc);
if (lineByteOffsetCacheBuffer.raw != nullptr)
{
all.list = all.list->Prepend(&lineByteOffsetCacheBuffer, alloc);
}
all.list = all.list->Prepend(&lineInfoHasByteCache, alloc);
all.list = all.list->Prepend(&lineCharacterOffsetCacheBuffer, alloc);
all.list = all.list->Prepend(&lineInfoCacheCount, alloc);
all.list = all.list->Prepend(&alignedString16Table, alloc);
all.list = all.list->Prepend(&string16IndexTable, alloc);
all.list = all.list->Prepend(&string16Count, alloc);
all.list = all.list->Prepend(&scopeInfoOffset, alloc);
all.list = all.list->Prepend(&functionsOffset, alloc);
all.list = all.list->Prepend(&lineInfoCacheOffset, alloc);
all.list = all.list->Prepend(&string16sOffset, alloc);
all.list = all.list->Prepend(&originalCharLength, alloc);
all.list = all.list->Prepend(&originalSourceSize, alloc);
all.list = all.list->Prepend(&expectedOpCodeCount, alloc);
all.list = all.list->Prepend(&expectedBuildInPropertyCount, alloc);
all.list = all.list->Prepend(&expectedFunctionBodySize, alloc);
all.list = all.list->Prepend(&architecture, alloc);
all.list = all.list->Prepend(&V4, alloc);
all.list = all.list->Prepend(&V3, alloc);
all.list = all.list->Prepend(&V2, alloc);
all.list = all.list->Prepend(&V1, alloc);
all.list = all.list->Prepend(&fileVersionKind, alloc);
all.list = all.list->Prepend(&totalSize, alloc);
all.list = all.list->Prepend(&magic, alloc);
// Get the string count.
string16Count.value = nextString16Id - this->builtInPropertyCount;
// Figure out the size and set all individual offsets
DWORD size = all.FixOffset(0);
totalSize.value = size;
// Allocate the bytes
if (ShouldAllocWithANew() || ShouldAllocWithCoTaskMem())
{
*bufferBytes = size;
if (ShouldAllocWithANew())
{
*buffer = AnewArray(scriptContext->SourceCodeAllocator(), byte, *bufferBytes);
}
else
{
Assert(ShouldAllocWithCoTaskMem());
*buffer = (byte*)CoTaskMemAlloc(*bufferBytes);
}
if (*buffer == nullptr)
{
return E_OUTOFMEMORY;
}
}
if (size > *bufferBytes)
{
*bufferBytes = size;
return *buffer == nullptr ? S_OK : E_INVALIDARG;
}
else
{
// Write into the buffer
all.Write(*buffer, *bufferBytes);
*bufferBytes = size;
DebugOnly(Output::Flush()); // Flush trace
return S_OK;
}
}
bool isBuiltinProperty(PropertyId pid) {
if (pid < this->builtInPropertyCount || pid==/*nil*/0xffffffff)
{
return true;
}
return false;
};
PropertyId encodeNonBuiltinPropertyId(PropertyId id) {
const PropertyRecord * propertyValue = nullptr;
Assert(id >= this->builtInPropertyCount); // Shouldn't have gotten a builtin property id
propertyValue = scriptContext->GetPropertyName(id);
id = GetIdOfPropertyRecord(propertyValue) - this->builtInPropertyCount;
return id ^ SERIALIZER_OBSCURE_NONBUILTIN_PROPERTY_ID;
};
PropertyId encodePossiblyBuiltInPropertyId(PropertyId id) {
const PropertyRecord * propertyValue = nullptr;
if(id >= this->builtInPropertyCount)
{
propertyValue = scriptContext->GetPropertyName(id);
id = GetIdOfPropertyRecord(propertyValue);
}
return id ^ SERIALIZER_OBSCURE_PROPERTY_ID;
};
int GetString16Id(ByteBuffer * bb, bool isPropertyRecord = false)
{
IndexEntry indexEntry;
if (!string16ToId->TryGetValue(bb, &indexEntry))
{
auto sizeInBytes = bb->byteCount;
auto stringEntry = Anew(alloc, BufferBuilderRaw, _u("String16"), sizeInBytes, (const byte *)bb->pv); // Writing the terminator even though it is computable so that this memory can be used as-is when deserialized
string16Table.list = string16Table.list->Prepend(stringEntry, alloc);
if (string16IndexTable.list == nullptr)
{
// First item in the list is the first string.
auto stringIndexEntry = Anew(alloc, BufferBuilderRelativeOffset, _u("First String16 Index"), stringEntry);
string16IndexTable.list = regex::ImmutableList<Js::BufferBuilder*>::OfSingle(stringIndexEntry, alloc);
PrependByte(string16IndexTable, _u("isPropertyRecord"), (BYTE)isPropertyRecord);
}
// Get a pointer to the previous entry of isPropertyRecord
indexEntry.isPropertyRecord = static_cast<BufferBuilderByte*>(string16IndexTable.list->First());
// Subsequent strings indexes point one past the end. This way, the size is always computable by subtracting indexes.
auto stringIndexEntry = Anew(alloc, BufferBuilderRelativeOffset, _u("String16 Index"), stringEntry, sizeInBytes);
string16IndexTable.list = string16IndexTable.list->Prepend(stringIndexEntry, alloc);
// By default, mark the next string to be not a property record.
PrependByte(string16IndexTable, _u("isPropertyRecord"), (BYTE)false);
indexEntry.id = nextString16Id;
string16ToId->Add(bb, indexEntry);
++nextString16Id;
}
// A string might start off as not being a property record and later becoming one. Hence,
// we set only if the transition is from false => true. Once it is a property record, it cannot go back.
if(isPropertyRecord)
{
indexEntry.isPropertyRecord->value = isPropertyRecord;
}
return indexEntry.id;
}
uint32 PrependRelativeOffset(BufferBuilderList & builder, LPCWSTR clue, BufferBuilder * pointedTo)
{
auto entry = Anew(alloc, BufferBuilderRelativeOffset, clue, pointedTo, 0);
builder.list = builder.list->Prepend(entry, alloc);
return sizeof(int32);
}
uint32 PrependInt16(BufferBuilderList & builder, LPCWSTR clue, int16 value, BufferBuilderInt16 ** entryOut = nullptr)
{
auto entry = Anew(alloc, BufferBuilderInt16, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
if (entryOut)
{
*entryOut = entry;
}
return sizeof(int16);
}
uint32 PrependInt32(BufferBuilderList & builder, LPCWSTR clue, int value, BufferBuilderInt32 ** entryOut = nullptr)
{
auto entry = Anew(alloc, BufferBuilderInt32, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
if (entryOut)
{
*entryOut = entry;
}
return sizeof(int32);
}
uint32 PrependConstantInt16(BufferBuilderList & builder, LPCWSTR clue, int16 value, ConstantSizedBufferBuilderOf<int16> ** entryOut = nullptr)
{
auto entry = Anew(alloc, ConstantSizedBufferBuilderOf<int16>, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
if (entryOut)
{
*entryOut = entry;
}
return sizeof(int16);
}
uint32 PrependConstantInt32(BufferBuilderList & builder, LPCWSTR clue, int value, ConstantSizedBufferBuilderOf<int> ** entryOut = nullptr)
{
auto entry = Anew(alloc, ConstantSizedBufferBuilderOf<int>, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
if (entryOut)
{
*entryOut = entry;
}
return sizeof(int32);
}
uint32 PrependConstantInt64(BufferBuilderList & builder, LPCWSTR clue, int64 value, ConstantSizedBufferBuilderOf<int64> ** entryOut = nullptr)
{
auto entry = Anew(alloc, ConstantSizedBufferBuilderOf<int64>, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
if (entryOut)
{
*entryOut = entry;
}
return sizeof(int64);
}
uint32 PrependByte(BufferBuilderList & builder, LPCWSTR clue, byte value)
{
auto entry = Anew(alloc, BufferBuilderByte, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
return sizeof(byte);
}
uint32 PrependFunctionBodyFlags(BufferBuilderList & builder, LPCWSTR clue, FunctionBody::FunctionBodyFlags value)
{
return PrependByte(builder, clue, (byte) value);
}
uint32 PrependBool(BufferBuilderList & builder, LPCWSTR clue, bool value)
{
return PrependByte(builder, clue, (byte) value);
}
uint32 PrependFloat(BufferBuilderList & builder, LPCWSTR clue, float value)
{
auto entry = Anew(alloc, BufferBuilderFloat, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
return sizeof(float);
}
uint32 PrependDouble(BufferBuilderList & builder, LPCWSTR clue, double value)
{
auto entry = Anew(alloc, BufferBuilderDouble, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
return sizeof(double);
}
uint32 PrependSIMDValue(BufferBuilderList & builder, LPCWSTR clue, SIMDValue value)
{
auto entry = Anew(alloc, BufferBuilderSIMD, clue, value);
builder.list = builder.list->Prepend(entry, alloc);
return sizeof(SIMDValue);
}
uint32 PrependString16(__in BufferBuilderList & builder, __in_nz LPCWSTR clue, __in_bcount_opt(byteLength) LPCWSTR sz, __in uint32 byteLength)
{
if (sz != nullptr)
{
auto bb = Anew(alloc, ByteBuffer, byteLength, (void*)sz); // Includes trailing null
return PrependInt32(builder, clue, GetString16Id(bb));
}
else
{
return PrependInt32(builder, clue, 0xffffffff);
}
}
uint32 PrependByteBuffer(BufferBuilderList & builder, LPCWSTR clue, ByteBuffer * bb)
{
auto id = GetString16Id(bb);
return PrependInt32(builder, clue, id);
}
int GetIdOfString(__in_bcount_opt(byteLength) LPCWSTR sz, __in uint32 byteLength)
{
auto bb = Anew(alloc, ByteBuffer, byteLength, (void*)sz); // Includes trailing null
return GetString16Id(bb);
}
int GetIdOfPropertyRecord(const PropertyRecord * propertyRecord)
{
AssertMsg(!propertyRecord->IsSymbol(), "bytecode serializer does not currently handle non-built-in symbol PropertyRecords");
size_t byteCount = ((size_t)propertyRecord->GetLength() + 1) * sizeof(char16);
if (byteCount > UINT_MAX)
{
// We should never see property record that big
Js::Throw::InternalError();
}
auto buffer = propertyRecord->GetBuffer();
#if DBG
const PropertyRecord * propertyRecordCheck;
scriptContext->FindPropertyRecord(buffer, propertyRecord->GetLength(), &propertyRecordCheck);
Assert(propertyRecordCheck == propertyRecord);
#endif
auto bb = Anew(alloc, ByteBuffer, (uint32)byteCount, (void*)buffer);
return GetString16Id(bb, /*isPropertyRecord=*/ true);
}
template<typename TLayout>
unaligned TLayout * DuplicateLayout(unaligned const TLayout * in)
{
auto sizeOfLayout = sizeof(unaligned TLayout);
auto newLayout = AnewArray(alloc, byte, sizeOfLayout);
js_memcpy_s(newLayout, sizeOfLayout, in, sizeOfLayout);
return (unaligned TLayout * )newLayout;
}
template<typename T>
uint32 Prepend(BufferBuilderList & builder, LPCWSTR clue, T * t)
{
auto block = Anew(alloc, BufferBuilderRaw, clue, sizeof(serialization_alignment T), (const byte*)t);
builder.list = builder.list->Prepend(block, alloc);
return sizeof(serialization_alignment T);
}
struct AuxRecord
{
SerializedAuxiliaryKind kind;
uint offset;
};
#ifdef ASMJS_PLAT
HRESULT RewriteAsmJsByteCodesInto(BufferBuilderList & builder, LPCWSTR clue, FunctionBody * function, ByteBlock * byteBlock, SerializedFieldList& definedFields)
{
SListCounted<AuxRecord> auxRecords(alloc);
auto finalSize = Anew(alloc, BufferBuilderInt32, _u("Final Byte Code Size"), 0); // Initially set to zero
builder.list = builder.list->Prepend(finalSize, alloc);
ByteCodeReader reader;
reader.Create(function);
uint32 size = 0;
const byte * opStart = nullptr;
bool cantGenerate = false;
auto saveBlock = [&]() {
uint32 byteCount;
if (TryConvertToUInt32(reader.GetIP() - opStart, &byteCount))
{
if (!GenerateByteCodeForNative())
{
auto block = Anew(alloc, BufferBuilderRaw, clue, byteCount, (const byte*)opStart);
builder.list = builder.list->Prepend(block, alloc);
size += byteCount;
}
}
else
{
AssertMsg(false, "Unlikely: byte code size overflows 32 bits");
cantGenerate = true;
}
};
Assert(!function->HasCachedScopePropIds());
while (!cantGenerate)
{
opStart = reader.GetIP();
opStart; // For prefast. It can't figure out that opStart is captured in saveBlock above.
LayoutSize layoutSize;
OpCodeAsmJs op = reader.ReadAsmJsOp(layoutSize);
if (op == OpCodeAsmJs::EndOfBlock)
{
saveBlock();
break;
}
OpLayoutTypeAsmJs layoutType = OpCodeUtilAsmJs::GetOpCodeLayout(op);
switch (layoutType)
{
#define LAYOUT_TYPE(layout) \
case OpLayoutTypeAsmJs::##layout: { \
Assert(layoutSize == SmallLayout); \
reader.##layout(); \
saveBlock(); \
break; }
#define LAYOUT_TYPE_WMS(layout) \
case OpLayoutTypeAsmJs::##layout: { \
switch (layoutSize) \
{ \
case SmallLayout: \
reader.##layout##_Small(); \
break; \
case MediumLayout: \
reader.##layout##_Medium(); \
break; \
case LargeLayout: \
reader.##layout##_Large(); \
break; \
default: \
Assume(UNREACHED); \
} \
saveBlock(); \
break; }
#include "LayoutTypesAsmJs.h"
default:
AssertMsg(false, "Unknown OpLayout");
cantGenerate = true;
break;
}
}
if (cantGenerate)
{
return ByteCodeSerializer::CantGenerate;
}
if (size != byteBlock->GetLength() && !GenerateByteCodeForNative())
{
Assert(size == byteBlock->GetLength());
return ByteCodeSerializer::CantGenerate;
}
finalSize->value = size;
RewriteAuxiliaryInto(builder, auxRecords, reader, function, definedFields);
return S_OK;
}
#endif
HRESULT RewriteByteCodesInto(BufferBuilderList & builder, LPCWSTR clue, FunctionBody * function, ByteBlock * byteBlock, SerializedFieldList& definedFields)
{
SListCounted<AuxRecord> auxRecords(alloc);
auto finalSize = Anew(alloc, BufferBuilderInt32, _u("Final Byte Code Size"), 0); // Initially set to zero
builder.list = builder.list->Prepend(finalSize, alloc);
ByteCodeReader reader;
reader.Create(function);
uint32 size = 0;
const byte * opStart = nullptr;
bool cantGenerate = false;
auto saveBlock = [&]() {
uint32 byteCount;
if (TryConvertToUInt32(reader.GetIP()-opStart, &byteCount))
{