-
Notifications
You must be signed in to change notification settings - Fork 8
/
vm.js
4661 lines (4557 loc) · 202 KB
/
vm.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
module('users.codefrau.St78.vm').requires().toRun(function() {
/*
* Copyright (c) 2013-2020 Vanessa Freudenberg and Dan Ingalls
*
* 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.
*/
NT = {
VM_DATE: "2024-01-11",
MAX_INSTSIZE: 0x100000, // arbitrary limit on instance size
largeOops: true, // automatically switch to 32 bit image format
OOP_NIL: 0,
OOP_FALSE: 2,
OOP_TRUE: 4,
OOP_THEPROCESS: 6,
OOP_SMALLTALK: 8,
// known classes
OOP_CLCLASS: 0x20,
OOP_CLINTEGER: 0x40, // class of SmallIntegers
OOP_CLSTRING: 0x60,
OOP_CLVECTOR: 0x80,
OOP_CLSTREAM: 0xa0,
OOP_CLFLOAT: 0xc0,
OOP_CLPROCESS: 0xe0,
OOP_CLREMOTECODE: 0x100,
OOP_CLPOINT: 0x120,
OOP_CLNATURAL: 0x140,
OOP_CLLARGEINTEGER: 0x160,
OOP_CLUNIQUESTRING: 0x1a0,
OOP_CLCOMPILEDMETHOD: 0x1e0,
OOP_CLRECTANGLE: 0x2a0,
OOP_CLVLENGTHCLASS: 0x9c0,
OOP_MASK: 0x1F, // mask for class oops
OOP_TAG_SMALL: 0x1E, // tag for 16 bit size header
OOP_TAG_LARGE: 0x1F, // tag for 32 bit size header
// CLCLASS layout:
PI_CLASS_TITLE: 0,
PI_CLASS_MYINSTVARS: 1,
PI_CLASS_INSTSIZE: 2,
PI_CLASS_MDICT: 3,
PI_CLASS_CLASSVARS: 4,
PI_CLASS_SUPERCLASS: 5,
PI_CLASS_ENVIRONMENT: 6,
// CLSTREAM layout:
PI_STREAM_ARRAY: 0,
PI_STREAM_POSITION: 1,
PI_STREAM_LIMIT: 2,
// CLPROCESS layout:
PI_PROCESS_MINSIZE: 0, // THEPROCESS: 128
PI_PROCESS_HWM: 1, // THEPROCESS: 0
PI_PROCESS_TOP: 2, // THEPROCESS: 7
PI_PROCESS_RESTARTCODE: 3, // THEPROCESS: NIL
PI_PROCESS_STACK: 4, // THEPROCESS: NIL
PN_PROCESS: 5, // number of fixed pointers
// CLREMOTECODE layout:
PI_RCODE_FRAMEOFFSET: 0,
PI_RCODE_STARTINGPC: 1,
PI_RCODE_PROCESS: 2,
PI_RCODE_STACKOFFSET: 3,
// CLHASHSET layout:
PI_HASHSET_OBJECTS: 0,
// CLDICTIONARY layout:
PI_DICTIONARY_OBJECTS: 0,
PI_DICTIONARY_VALUES: 1,
// CLSYMBOLTABLE layout:
PI_SYMBOLTABLE_OBJECTS: 0,
PI_SYMBOLTABLE_VALUES: 1,
// CLMESSAGEDICT layout:
PI_MESSAGEDICT_OBJECTS: 0,
PI_MESSAGEDICT_METHODS: 1,
// CLOBJECTREFERENCE layout:
PI_OBJECTREFERENCE_VALUE: 0,
// CLCOMPILEDMETHOD layout:
BI_COMPILEDMETHOD_FIRSTLITERAL: 2, // past method header
PC_BIAS: 2, // due to NT's shorter header format
// CLPOINT layout:
PI_POINT_X: 0,
PI_POINT_Y: 1,
// CLLARGEINTEGER layout:
PI_LARGEINTEGER_BYTES: 0,
PI_LARGEINTEGER_NEG: 1,
/* | i . (1 to: TextScanner instvars length) transform⦂ i to⦂ [(i-1),(TextScanner instvars◦i)] ==>
((0 'function' ) (1 'color' ) (2 'destbase' ) (3 'destraster' ) (4 'destx' ) (5 'desty' ) (6 'width' ) (7 'height' ) (8 'sourcebase' ) (9 'sourceraster' ) (10 'sourcex' ) (11 'sourcey' ) (12 'clipx' ) (13 'clipy' ) (14 'clipwidth' ) (15 'clipheight' ) (16 'sourcefield' ) (17 'destfield' ) (18 'source' ) (19 'dest' ) (20 'sstrike' ) (21 'dstrike' ) (22 'printing' ) (23 'chari' ) (24 'stopx' ) (25 'xtable' ) (26 'exceptions' ) (27 'spacecount' ) (28 'spacei' ) (29 'spacex' ) (30 'charpad' ) (31 'text' ) (32 'spacesize' ) (33 'style' ) (34 'para' ) (35 'font' ) (36 'fontno' ) (37 'minascii' ) (38 'maxascii' ) (39 'glyphs' ) (40 'frame' ) (41 'looktype' ) (42 'kern' ) ) */
// CLBITBLT layout:
PI_BITBLT_FUNCTION: 0,
PI_BITBLT_GRAY: 1,
PI_BITBLT_DESTBITS: 2,
PI_BITBLT_DESTRASTER: 3,
PI_BITBLT_DESTX: 4,
PI_BITBLT_DESTY: 5,
PI_BITBLT_WIDTH: 6,
PI_BITBLT_HEIGHT: 7,
PI_BITBLT_SOURCEBITS: 8,
PI_BITBLT_SOURCERASTER: 9,
PI_BITBLT_SOURCEX: 10,
PI_BITBLT_SOURCEY: 11,
PI_BITBLT_CLIPX: 12,
PI_BITBLT_CLIPY: 13,
PI_BITBLT_CLIPWIDTH: 14,
PI_BITBLT_CLIPHEIGHT: 15,
PI_BITBLT_SOURCEFIELD: 16,
PI_BITBLT_DESTFIELD: 17,
PI_BITBLT_SOURCE: 18,
PI_BITBLT_DEST: 19,
PI_BITBLT_PRINTING: 22,
PI_BITBLT_CHARI: 23,
PI_BITBLT_STOPX: 24,
PI_BITBLT_XTABLE: 25,
PI_BITBLT_EXCEPTIONS: 26,
PI_BITBLT_CHARPAD: 30,
PI_BITBLT_TEXT: 31,
PI_BITBLT_MINASCII: 37,
PI_BITBLT_MAXASCII: 38,
PI_BITBLT_KERN: 42,
// CLFORM layout:
PI_FORM_EXTENT: 0,
PI_FORM_BITS: 1,
// also: offset figure ground
// CLCURSOR layout:
PI_CURSOR_BITSTR: 0,
PI_CURSOR_OFFSET: 1,
// runtime indices and offsets:
// process frame layout (off BP):
FI_FIRST_TEMP: -1,
// nominal stack frame contains six items, as follow:
FI_SAVED_BP: 0,
FI_CALLER_PC: 1,
FI_NUMARGS: 2,
FI_METHOD: 3,
FI_MCLASS: 4,
FI_RECEIVER: 5, // top stack item in previous frame
//
FI_LAST_ARG: 6, // stack item in previous frame
//
F_FRAMESIZE: 5, // don't count args nor receiver...
// Class instSize format (assuming untagged integer!):
FMT_HASPOINTERS: 0x4000,
FMT_HASWORDS: 0x2000,
FMT_ISVARIABLE: 0x1000,
FMT_BYTELENGTH: 0x07ff,
// Ints
MAX_INT: 0x3FFF,
MIN_INT: -0x4000,
NON_INT: -0x5000, // non-small and neg (so non pos16 too)
// Display colors
BLACK: 0xFF000000,
WHITE: 0xFFFFFFFF,
// Event constants
Mouse_Blue: 1,
Mouse_Yellow: 2,
Mouse_Red: 4,
Key_Shift: 8,
Key_Ctrl: 16,
Key_Meta: 32, // Cmd on Mac, Alt on PC
// original keyboard map used inside the image
// set to vm.image.globalNamed('NTkbMap').bytes on startup
kbMap: [
255, 91, 255, 110, 104, 103, 114, 255, 25, 61, 32, 109, 56, 121, 116, 173,
13, 46, 122, 106, 255, 9, 49, 255, 95, 59, 255, 98, 99, 102, 160, 29,
39, 108, 120, 57, 115, 119, 51, 158, 93, 44, 111, 105, 97, 113, 50, 30,
47, 45, 48, 117, 55, 54, 53, 8, 92, 112, 107, 118, 100, 101, 52, 29,
255, 123, 255, 78, 72, 71, 82, 255, 25, 43, 32, 77, 42, 89, 84, 173,
13, 62, 90, 74, 255, 9, 33, 255, 94, 58, 255, 66, 67, 70, 160, 29,
34, 76, 88, 40, 83, 87, 35, 22, 125, 60, 79, 73, 65, 81, 90, 30,
63, 21, 41, 85, 38, 126, 37, 8, 124, 80, 75, 86, 68, 69, 36, 255,
255, 91, 255, 78, 72, 71, 82, 255, 25, 61, 32, 77, 56, 89, 84, 173,
13, 46, 90, 74, 255, 9, 49, 255, 95, 59, 255, 66, 67, 70, 160, 29,
39, 76, 88, 57, 83, 87, 51, 158, 93, 44, 79, 73, 65, 81, 90, 30,
47, 45, 48, 85, 55, 54, 53, 8, 92, 80, 75, 86, 68, 69, 52, 255,
255, 7, 255, 14, 179, 7, 18, 255, 25, 6, 32, 182, 180, 25, 6, 173,
13, 18, 167, 165, 255, 9, 159, 255, 17, 3, 255, 166, 3, 6, 160, 29,
15, 153, 151, 149, 19, 145, 143, 255, 23, 1, 15, 150, 1, 17, 167, 30,
27, 137, 135, 21, 131, 129, 127, 8, 14, 138, 136, 134, 132, 130, 128, 255,
255, 249, 255, 245, 243, 30, 239, 255, 25, 14, 32, 246, 244, 242, 240, 173,
13, 233, 231, 229, 255, 9, 223, 255, 246, 3, 255, 230, 228, 226, 160, 24,
219, 217, 215, 213, 211, 209, 207, 22, 220, 218, 226, 214, 212, 210, 231, 30,
203, 201, 199, 197, 195, 193, 191, 8, 204, 202, 200, 198, 196, 194, 192, 192],
// symbolic NT keycodes (it uses ASCII for 32-126)
kbSymbolic: {
tab: 9,
cr: 13,
// Dispframe>>kbd
ctld: 132,
ctlw: 145,
ctlx: 151,
// TextImage>>classInit, kbd
bs: 8,
ctlw: 145, // delete word?
cut: 173,
paste: 158,
esc: 160,
// TextImage>>checkLooks
ctlb: 166, // bold
ctli: 150, // italic
ctlminus: 137,
ctlx: 151, // reset emph
ctlB: 230, // non-bold
ctlI: 214, // non-italic
ctlMinus: 201,
ctlX: 215, // reset emph
ctl0: 135, // font 0
ctl1: 159, // font 1
ctl2: 144, // font 2
ctl3: 143, // font 3
ctl4: 128, // font 4
ctl5: 127, // font 5
ctl6: 129, // font 6
ctl7: 131, // font 7
ctl8: 180, // font 8
ctl9: 149, // font 9
ctlShift0: 199, // font 10
ctlShift1: 223, // font 11
ctlShift2: 208, // font 12
ctlShift3: 207, // font 13
ctlShift4: 192, // font 14
ctlShift5: 191, // font 15
ctlt: 240, // toBravo
ctlf: 226, // fromBravo
// newly assigned
smaller: 228,
larger: 229,
doit: 130,
prompt: 167,
again: 134,
selectAll: 136,
compile: 138,
undo: 153,
cancel: 165,
left: 193,
right: 194,
up: 195,
down: 196,
pageUp: 197,
pageDown: 198,
home: 202,
end: 203,
search: 204,
},
// key bindings: html keydown code to NT symbolic
kbCommands: {
'.': "interrupt",
'd': "doit",
'p': "doit", // printit
'D': "prompt",
'j': "again",
'a': "selectAll",
's': "compile",
'z': "undo",
'l': "cancel",
'f': "search",
'b': "ctlb", // bold
'i': "ctli", // italic
'u': "ctlminus", // underline
'x': "ctlx", // reset emph
'B': "ctlB", // bold
'I': "ctlI", // italic
'U': "ctlMinus", // underline
'X': "ctlX", // reset emph
'0': "ctl0", // font change
'1': "ctl1",
'2': "ctl2",
'3': "ctl3",
'4': "ctl4",
'5': "ctl5",
'6': "ctl6",
'7': "ctl7",
'8': "ctl8",
'9': "ctl9",
'-': "smaller",
'_': "smaller",
'+': "larger",
'=': "larger",
},
// key bindings: html keypress code to unicode
// var 31 = 31;
kbSpecial: {
35: '↪', // #: Unique string
64: '⌾', // @: make point
94: '⇑', // ^: return
95: '←', // _: assignment
96: 'ⓢ', // `: 's operator
1: '◦', // ^A: At
3: '⦂', // ^C: open Colon
4: 'ctld', // ^D
5: '∢', // ^E: Eye
6: '⇒', // ^F: iF
7: '≥', // ^G: Greater or equal
// 8: ^H = backspace
// 9: ^I = tab
12: '≤', // ^L: Lesser or equal
// 13: ^M = return
14: '≠', // ^N: Not equal
17: '◻', // ^Q: sQuare
19: 'ⓢ', // ^S: 's operator
20: '≡', // ^T: Triple equal
21: '↪', // ^U: Unique string
22: '➲', // ^V: inVerse arrow
23: 'ctlw', // ^W: delete word
24: '▱', // ^X
29: '◢', // ^]: doit
30: '↑', // ^^: single up arrow
31: '¬', // ^_: unary minus
},
// encoding of notetaker glyphs as printable unicode chars
toUnicode: {
'\x00': "␀",
'\x01': "≤",
'\x02': "␂",
'\x03': "⦂",
'\x04': "␄",
'\x05': "√",
'\x06': "≡",
'\x07': "◦",
'\x08': "␈",
//'\x09': "␉", // keep TAB
'\x0a': "␊",
'\x0b': "␋",
'\x0c': "␌",
'\x0d': "\n", // CR becomes LF
'\x0e': "≠",
'\x0f': "↪",
'\x10': "␐",
'\x11': "⇑",
'\x12': "≥",
'\x13': "ⓢ",
'\x14': "◣",
'\x15': "¬",
'\x16': "∢",
'\x17': "⌾",
'\x18': "▱",
'\x19': "➲",
'\x1a': "␚",
'\x1b': "⇒",
'\x1c': "␜",
'\x1d': "◻︎",
'\x1e': "◢",
'\x1f': "␟",
'\x7f': "␡",
'_' : "←",
'^' : "↑",
},
};
Object.subclass('St78.vm.ObjectTableReader',
'about', {
about: function() {
/*
ot is the object table, a sequence of 4-byte entries, retrievable by this.otAt(oop), where oop is an object pointer with the bottom two bits = 0. The entry encodes the data address, along with some other bits including a reference count that we can now ignore. The method dataAddress(oop) will retrieve the address, also taking into account the "dataBias" which I won't explain.
data is the object data space, a sequence of 2-byte words, retrievable by this.fieldOfObject(i, oop), where oop is an object pointer with the bottom two bits = 0, and i is the instance field number, with 1 being the index of the first field. An index of 0 would retrieve the class pointer of an object, but this must be masked by 0xFFC0 because the bottom 6 bits of the class word are used for the object's size in bytes. The method classOfOop will do this for you. This implies that all class oops have zero in the bottom 6 bits. This worked out nicely for OOZE's zones, but we will drop all that and go to the Squeak object format or whatever Vanessa is using internally. Note that if the size field is zero, then there is a word before the class with a 16-bit length. The method lengthBitsAt decodes this for you. It appears that the size field is the size in bytes, including the class(and size), so a string of length 1 has size=3, and a Point would have a size = 6.
The format of classes is (quoting from the system itself...
title "<String> for identification, printing"
myinstvars "<String> partnames for compiling, printing"
instsize "<Integer> for storage management"
messagedict "<MessageDict> for communication, compiling"
classvars "<Dictionary/nil> compiler checks here"
superclass "<Class> for execution of inherited behavior"
environment "<Vector of SymbolTables> for external refs"
fieldtype
The instsize is an integer (ie low bit = 1) with the following interpretation:
0x8000 - fields are pointers, else not
0x4000 - fields are words, else bytes
0x2000 - instances are variable length
0x0FFE - instance size in words including class
Thus Point has instsize = 0x8006 and Float has instsize = 04008 (nasty 3-word binary format)
*/
},
},
'initialize', {
initialize: function(objTable, objSpace, bias) {
this.ot = objTable;
this.data = objSpace;
this.dataBias = bias;
}
},
'reading', {
readObjects: function() {
// create js objects for the st78 objects in ot+data
var oopMap = {};
for (var oti = 0; oti < this.ot.length; oti += 4) {
var oop = oti / 2; // 1 more bit for our oops so we get up to 32 K objects
if (this.refCountOf(oop)) {
oopMap[oop] = new St78.vm.Object(oop);
}
}
return oopMap;
}
},
'object access', {
otAt: function(oop) {
// Return the OT entry for the oop
// Decode two two-byte numbers into one 32-bit number
var i = oop * 2,
val = 0;
val = this.ot[i+1];
val = val*256 + this.ot[i];
val = val*256 + this.ot[i+3];
val = val*256 + this.ot[i+2];
return val;
},
dataAddress: function(oop) {
var entry = this.otAt(oop);
return (entry&0xFFFF) * 16 + ((entry>>16)&0x1E) - this.dataBias;
},
fieldOfObject: function(i, oop) {
// i = 1 for first field after class
var addr = this.dataAddress(oop);
var a = addr+(2*i);
return this.data[a+1]*256 + this.data[a];
},
classOfOop: function(oop) {
return (this.fieldOfObject(0, oop) & 0xFFC0) / 2; // our oops are half the original
},
refCountOf: function (oop) {
return this.otAt(oop) >>> 24;
},
isInteger: function(oop) {
return oop & 1;
},
lengthBitsAtAddr: function(addr) {
var len = this.data[addr] & 0x3F;
if (len > 0) return len;
return this.data[addr-1] * 256 + this.data[addr-2];
},
});
Object.subclass('St78.vm.Image',
'about', {
about: function() {
/*
Object Format
=============
Each St78 object is a St78.vm.Object, only SmallIntegers are JS numbers.
Instance variables/fields reference other objects directly via the "pointers" property.
{
stClass: reference to class object
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
oop: unique integer (16 bits, lsb is 0, in classes 5 lower bits are 0)
mark: boolean (used only during GC, otherwise false)
nextObject: linked list of objects in old space (new space objects do not have this yet)
}
Object Table
============
Unlike the original Notetaker implementation, there is no object table.
Objects use direct references. We have immediate untagged ints (+/-16K).
The snapshot image format uses 16 bit words for oops (even) and tags the ints (odd).
If there are more than 32K objects, and NT.largeOops is true, we us snapshot image format 2.0
with 32 bit words for oops. SmallIntegers are still only +/-16K but stored as 32 bit words.
*/
}
},
'initializing', {
initialize: function(oopMap, process, display, name, convertTaggedInts, largeOops) {
this.name = name;
this.largeOops = largeOops || 0;
this.maxTenuresBeforeGC = 1000;
this.tenuresSinceLastGC = 0;
this.gcCount = 0;
this.newSpaceCount = 0;
this.oldSpaceCount = 0;
this.oldSpaceBytes = 0;
this.nextTempOop = -2; // new objects get negative preliminary oops
this.freeOops = []; // pool for real oops
this.freeClassOops = []; // pool for real class oops (lower bits 0)
// link all objects into oldspace
var prevObj,
large = !!this.largeOops,
maxOop = Math.max(this.largeOops, 0xFFFE);
for (var oop = 0; oop <= maxOop; oop += 2)
if (oopMap[oop]) {
this.oldSpaceCount++;
this.oldSpaceBytes += oopMap[oop].totalBytes(large);
if (prevObj) prevObj.nextObject = oopMap[oop];
prevObj = oopMap[oop];
} else if (oop < 0x10000) {
(oop & NT.OOP_MASK ? this.freeOops : this.freeClassOops).push(oop);
}
this.firstOldObject = oopMap[0];
this.lastOldObject = prevObj;
this.userProcess = process;
this.userDisplay = display;
this.initKnownObjects(oopMap);
this.initCompiledMethods(oopMap, convertTaggedInts);
console.log("Loaded image " + this.name);
},
initKnownObjects: function(oopMap) {
oopMap[NT.OOP_NIL].isNil = true;
oopMap[NT.OOP_TRUE].isTrue = true;
oopMap[NT.OOP_FALSE].isFalse = true;
this.globals = oopMap[NT.OOP_SMALLTALK];
this.specialOopsVector = this.globalNamed('SpecialOops');
},
initCompiledMethods: function(oopMap, convertTaggedInts) {
// make proper pointer objects for literals encoded in bytes
var cmClass = this.objectFromOop(NT.OOP_CLCOMPILEDMETHOD, oopMap),
cm = this.someInstanceOf(cmClass);
while (cm) {
cm.methodInitLits(this, oopMap, convertTaggedInts);
cm = this.nextInstanceAfter(cm);
}
},
globalRefNamed: function(name) {
var ref = this.globals.symbolTableRefNamed(name);
if (!ref) {
// try other symbol tables
var tableClass = this.globals.stClass,
table = this.firstOldObject;
while ((table = table.nextObject) && !ref) {
if (table.stClass !== tableClass) continue;
if (table !== this.globals)
ref = table.symbolTableRefNamed(name);
}
}
return ref;
},
selectorNamed: function(name) {
var symbolClass = this.objectFromOop(NT.OOP_CLUNIQUESTRING),
symbol = this.someInstanceOf(symbolClass);
while (symbol) {
if (name.length === symbol.bytes.length && name === symbol.bytesAsUnicode())
return symbol;
symbol = this.nextInstanceAfter(symbol);
}
},
globalNamed: function(name) {
return this.globalRefNamed(name).pointers[NT.PI_OBJECTREFERENCE_VALUE];
},
smallifyLargeInts: function() {
// visit every pointer field of every object, converting smallable LargeInts to Integers
// We do this because the normal ST-76 range is +-32K
var lgIntClass = this.objectFromOop(NT.OOP_CLLARGEINTEGER),
obj = this.firstOldObject;
while (obj) {
var body = obj.pointers;
if (body) {
for (var i=0; i<body.length; i++) {
if (body[i].stClass === lgIntClass) {
var value = body[i].largeIntegerValue();
if (value <= 32767 && value >= -32768) body[i] = value
}
}
}
obj = obj.nextObject;
}
},
},
'garbage collection', {
fullGC: function() {
// 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,
// and then linking them into old space.
// Note: after an old object is released, its "nextObject" ref must still allow traversal
// of all remaining objects. This is so enumeration works despite GC.
var newObjects = this.markReachableObjects();
var removedObjects = this.removeUnmarkedOldObjects();
if (this.largeOops) this.compactLargeOops(); // possibly sets largeOops to false
this.appendToOldObjects(newObjects);
if (this.largeOops) this.updateOldSpaceBytes();
/*
this.spaceReport(newObjects, removedObjects, function(line){console.log(line)});
console.log(Strings.format("GC: %s allocations, %s unchecked tenures, %s released, %s tenured, now %s total (%s bytes)",
this.newSpaceCount, this.tenuresSinceLastGC, removedObjects.length, newObjects.length, this.oldSpaceCount, this.oldSpaceBytes));
*/
this.tenuresSinceLastGC = 0;
this.newSpaceCount = 0;
this.nextTempOop = -2;
this.gcCount++;
return this.availableOops();
},
allocateOopFor: function(anObj) {
// get an oop from the pool of unused oops
var isClass = anObj.isClass(),
pool = isClass ? this.freeClassOops : this.freeOops;
if (pool.length > 0) {
return anObj.oop = pool.pop();
}
// support for more than 32 K objects
if (!this.largeOops && NT.largeOops) {
this.largeOops = 0xFFFE; // so first large oop is 0x10000
console.log("Too many oops - switching from 16 to 32 bits");
}
if (this.largeOops >= 0xFFFE && this.largeOops <= 0xFFFFFFF0) {
return anObj.oop = this.largeOops += 2;
}
this.vm.primHandler.filePut('spacereport.txt', this.spaceReport());
throw isClass ? "too many classes" : "too many objects";
},
freeOopFor: function(anObj) {
if (anObj.oop > 0) {
if (anObj.oop < 0x10000) {
(anObj.oop & NT.OOP_MASK ? this.freeOops : this.freeClassOops).push(anObj.oop);
}
anObj.oop = null;
} else throw "attempt to free invalid oop";
},
markReachableObjects: function() {
// Visit all reachable objects and mark them.
// Return surviving new objects
if (this.vm) {
this.userProcess = this.vm.activeProcess;
this.userDisplay = this.vm.primHandler.displayBlt;
}
var todo = [this.globals, this.userProcess];
if (this.userDisplay) // stored in image header so must be retained
todo.push(this.userDisplay);
var newObjects = [];
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.stClass.mark) // trace class if not marked
todo.push(object.stClass);
var body = object.pointers;
if (body) // trace all unmarked pointers
for (var i = 0; i < body.length; i++)
if (typeof body[i] === "object" && !body[i].mark) // except SmallInts
todo.push(body[i]);
}
return newObjects;
},
removeUnmarkedOldObjects: function() {
// Unlink unmarked old objects from the nextObject linked list
// Reset marks of remaining objects
// Set this.lastOldObject to last old object
// Return removed old objects
var removed = [];
var obj = this.firstOldObject;
while (true) {
var next = obj.nextObject;
if (!next) {// we're done
this.lastOldObject = obj;
return removed;
}
// if marked, continue with next object
if (next.mark) {
next.mark = false; // unmark for next GC
obj = next;
} else { // otherwise, remove it
var corpse = next;
obj.nextObject = corpse.nextObject; // drop from list
this.oldSpaceCount--;
this.oldSpaceBytes -= corpse.totalBytes(!!this.largeOops);
this.freeOopFor(corpse);
removed.push(corpse);
}
}
},
appendToOldObjects: function(newObjects) {
// append new objects to linked list of old objects
// and unmark them. Also, assign a real oop.
// Note: also called outside GC to quickly tenure an object
var oldObj = this.lastOldObject;
for (var i = 0; i < newObjects.length; i++) {
var newObj = newObjects[i];
if (newObj.oop >= 0) {debugger; throw "attempt to tenure old object"}
newObj.mark = false;
this.allocateOopFor(newObj);
oldObj.nextObject = newObj;
oldObj = newObj;
this.oldSpaceCount++;
this.oldSpaceBytes += newObj.totalBytes(!!this.largeOops);
}
this.lastOldObject = oldObj;
},
compactLargeOops: function() {
if (this.freeOops.length > 0) {
// if we have free small oops, maybe we can fall back to 16 bits
return this.compactLargeOopsToSmall();
}
// otherwise just reassign oops in sequence
var nextOop = 0xFFFE; // so the first large oop is 0x10000
var obj = this.firstOldObject;
while (obj) {
if (obj.oop >= 0x10000) obj.oop = nextOop += 2;
obj = obj.nextObject;
}
this.largeOops = nextOop;
},
compactLargeOopsToSmall: function() {
// we had some free small oops, use those first, then large ones
this.largeOops = 0xFFFE; // so the first large oop is 0x10000
var obj = this.firstOldObject;
while (obj) {
if (obj.oop >= 0x10000) obj.oop = this.allocateOopFor(obj);
obj = obj.nextObject;
}
// if we did not use any large oops, switch back to 16 bits
if (this.largeOops === 0xFFFE) {
this.largeOops = 0;
this.updateOldSpaceBytes();
console.log("Freed oops - switching from 32 to 16 bits");
}
},
updateOldSpaceBytes: function() {
// with large oops, object size can change depending on the oops it holds
var large = !!this.largeOops,
obj = this.firstOldObject,
bytes = 0;
while (obj) {
bytes += obj.totalBytes(large);
obj = obj.nextObject;
}
this.oldSpaceBytes = bytes;
},
},
'creating', {
tempOop: function() {
// new objects get a temporary oop
this.newSpaceCount++;
return this.nextTempOop -= 2;
},
instantiateClass: function(aClass, indexableSize, nilObj) {
var newObject = new St78.vm.Object(this.tempOop());
newObject.initInstanceOf(aClass, indexableSize, nilObj);
return newObject;
},
},
'operations', {
bulkBecome: function(fromArray, toArray, twoWay) {
var n = fromArray.length;
if (n !== toArray.length)
return false;
var mutations = {};
for (var i = 0; i < n; i++) {
var obj = fromArray[i];
if (!obj.stClass) 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.stClass) return false; //non-objects in to array
if (mutations[obj.oop]) return false; //repeated oops in to array
else mutations[obj.oop] = fromArray[i];
}
// ensure new objects have nextObject pointers
if (this.newSpaceCount > 0)
this.fullGC();
// Now, for every object...
var obj = this.firstOldObject;
while (obj) {
// mutate the class
var mut = mutations[obj.stClass.oop];
if (mut) obj.stClass = mut;
// 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;
}
obj = obj.nextObject;
}
// finally, swap the oops so they stay with the pointer, not the object
for (var i = 0; i < n; i++) {
var temp = fromArray[i].oop;
fromArray[i].oop = toArray[i].oop;
toArray[i].oop = temp;
}
this.vm.flushMethodCacheAfterBecome(mutations);
return true;
},
diffFrom: function(base) {
// assumes both images have ordered oops
// which is the case right after loading them
var thisObj = this.firstOldObject,
baseObj = base.firstOldObject,
delta = [];
while (thisObj) {
if (!thisObj.sameAs(baseObj)) {
if (!baseObj || thisObj.oop <= baseObj.oop) {
// after end of base, or modified, or new
delta.push(thisObj);
if (baseObj && thisObj.oop < baseObj.oop) {
thisObj = thisObj.nextObject;
continue;
}
} else { // baseObj.oop < thisObj.oop
baseObj = baseObj.nextObject;
continue;
}
}
// same oops, or after end of base image
if (baseObj) baseObj = baseObj.nextObject;
thisObj = thisObj.nextObject;
}
return delta;
},
writeDiffToBuffer: function(baseImage) {
// write only objects in this image that are not in baseImage
// assumes both images are freshly loaded, not run
if (this.largeOops) throw new Error("32 bit image deltas not supported");
var delta = this.diffFrom(baseImage),
deltaBytes = 0;
for (var i = 0; i < delta.length; i++)
deltaBytes += delta[i].totalBytes(false);
var magic = 'Sd78',
version = 0x0100, // 1.0
headerSize = 18,
data = new DataView(new ArrayBuffer(headerSize + deltaBytes)),
pos = 0;
// magic bytes
for (var i = 0; i < 4; i++)
data.setUint8(pos++, magic.charCodeAt(i));
// version
data.setUint16(pos, version); pos += 2;
// header size
data.setUint16(pos, headerSize); pos += 2;
// delta size
data.setUint16(pos, delta.length); pos += 2;
data.setUint32(pos, deltaBytes); pos += 4;
// current process and display
data.setUint16(pos, this.userProcess.oop); pos += 2;
data.setUint16(pos, this.userDisplay.oop); pos += 2;
if (pos !== headerSize) throw "wrong header size";
// objects
for (var i = 0; i < delta.length; i++)
pos = delta[i].writeTo(data, pos, this);
if (pos !== headerSize + deltaBytes) throw "wrong image size";
return data.buffer;
},
writeToBuffer: function() {
this.fullGC(); // collect all objects
if (this.largeOops) return this.writeToBufferLarge();
var magic = 'St78',
version = 0x0100, // 1.0: 16 bit oops
headerSize = 18,
data = new DataView(new ArrayBuffer(headerSize + this.oldSpaceBytes)),
pos = 0;
// magic bytes
for (var i = 0; i < 4; i++)
data.setUint8(pos++, magic.charCodeAt(i));
// version
data.setUint16(pos, version); pos += 2;
// header size
data.setUint16(pos, headerSize); pos += 2;
// image size
data.setUint16(pos, this.oldSpaceCount); pos += 2;
data.setUint32(pos, this.oldSpaceBytes); pos += 4;
// current process and display
data.setUint16(pos, this.vm.activeProcess.oop); pos += 2;
data.setUint16(pos,this.vm.primHandler.displayBlt.oop); pos += 2;
if (pos !== headerSize) throw "wrong header size";
// objects
var obj = this.firstOldObject,
n = 0;
while (obj) {
pos = obj.writeTo(data, pos, this);
obj = obj.nextObject;
n++;
}
if (pos !== headerSize + this.oldSpaceBytes) throw "wrong image size";
if (n !== this.oldSpaceCount) throw "wrong object count";
return data.buffer;
},
writeToBufferLarge: function() {
// this.fullGC(); // happened already
var magic = 'St78',
version = 0x0200, // 2.0: 32 bit oops
headerSize = 28,
data = new DataView(new ArrayBuffer(headerSize + this.oldSpaceBytes)),
pos = 0;
// magic bytes
for (var i = 0; i < 4; i++)
data.setUint8(pos++, magic.charCodeAt(i));
// version
data.setUint16(pos, version); pos += 2;
// header size
data.setUint16(pos, headerSize); pos += 2;
// image size
data.setUint32(pos, this.oldSpaceCount); pos += 4;
data.setUint32(pos, this.oldSpaceBytes); pos += 4;
data.setUint32(pos, this.largeOops); pos += 4;
// current process and display
data.setUint32(pos, this.vm.activeProcess.oop); pos += 4;
data.setUint32(pos,this.vm.primHandler.displayBlt.oop); pos += 4;
if (pos !== headerSize) throw "wrong header size";
// objects
var obj = this.firstOldObject,
n = 0;
while (obj) {
pos = obj.writeToLarge(data, pos, this);
obj = obj.nextObject;
n++;
}
if (pos !== headerSize + this.oldSpaceBytes) throw "wrong image size";
if (n !== this.oldSpaceCount) throw "wrong object count";
return data.buffer;
},
objectFromOop: function(oop, optionalOopMap) {
if (oop & 1) {
var val = oop >> 1;
return (val & 0x3FFF) - (val & 0x4000);
}
if (optionalOopMap) return optionalOopMap[oop]; // only available at startup
// find the object with the given oop - looks only in oldSpace for now!
var obj = this.firstOldObject;
do {
if (oop === obj.oop) return obj;
obj = obj.nextObject;
} while (obj);
debugger;
throw "oop not found";
},
objectToOop: function(anObject) {
// newly created objects have a temporary oop, so assign a real one
if (typeof anObject === "number")
return (anObject * 2 + 0x10001) & 0xFFFF; // add tag bit, make unsigned
if (anObject.oop < 0) { // it's a temp oop
if (this.tenuresSinceLastGC++ > this.maxTenuresBeforeGC) {
console.log("Forcing GC after " + this.maxTenuresBeforeGC + " unchecked tenures");
this.fullGC(); // force a GC since we tenured many objects already
if (!(anObject.oop > 0))
throw "attempt to tenure unreachable object";
} else {
this.appendToOldObjects([anObject]); // just tenure the object
console.log("Tenuring " + anObject.stInstName(32));
}
}
return anObject.oop;
},
someInstanceOf: function(clsObj) {
var obj = this.firstOldObject;
while (true) {
if (obj.stClass === clsObj)
return obj;
if (!obj.nextObject) {
// this was the last old object, tenure new objects and try again
if (this.newSpaceCount > 0) this.fullGC();
// if this really was the last object, we're done
if (!obj.nextObject) return null;