-
Notifications
You must be signed in to change notification settings - Fork 78
/
vm.image.js
1412 lines (1389 loc) · 65.2 KB
/
vm.image.js
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
"use strict";
/*
* Copyright (c) 2013-2024 Vanessa Freudenberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
Object.subclass('Squeak.Image',
'about', {
about: function() {
/*
Object Format
=============
Each Squeak object is a Squeak.Object instance, only SmallIntegers are JS numbers.
Instance variables/fields reference other objects directly via the "pointers" property.
A Spur image uses Squeak.ObjectSpur instances instead. Characters are not immediate,
but made identical using a character table. They are created with their mark bit set to
true, so are ignored by the GC.
{
sqClass: reference to class object
format: format integer as in Squeak oop header
hash: identity hash integer
pointers: (optional) Array referencing inst vars + indexable fields
words: (optional) Array of numbers (words)
bytes: (optional) Array of numbers (bytes)
float: (optional) float value if this is a Float object
isNil: (optional) true if this is the nil object
isTrue: (optional) true if this is the true object
isFalse: (optional) true if this is the false object
isFloat: (optional) true if this is a Float object
isFloatClass: (optional) true if this is the Float class
isCompact: (optional) true if this is a compact class
oop: identifies this object in a snapshot (assigned on GC, new space object oops are negative)
mark: boolean (used only during GC, otherwise false)
dirty: boolean (true when an object may have a ref to a new object, set on every write, reset on GC)
nextObject: linked list of objects in old space and young space (newly created objects do not have this yet)
}
Object Memory
=============
Objects in old space are a linked list (firstOldObject). When loading an image, all objects are old.
Objects are tenured to old space during a full GC.
New objects are only referenced by other objects' pointers, and thus can be garbage-collected
at any time by the Javascript GC.
A partial GC creates a linked list of new objects reachable from old space. We call this
list "young space". It is not stored, but only created by primitives like nextObject,
nextInstance, or become to support enumeration of new space.
To efficiently find potential young space roots, any write to an instance variable sets
the "dirty" flag of the object, allowing to skip clean objects.
Weak references are finalized by a full GC. A partial GC only finalizes young weak references.
*/
}
},
'initializing', {
initialize: function(name) {
this.headRoom = 100000000; // TODO: pass as option
this.totalMemory = 0;
this.headerFlags = 0;
this.name = name;
this.gcCount = 0;
this.gcMilliseconds = 0;
this.pgcCount = 0;
this.pgcMilliseconds = 0;
this.gcTenured = 0;
this.allocationCount = 0;
this.oldSpaceCount = 0;
this.youngSpaceCount = 0;
this.newSpaceCount = 0;
this.hasNewInstances = {};
},
readFromBuffer: function(arraybuffer, thenDo, progressDo) {
console.log('squeak: reading ' + this.name + ' (' + arraybuffer.byteLength + ' bytes)');
this.startupTime = Date.now();
var data = new DataView(arraybuffer),
littleEndian = false,
pos = 0;
var readWord32 = function() {
var int = data.getUint32(pos, littleEndian);
pos += 4;
return int;
};
var readWord64 = function() {
// we assume littleEndian for now
var lo = data.getUint32(pos, true),
hi = data.getUint32(pos+4, true);
pos += 8;
return Squeak.word64FromUint32(hi, lo);
};
var readWord = readWord32;
var wordSize = 4;
var readBits = function(nWords, isPointers) {
if (isPointers) { // do endian conversion
var oops = [];
while (oops.length < nWords)
oops.push(readWord());
return oops;
} else { // words (no endian conversion yet)
var bits = new Uint32Array(arraybuffer, pos, nWords * wordSize / 4);
pos += nWords * wordSize;
return bits;
}
};
// read version and determine endianness
var baseVersions = [6501, 6502, 6504, 68000, 68002, 68004],
baseVersionMask = 0x119EE,
version = 0,
fileHeaderSize = 0;
while (true) { // try all four endianness + header combos
littleEndian = !littleEndian;
pos = fileHeaderSize;
version = readWord();
if (baseVersions.indexOf(version & baseVersionMask) >= 0) break;
if (!littleEndian) fileHeaderSize += 512;
if (fileHeaderSize > 512) throw Error("bad image version"); // we tried all combos
};
this.version = version;
var nativeFloats = (version & 1) !== 0;
this.hasClosures = !([6501, 6502, 68000].indexOf(version) >= 0);
this.isSpur = (version & 16) !== 0;
// var multipleByteCodeSetsActive = (version & 256) !== 0; // not used
var is64Bit = version >= 68000;
if (is64Bit && !this.isSpur) throw Error("64 bit non-spur images not supported yet");
if (is64Bit) { readWord = readWord64; wordSize = 8; }
// parse image header
var imageHeaderSize = readWord32(); // always 32 bits
var objectMemorySize = readWord(); //first unused location in heap
var oldBaseAddr = readWord(); //object memory base address of image
var specialObjectsOopInt = readWord(); //oop of array of special oops
var lastHash = readWord32(); if (is64Bit) readWord32(); // not used
var savedWindowSize = readWord(); // not used
this.headerFlags = readWord(); // vm attribute 48
this.savedHeaderWords = [lastHash, savedWindowSize, this.headerFlags];
for (var i = 0; i < 4; i++) {
this.savedHeaderWords.push(readWord32());
}
var firstSegSize = readWord();
var prevObj;
var oopMap = {};
var rawBits = {};
var headerSize = fileHeaderSize + imageHeaderSize;
pos = headerSize;
if (!this.isSpur) {
// read traditional object memory
while (pos < headerSize + objectMemorySize) {
var nWords = 0;
var classInt = 0;
var header = readWord();
switch (header & Squeak.HeaderTypeMask) {
case Squeak.HeaderTypeSizeAndClass:
nWords = header >>> 2;
classInt = readWord();
header = readWord();
break;
case Squeak.HeaderTypeClass:
classInt = header - Squeak.HeaderTypeClass;
header = readWord();
nWords = (header >>> 2) & 63;
break;
case Squeak.HeaderTypeShort:
nWords = (header >>> 2) & 63;
classInt = (header >>> 12) & 31; //compact class index
//Note classInt<32 implies compact class index
break;
case Squeak.HeaderTypeFree:
throw Error("Unexpected free block");
}
nWords--; //length includes base header which we have already read
var oop = pos - 4 - headerSize, //0-rel byte oop of this object (base header)
format = (header>>>8) & 15,
hash = (header>>>17) & 4095,
bits = readBits(nWords, format < 5);
var object = new Squeak.Object();
object.initFromImage(oop, classInt, format, hash);
if (classInt < 32) object.hash |= 0x10000000; // see fixCompactOops()
if (prevObj) prevObj.nextObject = object;
this.oldSpaceCount++;
prevObj = object;
//oopMap is from old oops to actual objects
oopMap[oldBaseAddr + oop] = object;
//rawBits holds raw content bits for objects
rawBits[oop] = bits;
}
this.firstOldObject = oopMap[oldBaseAddr+4];
this.lastOldObject = object;
this.lastOldObject.nextObject = null; // Add next object pointer as indicator this is in fact an old object
this.oldSpaceBytes = objectMemorySize;
} else {
// Read all Spur object memory segments
this.oldSpaceBytes = firstSegSize - 16;
var segmentEnd = pos + firstSegSize,
addressOffset = 0,
classPages = null,
skippedBytes = 0,
oopAdjust = {};
while (pos < segmentEnd) {
while (pos < segmentEnd - 16) {
// read objects in segment
var objPos = pos,
formatAndClass = readWord32(),
sizeAndHash = readWord32(),
size = sizeAndHash >>> 24;
if (size === 255) { // this was the extended size header, read actual header
size = formatAndClass;
// In 64 bit images the size can actually be 56 bits. LOL. Nope.
// if (is64Bit) size += (sizeAndHash & 0x00FFFFFF) * 0x100000000;
formatAndClass = readWord32();
sizeAndHash = readWord32();
}
var oop = addressOffset + pos - 8 - headerSize,
format = (formatAndClass >>> 24) & 0x1F,
classID = formatAndClass & 0x003FFFFF,
hash = sizeAndHash & 0x003FFFFF;
var bits = readBits(size, format < 10 && classID > 0);
// align on 8 bytes, min size 16 bytes
pos += is64Bit
? (size < 1 ? 1 - size : 0) * 8
: (size < 2 ? 2 - size : size & 1) * 4;
// low class ids are internal to Spur
if (classID >= 32) {
var object = new Squeak.ObjectSpur();
object.initFromImage(oop, classID, format, hash);
if (prevObj) prevObj.nextObject = object;
this.oldSpaceCount++;
prevObj = object;
//oopMap is from old oops to actual objects
oopMap[oldBaseAddr + oop] = object;
//rawBits holds raw content bits for objects
rawBits[oop] = bits;
oopAdjust[oop] = skippedBytes;
// account for size difference of 32 vs 64 bit oops
if (is64Bit) {
var overhead = object.overhead64(bits);
skippedBytes += overhead.bytes;
// OTOH, in 32 bits we need the extra size header sooner
// so in some cases 64 bits has 2 words less overhead
if (overhead.sizeHeader) {
oopAdjust[oop] -= 8;
skippedBytes -= 8;
}
}
} else {
skippedBytes += pos - objPos;
if (classID === 16 && !classPages) classPages = bits;
if (classID) oopMap[oldBaseAddr + oop] = bits; // used in spurClassTable()
}
}
if (pos !== segmentEnd - 16) throw Error("invalid segment");
// last 16 bytes in segment is a bridge object
var deltaWords = readWord32(),
deltaWordsHi = readWord32(),
segmentBytes = readWord32(),
segmentBytesHi = readWord32();
// if segmentBytes is zero, the end of the image has been reached
if (segmentBytes !== 0) {
var deltaBytes = deltaWordsHi & 0xFF000000 ? (deltaWords & 0x00FFFFFF) * 4 : 0;
segmentEnd += segmentBytes;
addressOffset += deltaBytes;
skippedBytes += 16 + deltaBytes;
this.oldSpaceBytes += deltaBytes + segmentBytes;
}
}
this.oldSpaceBytes -= skippedBytes;
this.firstOldObject = oopMap[oldBaseAddr];
this.lastOldObject = object;
this.lastOldObject.nextObject = null; // Add next object pointer as indicator this is in fact an old object
}
this.totalMemory = this.oldSpaceBytes + this.headRoom;
this.totalMemory = Math.ceil(this.totalMemory / 1000000) * 1000000;
if (true) {
// For debugging: re-create all objects from named prototypes
var _splObs = oopMap[specialObjectsOopInt],
cc = this.isSpur ? this.spurClassTable(oopMap, rawBits, classPages, _splObs)
: rawBits[oopMap[rawBits[_splObs.oop][Squeak.splOb_CompactClasses]].oop];
var renamedObj = null;
object = this.firstOldObject;
prevObj = null;
while (object) {
prevObj = renamedObj;
renamedObj = object.renameFromImage(oopMap, rawBits, cc);
if (prevObj) prevObj.nextObject = renamedObj;
else this.firstOldObject = renamedObj;
oopMap[oldBaseAddr + object.oop] = renamedObj;
object = object.nextObject;
}
this.lastOldObject = renamedObj;
this.lastOldObject.nextObject = null; // Add next object pointer as indicator this is in fact an old object
}
// properly link objects by mapping via oopMap
var splObs = oopMap[specialObjectsOopInt];
var compactClasses = rawBits[oopMap[rawBits[splObs.oop][Squeak.splOb_CompactClasses]].oop];
var floatClass = oopMap[rawBits[splObs.oop][Squeak.splOb_ClassFloat]];
// Spur needs different arguments for installFromImage()
if (this.isSpur) {
this.initImmediateClasses(oopMap, rawBits, splObs);
compactClasses = this.spurClassTable(oopMap, rawBits, classPages, splObs);
nativeFloats = this.getCharacter.bind(this);
this.initSpurOverrides();
}
var obj = this.firstOldObject,
done = 0;
var mapSomeObjects = function() {
if (obj) {
var stop = done + (this.oldSpaceCount / 20 | 0); // do it in 20 chunks
while (obj && done < stop) {
obj.installFromImage(oopMap, rawBits, compactClasses, floatClass, littleEndian, nativeFloats, is64Bit && {
makeFloat: function makeFloat(bits) {
return this.instantiateFloat(bits);
}.bind(this),
makeLargeFromSmall: function makeLargeFromSmall(hi, lo) {
return this.instantiateLargeFromSmall(hi, lo);
}.bind(this),
});
obj = obj.nextObject;
done++;
}
if (progressDo) progressDo(done / this.oldSpaceCount);
return true; // do more
} else { // done
this.specialObjectsArray = splObs;
this.decorateKnownObjects();
if (this.isSpur) {
this.fixSkippedOops(oopAdjust);
if (is64Bit) this.fixPCs();
this.ensureFullBlockClosureClass(this.specialObjectsArray, compactClasses);
} else {
this.fixCompiledMethods();
this.fixCompactOops();
}
return false; // don't do more
}
}.bind(this);
function mapSomeObjectsAsync() {
if (mapSomeObjects()) {
self.setTimeout(mapSomeObjectsAsync, 0);
} else {
if (thenDo) thenDo();
}
};
if (!progressDo) {
while (mapSomeObjects()) {}; // do it synchronously
if (thenDo) thenDo();
} else {
self.setTimeout(mapSomeObjectsAsync, 0);
}
},
decorateKnownObjects: function() {
var splObjs = this.specialObjectsArray.pointers;
splObjs[Squeak.splOb_NilObject].isNil = true;
splObjs[Squeak.splOb_TrueObject].isTrue = true;
splObjs[Squeak.splOb_FalseObject].isFalse = true;
splObjs[Squeak.splOb_ClassFloat].isFloatClass = true;
if (!this.isSpur) {
this.compactClasses = this.specialObjectsArray.pointers[Squeak.splOb_CompactClasses].pointers;
for (var i = 0; i < this.compactClasses.length; i++)
if (!this.compactClasses[i].isNil)
this.compactClasses[i].isCompact = true;
}
if (!Number.prototype.sqInstName)
Object.defineProperty(Number.prototype, 'sqInstName', {
enumerable: false,
value: function() { return this.toString() }
});
},
fixCompactOops: function() {
// instances of compact classes might have been saved with a non-compact header
// fix their oops here so validation succeeds later
if (this.isSpur) return;
var obj = this.firstOldObject,
adjust = 0;
while (obj) {
var hadCompactHeader = obj.hash > 0x0FFFFFFF,
mightBeCompact = !!obj.sqClass.isCompact;
if (hadCompactHeader !== mightBeCompact) {
var isCompact = obj.snapshotSize().header === 0;
if (hadCompactHeader !== isCompact) {
adjust += isCompact ? -4 : 4;
}
}
obj.hash &= 0x0FFFFFFF;
obj.oop += adjust;
obj = obj.nextObject;
}
this.oldSpaceBytes += adjust;
},
fixCompiledMethods: function() {
// in the 6501 pre-release image, some CompiledMethods
// do not have the proper class
if (this.version >= 6502) return;
var obj = this.firstOldObject,
compiledMethodClass = this.specialObjectsArray.pointers[Squeak.splOb_ClassCompiledMethod];
while (obj) {
if (obj.isMethod()) obj.sqClass = compiledMethodClass;
obj = obj.nextObject;
}
},
fixSkippedOops: function(oopAdjust) {
// reading Spur skips some internal objects
// we adjust the oops of following objects here
// this is like the compaction phase of our GC
var obj = this.firstOldObject;
while (obj) {
obj.oop -= oopAdjust[obj.oop];
obj = obj.nextObject;
}
// do a sanity check
obj = this.lastOldObject;
if (obj.addr() + obj.totalBytes() !== this.oldSpaceBytes)
throw Error("image size doesn't match object sizes")
},
fixPCs: function() {
// In 64 bits literals take up twice as much space
// The pc starts after the last literal. Fix it.
var clsMethodContext = this.specialObjectsArray.pointers[Squeak.splOb_ClassMethodContext],
pc = Squeak.Context_instructionPointer,
method = Squeak.Context_method,
clsBlockClosure = this.specialObjectsArray.pointers[Squeak.splOb_ClassBlockClosure],
startpc = Squeak.Closure_startpc,
outerContext = Squeak.Closure_outerContext,
obj = this.firstOldObject;
while (obj) {
if (obj.sqClass === clsMethodContext) {
obj.pointers[pc] -= obj.pointers[method].pointers.length * 4;
} else if (obj.sqClass === clsBlockClosure) {
obj.pointers[startpc] -= obj.pointers[outerContext].pointers[method].pointers.length * 4;
}
obj = obj.nextObject;
}
},
ensureFullBlockClosureClass: function(splObs, compactClasses) {
// Read FullBlockClosure class from compactClasses if not yet present in specialObjectsArray.
if (splObs.pointers[Squeak.splOb_ClassFullBlockClosure].isNil && compactClasses[38]) {
splObs.pointers[Squeak.splOb_ClassFullBlockClosure] = compactClasses[38];
}
},
},
'garbage collection - full', {
fullGC: function(reason) {
// Collect garbage and return first tenured object (to support object enumeration)
// Old space is a linked list of objects - each object has an "nextObject" reference.
// New space objects do not have that pointer, they are garbage-collected by JavaScript.
// But they have an allocation id so the survivors can be ordered on tenure.
// The "nextObject" references are created by collecting all new objects,
// sorting them by id, and then linking them into old space.
this.vm.addMessage("fullGC: " + reason);
var start = Date.now();
var previousNew = this.newSpaceCount; // includes young and newly allocated
var previousOld = this.oldSpaceCount;
var newObjects = this.markReachableObjects(); // technically these are young objects
this.removeUnmarkedOldObjects();
this.appendToOldObjects(newObjects);
this.finalizeWeakReferences();
this.allocationCount += this.newSpaceCount;
this.newSpaceCount = 0;
this.youngSpaceCount = 0;
this.hasNewInstances = {};
this.gcCount++;
this.gcMilliseconds += Date.now() - start;
var delta = previousOld - this.oldSpaceCount; // absolute change
var survivingNew = newObjects.length;
var survivingOld = this.oldSpaceCount - survivingNew;
var gcedNew = previousNew - survivingNew;
var gcedOld = previousOld - survivingOld;
console.log("Full GC (" + reason + "): " + (Date.now() - start) + " ms;" +
" before: " + previousOld.toLocaleString() + " old objects;" +
" allocated " + previousNew.toLocaleString() + " new;" +
" surviving " + survivingOld.toLocaleString() + " old;" +
" tenuring " + survivingNew.toLocaleString() + " new;" +
" gc'ed " + gcedOld.toLocaleString() + " old and " + gcedNew.toLocaleString() + " new;" +
" total now: " + this.oldSpaceCount.toLocaleString() + " (" + (delta > 0 ? "+" : "") + delta.toLocaleString() + ", "
+ this.oldSpaceBytes.toLocaleString() + " bytes)"
);
return newObjects.length > 0 ? newObjects[0] : null;
},
gcRoots: function() {
// the roots of the system
this.vm.storeContextRegisters(); // update active context
return [this.specialObjectsArray, this.vm.activeContext];
},
markReachableObjects: function() {
// FullGC: Visit all reachable objects and mark them.
// Return surviving new objects (young objects to be tenured).
// Contexts are handled specially: they have garbage beyond the stack pointer
// which must not be traced, and is cleared out here
// In weak objects, only the inst vars are traced
var todo = this.gcRoots();
var newObjects = [];
this.weakObjects = [];
while (todo.length > 0) {
var object = todo.pop();
if (object.mark) continue; // objects are added to todo more than once
if (object.oop < 0) // it's a new object
newObjects.push(object);
object.mark = true; // mark it
if (!object.sqClass.mark) // trace class if not marked
todo.push(object.sqClass);
var body = object.pointers;
if (body) { // trace all unmarked pointers
var n = body.length;
if (object.isWeak()) {
n = object.sqClass.classInstSize(); // do not trace weak fields
this.weakObjects.push(object);
}
if (this.vm.isContext(object)) { // contexts have garbage beyond SP
n = object.contextSizeWithStack();
for (var i = n; i < body.length; i++) // clean up that garbage
body[i] = this.vm.nilObj;
}
for (var i = 0; i < n; i++)
if (typeof body[i] === "object" && !body[i].mark) // except immediates
todo.push(body[i]);
// Note: "immediate" character objects in Spur always stay marked
}
}
// pre-spur sort by oop to preserve creation order
return this.isSpur ? newObjects : newObjects.sort(function(a,b){return b.oop - a.oop});
},
removeUnmarkedOldObjects: function() {
// FullGC: Unlink unmarked old objects from the nextObject linked list
// Reset marks of remaining objects, and adjust their oops
// Set this.lastOldObject to last old object
var removedCount = 0,
removedBytes = 0,
obj = this.firstOldObject;
obj.mark = false; // we know the first object (nil) was marked
while (true) {
var next = obj.nextObject;
if (!next) {// we're done
this.lastOldObject = obj;
this.lastOldObject.nextObject = null; // Add next object pointer as indicator this is in fact an old object
this.oldSpaceBytes -= removedBytes;
this.oldSpaceCount -= removedCount;
return;
}
// reset partial GC flag
if (next.dirty) next.dirty = false;
// if marked, continue with next object
if (next.mark) {
obj = next;
obj.mark = false; // unmark for next GC
obj.oop -= removedBytes; // compact oops
} else { // otherwise, remove it
var corpse = next;
obj.nextObject = corpse.nextObject; // drop from old-space list
corpse.oop = -(++this.newSpaceCount); // move to new-space for finalizing
removedBytes += corpse.totalBytes();
removedCount++;
//console.log("removing " + removedCount + " " + removedBytes + " " + corpse.totalBytes() + " " + corpse.toString())
}
}
},
appendToOldObjects: function(newObjects) {
// FullGC: append new objects to linked list of old objects
// and unmark them
var oldObj = this.lastOldObject;
//var oldBytes = this.oldSpaceBytes;
for (var i = 0; i < newObjects.length; i++) {
var newObj = newObjects[i];
newObj.mark = false;
this.oldSpaceBytes = newObj.setAddr(this.oldSpaceBytes); // add at end of memory
oldObj.nextObject = newObj;
oldObj = newObj;
//console.log("tenuring " + (i+1) + " " + (this.oldSpaceBytes - oldBytes) + " " + newObj.totalBytes() + " " + newObj.toString());
}
oldObj.nextObject = null; // might have been in young space
this.lastOldObject = oldObj;
this.lastOldObject.nextObject = null; // Add next object pointer as indicator this is in fact an old object
this.oldSpaceCount += newObjects.length;
this.gcTenured += newObjects.length;
// this is the only place that increases oldSpaceBytes / decreases bytesLeft
this.vm.signalLowSpaceIfNecessary(this.bytesLeft());
// TODO: keep track of newSpaceBytes and youngSpaceBytes, and signal low space if necessary
// basically, add obj.totalBytes() to newSpaceBytes when instantiating,
// trigger partial GC if newSpaceBytes + lowSpaceThreshold > totalMemory - (youngSpaceBytes + oldSpaceBytes)
// which would set newSpaceBytes to 0 and youngSpaceBytes to the actual survivors.
// for efficiency, only compute object size once per object and store? test impact on GC speed
},
tenureIfYoung: function(object) {
if (object.oop < 0) {
this.appendToOldObjects([object]);
}
},
finalizeWeakReferences: function() {
// nil out all weak fields that did not survive GC
var weakObjects = this.weakObjects;
this.weakObjects = null;
for (var o = 0; o < weakObjects.length; o++) {
var weakObj = weakObjects[o],
pointers = weakObj.pointers,
firstWeak = weakObj.sqClass.classInstSize(),
finalized = false;
for (var i = firstWeak; i < pointers.length; i++) {
if (pointers[i].oop < 0) { // ref is not in old-space
pointers[i] = this.vm.nilObj;
finalized = true;
}
}
if (finalized) {
this.vm.pendingFinalizationSignals++;
if (firstWeak >= 2) { // check if weak obj is a finalizer item
var list = weakObj.pointers[Squeak.WeakFinalizerItem_list];
if (list.sqClass == this.vm.specialObjects[Squeak.splOb_ClassWeakFinalizer]) {
// add weak obj as first in the finalization list
var items = list.pointers[Squeak.WeakFinalizationList_first];
weakObj.pointers[Squeak.WeakFinalizerItem_next] = items;
list.pointers[Squeak.WeakFinalizationList_first] = weakObj;
}
}
}
};
if (this.vm.pendingFinalizationSignals > 0) {
this.vm.forceInterruptCheck(); // run finalizer asap
}
},
},
'garbage collection - partial', {
partialGC: function(reason) {
// make a linked list of young objects
// and finalize weak refs
this.vm.addMessage("partialGC: " + reason);
var start = Date.now();
var previous = this.newSpaceCount;
var young = this.findYoungObjects();
this.appendToYoungSpace(young);
this.finalizeWeakReferences();
this.cleanupYoungSpace(young);
this.allocationCount += this.newSpaceCount - young.length;
this.youngSpaceCount = young.length;
this.newSpaceCount = this.youngSpaceCount;
this.pgcCount++;
this.pgcMilliseconds += Date.now() - start;
console.log("Partial GC (" + reason+ "): " + (Date.now() - start) + " ms, " +
"found " + this.youngRootsCount.toLocaleString() + " roots in " + this.oldSpaceCount.toLocaleString() + " old, " +
"kept " + this.youngSpaceCount.toLocaleString() + " young (" + (previous - this.youngSpaceCount).toLocaleString() + " gc'ed)");
return young[0];
},
youngRoots: function() {
// PartialGC: Find new objects directly pointed to by old objects.
// For speed we only scan "dirty" objects that have been written to
var roots = this.gcRoots().filter(function(obj){return obj.oop < 0;}),
object = this.firstOldObject;
while (object) {
if (object.dirty) {
var body = object.pointers,
dirty = false;
for (var i = 0; i < body.length; i++) {
var child = body[i];
if (typeof child === "object" && child.oop < 0) { // if child is new
roots.push(child);
dirty = true;
}
}
if (!dirty) object.dirty = false;
}
object = object.nextObject;
}
return roots;
},
findYoungObjects: function() {
// PartialGC: find new objects transitively reachable from old objects
var todo = this.youngRoots(), // direct pointers from old space
newObjects = [];
this.youngRootsCount = todo.length;
this.weakObjects = [];
while (todo.length > 0) {
var object = todo.pop();
if (object.mark) continue; // objects are added to todo more than once
newObjects.push(object);
object.mark = true; // mark it
if (object.sqClass.oop < 0) // trace class if new
todo.push(object.sqClass);
var body = object.pointers;
if (body) { // trace all unmarked pointers
var n = body.length;
if (object.isWeak()) {
n = object.sqClass.classInstSize(); // do not trace weak fields
this.weakObjects.push(object);
}
if (this.vm.isContext(object)) { // contexts have garbage beyond SP
n = object.contextSizeWithStack();
for (var i = n; i < body.length; i++) // clean up that garbage
body[i] = this.vm.nilObj;
}
for (var i = 0; i < n; i++) {
var child = body[i];
if (typeof child === "object" && child.oop < 0)
todo.push(child);
}
}
}
// pre-spur sort by oop to preserve creation order
return this.isSpur ? newObjects : newObjects.sort(function(a,b){return b.oop - a.oop});
},
appendToYoungSpace: function(objects) {
// PartialGC: link new objects into young list
// and give them positive oops temporarily so finalization works
var tempOop = this.lastOldObject.oop + 1;
for (var i = 0; i < objects.length; i++) {
var obj = objects[i];
if (this.hasNewInstances[obj.oop]) {
delete this.hasNewInstances[obj.oop];
this.hasNewInstances[tempOop] = true;
}
obj.oop = tempOop;
obj.nextObject = objects[i + 1];
tempOop++;
}
},
cleanupYoungSpace: function(objects) {
// PartialGC: After finalizing weak refs, make oops
// in young space negative again
var obj = objects[0],
youngOop = -1;
while (obj) {
if (this.hasNewInstances[obj.oop]) {
delete this.hasNewInstances[obj.oop];
this.hasNewInstances[youngOop] = true;
}
obj.oop = youngOop;
obj.mark = false;
obj = obj.nextObject;
youngOop--;
}
},
},
'creating', {
registerObject: function(obj) {
// We don't actually register the object yet, because that would prevent
// it from being garbage-collected by the Javascript collector
obj.oop = -(++this.newSpaceCount); // temp oops are negative. Real oop assigned when surviving GC
this.lastHash = (13849 + (27181 * this.lastHash)) & 0xFFFFFFFF;
return this.lastHash & 0xFFF;
},
registerObjectSpur: function(obj) {
// We don't actually register the object yet, because that would prevent
// it from being garbage-collected by the Javascript collector
obj.oop = -(++this.newSpaceCount); // temp oops are negative. Real oop assigned when surviving GC
return 0; // actual hash created on demand
},
instantiateClass: function(aClass, indexableSize, filler) {
var newObject = new (aClass.classInstProto()); // Squeak.Object
var hash = this.registerObject(newObject);
newObject.initInstanceOf(aClass, indexableSize, hash, filler);
this.hasNewInstances[aClass.oop] = true; // need GC to find all instances
return newObject;
},
clone: function(object) {
var newObject = new (object.sqClass.classInstProto()); // Squeak.Object
var hash = this.registerObject(newObject);
newObject.initAsClone(object, hash);
this.hasNewInstances[newObject.sqClass.oop] = true; // need GC to find all instances
return newObject;
},
},
'operations', {
bulkBecome: function(fromArray, toArray, twoWay, copyHash) {
if (!fromArray)
return !toArray;
var n = fromArray.length;
if (n !== toArray.length)
return false;
// need to visit all objects: find young objects now
// so oops do not change later
var firstYoungObject = null;
if (this.newSpaceCount > 0)
firstYoungObject = this.partialGC("become"); // does update context
else
this.vm.storeContextRegisters(); // still need to update active context
// obj.oop used as dict key here is why we store them
// rather than just calculating at image snapshot time
var mutations = {};
for (var i = 0; i < n; i++) {
var obj = fromArray[i];
if (!obj.sqClass) return false; //non-objects in from array
if (mutations[obj.oop]) return false; //repeated oops in from array
else mutations[obj.oop] = toArray[i];
}
if (twoWay) for (var i = 0; i < n; i++) {
var obj = toArray[i];
if (!obj.sqClass) return false; //non-objects in to array
if (mutations[obj.oop]) return false; //repeated oops in to array
else mutations[obj.oop] = fromArray[i];
}
// unless copyHash is false, make hash stay with the reference, not with the object
if (copyHash) for (var i = 0; i < n; i++) {
if (!toArray[i].sqClass) return false; //cannot change hash of non-objects
var fromHash = fromArray[i].hash;
fromArray[i].hash = toArray[i].hash;
toArray[i].hash = fromHash;
// Spur class table is not part of the object memory in SqueakJS
// so won't be updated below, we have to update it manually
if (this.isSpur && this.classTable[fromHash] === fromArray[i]) {
this.classTable[fromHash] = toArray[i];
}
}
// temporarily append young objects to old space
this.lastOldObject.nextObject = firstYoungObject;
// Now, for every object...
var obj = this.firstOldObject;
while (obj) {
// mutate the class
var mut = mutations[obj.sqClass.oop];
if (mut) {
obj.sqClass = mut;
if (mut.oop < 0) obj.dirty = true;
}
// and mutate body pointers
var body = obj.pointers;
if (body) for (var j = 0; j < body.length; j++) {
mut = mutations[body[j].oop];
if (mut) {
body[j] = mut;
if (mut.oop < 0) obj.dirty = true;
}
}
obj = obj.nextObject;
}
// separate old / young space again
this.lastOldObject.nextObject = null;
this.vm.flushMethodCacheAfterBecome(mutations);
return true;
},
objectAfter: function(obj) {
// if this was the last old object, continue with young objects
return obj.nextObject || this.nextObjectWithGC("nextObject", obj);
},
someInstanceOf: function(clsObj) {
var obj = this.firstOldObject;
while (obj) {
if (obj.sqClass === clsObj)
return obj;
obj = obj.nextObject || this.nextObjectWithGCFor(obj, clsObj);
}
return null;
},
nextInstanceAfter: function(obj) {
var clsObj = obj.sqClass;
while (true) {
obj = obj.nextObject || this.nextObjectWithGCFor(obj, clsObj);
if (!obj) return null;
if (obj.sqClass === clsObj)
return obj;
}
},
nextObjectWithGC: function(reason, obj) {
// obj is either the last object in old space (after enumerating it)
// or young space (after enumerating the list returned by partialGC)
// or a random new object
var limit = obj.oop > 0 ? 0 : this.youngSpaceCount;
if (this.newSpaceCount <= limit) return null; // no more objects
if (obj.oop < 0) this.fullGC(reason); // found a non-young new object
return this.partialGC(reason);
},
nextObjectWithGCFor: function(obj, clsObj) {
// this is nextObjectWithGC but avoids GC if no instances in new space
if (!this.hasNewInstances[clsObj.oop]) return null;
return this.nextObjectWithGC("instance of " + clsObj.className(), obj);
},
allInstancesOf: function(clsObj) {
var obj = this.firstOldObject,
result = [];
while (obj) {
if (obj.sqClass === clsObj) result.push(obj);
obj = obj.nextObject || this.nextObjectWithGCFor(obj, clsObj);
}
return result;
},
writeToBuffer: function() {
var headerSize = 64,
data = new DataView(new ArrayBuffer(headerSize + this.oldSpaceBytes)),
pos = 0;
var writeWord = function(word) {
data.setUint32(pos, word);
pos += 4;
};
writeWord(this.formatVersion()); // magic number
writeWord(headerSize);
writeWord(this.oldSpaceBytes); // end of memory
writeWord(this.firstOldObject.addr()); // base addr (0)
writeWord(this.objectToOop(this.specialObjectsArray));
writeWord(this.lastHash);
writeWord((800 << 16) + 600); // window size
while (pos < headerSize)
writeWord(0);
// objects
var obj = this.firstOldObject,
n = 0;
while (obj) {
pos = obj.writeTo(data, pos, this);
obj = obj.nextObject;
n++;
}
if (pos !== data.byteLength) throw Error("wrong image size");
if (n !== this.oldSpaceCount) throw Error("wrong object count");
return data.buffer;
},
objectToOop: function(obj) {
// unsigned word for use in snapshot
if (typeof obj === "number")
return obj << 1 | 1; // add tag bit
if (obj.oop < 0) throw Error("temporary oop");
return obj.oop;
},
bytesLeft: function() {
return this.totalMemory - this.oldSpaceBytes;
},
formatVersion: function() {
return this.isSpur ? 6521 : this.hasClosures ? 6504 : 6502;
},
segmentVersion: function() {
// a more complex version that tells both the word reversal and the endianness
// of the machine it came from. Low half of word is 6502. Top byte is top byte
// of #doesNotUnderstand: ($d on big-endian or $s on little-endian).
// In SqueakJS we write non-Spur images and segments as big-endian, Spur as little-endian
// (TODO: write non-Spur as little-endian too since that matches all modern platforms)
var dnuFirstWord = this.isSpur ? 'seod' : 'does';
return this.formatVersion() | (dnuFirstWord.charCodeAt(0) << 24);
},
storeImageSegment: function(segmentWordArray, outPointerArray, arrayOfRoots) {
// This primitive will store a binary image segment (in the same format as the Squeak image file) of the receiver and every object in its proper tree of subParts (ie, that is not refered to from anywhere else outside the tree). Note: all elements of the receiver are treated as roots determining the extent of the tree. All pointers from within the tree to objects outside the tree will be copied into the array of outpointers. In their place in the image segment will be an oop equal to the offset in the outpointer array (the first would be 4). but with the high bit set.
// The primitive expects the array and wordArray to be more than adequately long. In this case it returns normally, and truncates the two arrays to exactly the right size. If either array is too small, the primitive will fail, but in no other case.
// use a DataView to access the segment as big-endian words
var segment = new DataView(segmentWordArray.words.buffer),
pos = 0, // write position in segment in bytes
outPointers = outPointerArray.pointers,
outPos = 0; // write position in outPointers in words
// write header
segment.setUint32(pos, this.segmentVersion()); pos += 4;
// we don't want to deal with new space objects
this.fullGC("storeImageSegment");
// First mark the root array and all root objects
arrayOfRoots.mark = true;
for (var i = 0; i < arrayOfRoots.pointers.length; i++)
if (typeof arrayOfRoots.pointers[i] === "object")
arrayOfRoots.pointers[i].mark = true;
// Then do a mark pass over all objects. This will stop at our marked roots,
// thus leaving our segment unmarked in their shadow
this.markReachableObjects();
// Finally unmark the rootArray and all root objects
arrayOfRoots.mark = false;
for (var i = 0; i < arrayOfRoots.pointers.length; i++)
if (typeof arrayOfRoots.pointers[i] === "object")
arrayOfRoots.pointers[i].mark = false;
// helpers for mapping objects to segment oops
var segmentOops = {}, // map from object oop to segment oop
todo = []; // objects that were added to the segment but still need to have their oops mapped
// if an object does not yet have a segment oop, write it to the segment or outPointers
function addToSegment(object) {
var oop = segmentOops[object.oop];
if (!oop) {
if (object.mark) {
// object is outside segment, add to outPointers
if (outPos >= outPointers.length) return 0; // fail if outPointerArray is too small
oop = 0x80000004 + outPos * 4;
outPointers[outPos++] = object;
// no need to mark outPointerArray dirty, all objects are in old space
} else {
// add object to segment.
if (pos + object.totalBytes() > segment.byteLength) return 0; // fail if segment is too small
oop = pos + (object.snapshotSize().header + 1) * 4; // addr plus extra headers + base header
pos = object.writeTo(segment, pos, this);
// the written oops inside the object still need to be mapped to segment oops
todo.push(object);
}
segmentOops[object.oop] = oop;
}
return oop;
}
addToSegment = addToSegment.bind(this);
// if we have to bail out, clean up what we modified