-
Notifications
You must be signed in to change notification settings - Fork 65
/
CogVMSimulator.class.st
2766 lines (2396 loc) · 91.2 KB
/
CogVMSimulator.class.st
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
"
This class defines basic memory access and primitive simulation so that the CoInterpreter can run simulated in the Squeak environment. It also defines a number of handy object viewing methods to facilitate pawing around in the object memory. Remember that you can test the Cogit using its class-side in-image compilation facilities.
To see the thing actually run, you could (after backing up this image and changes), execute
(CogVMSimulator new openOn: Smalltalk imageName) test
and be patient both to wait for things to happen, and to accept various things that may go wrong depending on how large or unusual your image may be. We usually do this with a small and simple benchmark image.
Here's an example to launch the simulator in a window. The bottom-right window has a menu packed with useful stuff:
(CogVMSimulator newWithOptions: #(Cogit StackToRegisterMappingCogit))
desiredNumStackPages: 8;
openOn: '/Users/eliot/Cog/startreader.image';
openAsMorph;
run
Here's a hairier example that I (Eliot) actually use in daily development with some of the breakpoint facilities commented out.
| cos proc opts |
CoInterpreter initializeWithOptions: (opts := Dictionary newFromPairs: #(Cogit StackToRegisterMappingCogit)).
CogVMSimulator chooseAndInitCogitClassWithOpts: opts.
cos := CogVMSimulator new.
""cos initializeThreadSupport."" ""to test the multi-threaded VM""
cos desiredNumStackPages: 8. ""to set the size of the stack zone""
""cos desiredCogCodeSize: 8 * 1024 * 1024."" ""to set the size of the Cogit's code zone""
cos openOn: '/Users/eliot/Squeak/Squeak4.4/trunk44.image'. ""choose your favourite image""
""cos setBreakSelector: 'r:degrees:'."" ""set a breakpoint at a specific selector""
proc := cos cogit processor.
""cos cogit sendTrace: 7."" ""turn on tracing""
""set a complex breakpoint at a specific point in machine code""
""cos cogit singleStep: true; breakPC: 16r56af; breakBlock: [:cg| cos framePointer > 16r101F3C and: [(cos longAt: cos framePointer - 4) = 16r2479A and: [(cos longAt: 16r101F30) = (cos longAt: 16r101F3C) or: [(cos longAt: 16r101F2C) = (cos longAt: 16r101F3C)]]]]; sendTrace: 1"".
""[cos cogit compilationTrace: -1] on: MessageNotUnderstood do: [:ex|]."" ""turn on compilation tracing in the StackToRegisterMappingCogit""
""cos cogit setBreakMethod: 16rB38880.""
cos
openAsMorph;
""toggleTranscript;"" ""toggleTranscript will send output to the Transcript instead of the morph's rather small window""
halt;
run
"
Class {
#name : #CogVMSimulator,
#superclass : #CoInterpreterPrimitives,
#instVars : [
'parent',
'enableCog',
'byteCount',
'lastPollCount',
'lastExtPC',
'sendCount',
'lookupCount',
'printSends',
'traceOn',
'myBitBlt',
'displayForm',
'fakeForm',
'imageName',
'pluginList',
'mappedPluginEntries',
'quitBlock',
'transcript',
'displayView',
'eventTransformer',
'printFrameAtEachStep',
'printBytecodeAtEachStep',
'systemAttributes',
'uniqueIndices',
'uniqueIndex',
'breakCount',
'atEachStepBlock',
'startMicroseconds',
'lastYieldMicroseconds',
'externalSemaphoreSignalRequests',
'externalSemaphoreSignalResponses',
'extSemTabSize',
'debugStackDepthDictionary',
'performFilters',
'eventQueue',
'expectedSends',
'expecting',
'bootstrapping',
'primitiveFailCount',
'primitiveFlags',
'initialAddress'
],
#classVars : [
'ByteCountsPerMicrosecond',
'ExpectedSends'
],
#category : #'VMMaker-JITSimulation'
}
{ #category : #'debug support' }
CogVMSimulator class >> expectedSends [
^ExpectedSends
]
{ #category : #initialization }
CogVMSimulator class >> initializeWithOptions: optionsDictionary [
super initializeWithOptions: optionsDictionary.
ByteCountsPerMicrosecond := InitializationOptions
at: #ByteCountsPerMicrosecond
ifAbsent: [100]
]
{ #category : #'instance creation' }
CogVMSimulator class >> new [
^self onObjectMemory: nil cogit: nil options: #()
]
{ #category : #'instance creation' }
CogVMSimulator class >> newWithOptions: optionsDictionaryOrArray [
^self onObjectMemory: nil cogit: nil options: optionsDictionaryOrArray
]
{ #category : #'instance creation' }
CogVMSimulator class >> onObjectMemory: anObjectMemory [
^self onObjectMemory: anObjectMemory cogit: nil options: #()
]
{ #category : #'instance creation' }
CogVMSimulator class >> onObjectMemory: anObjectMemory cogit: aCogit [
^self onObjectMemory: anObjectMemory cogit: aCogit options: #()
]
{ #category : #'instance creation' }
CogVMSimulator class >> onObjectMemory: anObjectMemory cogit: aCogit options: optionsDictionaryOrArray [
| simulatorClass |
^self == CogVMSimulator
ifTrue:
[simulatorClass := SmalltalkImage current endianness == #big
ifTrue: [self notYetImplemented]
ifFalse: [CogVMSimulatorLSB].
simulatorClass
initializeWithOptions: optionsDictionaryOrArray
objectMemoryClass: (anObjectMemory ifNotNil: [anObjectMemory class]).
simulatorClass
onObjectMemory: (anObjectMemory ifNil:
[self objectMemoryClass simulatorClass new])
cogit: aCogit
options: optionsDictionaryOrArray]
ifFalse:
[| sim |
sim := self basicNew.
sim objectMemory: anObjectMemory.
sim cogit: aCogit.
sim initialize.
sim]
]
{ #category : #'debug support' }
CogVMSimulator >> allObjectsSelect: objBlock [
"self allObjectsSelect: [:oop | (self baseHeader: oop) = 1234]"
| selected |
selected := OrderedCollection new.
objectMemory allObjectsDo:
[:oop| (objBlock value: oop) ifTrue: [selected addLast: oop]].
^ selected
]
{ #category : #accessing }
CogVMSimulator >> atEachStepBlock [
^atEachStepBlock
]
{ #category : #accessing }
CogVMSimulator >> atEachStepBlock: aBlock [
atEachStepBlock := aBlock
]
{ #category : #'jump bytecodes' }
CogVMSimulator >> attemptToSwitchToMachineCode: bcpc [
"method = 16r96A294 ifTrue: [self halt]."
^super attemptToSwitchToMachineCode: bcpc
]
{ #category : #'return bytecodes' }
CogVMSimulator >> baseFrameReturn [
"| contextToReturnTo |
contextToReturnTo := self frameCallerContext: localFP.
(self stringOf: (self penultimateLiteralOf: (self fetchPointer: MethodIndex ofObject: contextToReturnTo))) = #indexOf:startingAt:ifAbsent: ifTrue:
[self halt]."
^super baseFrameReturn
]
{ #category : #initialization }
CogVMSimulator >> basicInitialize [
"Initialize the CogVMSimulator when running the interpreter inside Smalltalk. The
primary responsibility of this method is to allocate Smalltalk Arrays for variables
that will be declared as statically-allocated global arrays in the translated code."
super initialize.
transcript := Transcript.
bootstrapping := false.
objectMemory ifNil:
[objectMemory := self class objectMemoryClass simulatorClass new].
cogit ifNil:
[cogit := self class cogitClass new setInterpreter: self].
objectMemory coInterpreter: self cogit: cogit.
(cogit numRegArgs > 0
and: [VMClass initializationOptions at: #CheckStackDepth ifAbsent: [true]]) ifTrue:
[debugStackDepthDictionary := Dictionary new].
self assert: ConstMinusOne = (objectMemory integerObjectOf: -1).
cogMethodZone := cogit methodZone. "Because Slang can't remove intermediate implicit receivers (cogit methodZone foo doesn't reduce to foo())"
enableCog := true.
methodCache := Array new: MethodCacheSize.
atCache := nil.
self flushMethodCache.
cogCompiledCodeCompactionCalledFor := false.
gcSemaphoreIndex := 0.
externalSemaphoreSignalRequests := externalSemaphoreSignalResponses := #().
externalPrimitiveTable := CArrayAccessor on: (Array
new: MaxExternalPrimitiveTableSize
withAll: 0).
externalPrimitiveTableFirstFreeIndex := 0.
primitiveTable := self class primitiveTable copy.
desiredNumStackPages := desiredEdenBytes := desiredCogCodeSize := 0.
"This is initialized on loading the image, but convenient for testing stack page values..."
numStackPages := self defaultNumStackPages.
startMicroseconds := lastYieldMicroseconds := self ioUTCStartMicroseconds.
maxLiteralCountForCompile := MaxLiteralCountForCompile.
minBackwardJumpCountForCompile := MinBackwardJumpCountForCompile.
flagInterpretedMethods := false.
"initialize InterpreterSimulator variables used for debugging"
byteCount := lastPollCount := sendCount := lookupCount := 0.
quitBlock := [^self close].
traceOn := true.
printSends := printFrameAtEachStep := printBytecodeAtEachStep := false.
myBitBlt := BitBltSimulator new setInterpreter: self.
displayForm := fakeForm := 'Display has not yet been installed' asDisplayText form.
eventQueue := SharedQueue new.
suppressHeartbeatFlag := deferSmash := deferredSmash := false.
systemAttributes := Dictionary new.
primTraceLog := CArrayAccessor on: (Array new: 256 withAll: 0).
primTraceLogIndex := 0.
traceLog := CArrayAccessor on: (Array new: TraceBufferSize withAll: 0).
traceLogIndex := 0.
traceSources := TraceSources.
statCodeCompactionCount := 0.
statCodeCompactionUsecs := 0.
extSemTabSize := 256.
"This will be overriden when calling initializePluginEntries"
mappedPluginEntries := OrderedCollection new.
imageReader := SpurImageReader newWithMemory: objectMemory andInterpreter: self.
imageWriter := SpurImageWriter newWithMemory: objectMemory andInterpreter: self
]
{ #category : #hooks }
CogVMSimulator >> beforeCodeZoneInitialization [
super beforeCodeZoneInitialization.
self moveMethodCacheToMemoryAt: (memoryManager allocate: MethodCacheEntrySize * MethodCacheSize * (self sizeof: #sqInt)).
self movePrimTraceLogToMemoryAt: (memoryManager allocate: PrimTraceLogSize * (self sizeof: #sqInt)).
]
{ #category : #accessing }
CogVMSimulator >> bootstrapping: aBoolean [
bootstrapping := aBoolean.
objectMemory ifNotNil:
[objectMemory bootstrapping: aBoolean]
]
{ #category : #accessing }
CogVMSimulator >> breakCount [
^breakCount
]
{ #category : #'memory access' }
CogVMSimulator >> byteAt: byteAddress [
"This is really only for the C library simulations memcpy:_:_: et al in VMClass.
Use objectMemory byteAt: directly where possible."
^objectMemory byteAt: byteAddress
]
{ #category : #'memory access' }
CogVMSimulator >> byteAt: byteAddress put: byte [
^objectMemory byteAt: byteAddress put: byte
]
{ #category : #'debug support' }
CogVMSimulator >> byteCount [
"So you can call this from temp debug statements in, eg, Interpreter, such as
self byteCount = 12661 ifTrue: [self halt].
"
^ byteCount
]
{ #category : #UI }
CogVMSimulator >> byteCountText [
^(String streamContents: [:s| s nextPutAll: byteCount asStringWithCommas; nextPut: $/; nextPutAll: sendCount asStringWithCommas]) asText
]
{ #category : #'translation support' }
CogVMSimulator >> cCoerceSimple: value to: cTypeString [
"Type coercion for translation and simulation.
For simulation answer a suitable surrogate for the struct types"
^cTypeString
caseOf:
{ [#'CogMethod *'] -> [cogit cogMethodSurrogateAt: value asUnsignedInteger].
[#'CogBlockMethod *'] -> [cogit cogBlockMethodSurrogateAt: value asUnsignedInteger] }
otherwise: [value]
]
{ #category : #'plugin support' }
CogVMSimulator >> callExternalPrimitive: mapIndex [
| entry |
entry := self pluginEntryFor: mapIndex.
"Spur needs the primitiveFunctionPointer to be set correctly
for accurate following of forwarders on primitive failure."
objectMemory hasSpurMemoryManagerAPI ifTrue:
[primitiveFunctionPointer := entry at: 2].
^(entry at: 1) perform: (entry at: 2)
]
{ #category : #enilopmarts }
CogVMSimulator >> ceActivateFailingPrimitiveMethod: aPrimitiveMethod [
"self halt."
^super ceActivateFailingPrimitiveMethod: aPrimitiveMethod
]
{ #category : #trampolines }
CogVMSimulator >> ceBaseFrameReturn: returnValue [
"self printCallStackOf: (stackPages longAt: stackPage baseAddress) currentFP: stackPage baseFP.
Transcript print: byteCount; tab; print: thisContext; cr.
(self confirm: 'continue?') ifFalse: [self returnValue hex]."
"returnValue = 16r01934F78 ifTrue: [self halt]."
"| contextToReturnTo |
contextToReturnTo := stackPages longAt: stackPage baseAddress.
(self stringOf: (self penultimateLiteralOf: (self fetchPointer: MethodIndex ofObject: contextToReturnTo))) = #indexOf:startingAt:ifAbsent: ifTrue:
[self halt]."
^super ceBaseFrameReturn: returnValue
]
{ #category : #trampolines }
CogVMSimulator >> ceContext: aOnceMarriedContext instVar: slotIndex [
cogit assertCStackWellAligned.
^super ceContext: aOnceMarriedContext instVar: slotIndex
]
{ #category : #trampolines }
CogVMSimulator >> ceContext: aOnceMarriedContext instVar: slotIndex value: anOop [
"aOnceMarriedContext = 26431360 ifTrue:
[transcript cr; cr.
self printContext: aOnceMarriedContext.
transcript cr.
(self isContext: anOop)
ifTrue: [self printContext: anOop]
ifFalse: [self printOop: anOop].
self halt]."
cogit assertCStackWellAligned.
^super ceContext: aOnceMarriedContext instVar: slotIndex value: anOop
]
{ #category : #'cog jit support' }
CogVMSimulator >> ceCounterTripped: condition [
| counterTrippedSelector |
self transcript cr; nextPutAll: 'counter tripped in '.
self shortPrintFrame: framePointer.
counterTrippedSelector := objectMemory maybeSplObj: SelectorCounterTripped.
(counterTrippedSelector isNil
or: [counterTrippedSelector = objectMemory nilObject]) ifFalse:
[self halt: 'counter tripped'].
^super ceCounterTripped: condition
]
{ #category : #trampolines }
CogVMSimulator >> ceMNUFromPICMNUMethod: aMethodObj receiver: rcvr [
| cPIC |
cPIC := self cCoerceSimple: self stackTop - cogit mnuOffset to: #'CogMethod *'.
self assert: (cPIC cmType = CMPolymorphicIC or: [cPIC cmType = CMMegamorphicIC]).
self mnuBreakpoint: cPIC selector receiver: nil.
^super ceMNUFromPICMNUMethod: aMethodObj receiver: rcvr
]
{ #category : #'debug support' }
CogVMSimulator >> ceNonLocalReturn: returnValue [
"self halt."
^super ceNonLocalReturn: returnValue
]
{ #category : #trampolines }
CogVMSimulator >> ceReapAndResetErrorCodeFor: cogMethod [
"Override to map the address into a CogMethodSurrogate"
| surrogate |
surrogate := cogMethod isInteger
ifTrue: [cogit cogMethodSurrogateAt: cogMethod]
ifFalse: [cogMethod].
^super ceReapAndResetErrorCodeFor: surrogate
]
{ #category : #trampolines }
CogVMSimulator >> ceSend: selector super: superNormalBar to: rcvr numArgs: numArgs [
"self stringOf: selector"
"self printOop: rcvr"
"(superNormalBar ~= 0 and: [(self stringOf: selector) = #bitShift:]) ifTrue:
[self halt]."
self logSend: selector.
cogit assertCStackWellAligned.
self maybeCheckStackDepth: numArgs + 1 sp: stackPointer pc: (stackPages longAt: stackPointer).
^super ceSend: selector super: superNormalBar to: rcvr numArgs: numArgs
]
{ #category : #trampolines }
CogVMSimulator >> ceSendAbort: selector to: rcvr numArgs: numArgs [
"self stringOf: selector"
"self printOop: rcvr"
self logSend: selector.
cogit assertCStackWellAligned.
self maybeCheckStackDepth: numArgs + 1
sp: stackPointer
pc: (stackPages longAt: stackPointer).
^super ceSendAbort: selector to: rcvr numArgs: numArgs
]
{ #category : #trampolines }
CogVMSimulator >> ceSendFromInLineCacheMiss: oPIC [
"Override to map the address into a CogMethodSurrogate"
| surrogate |
surrogate := oPIC isInteger
ifTrue: [cogit cogMethodSurrogateAt: oPIC]
ifFalse: [oPIC].
self logSend: surrogate selector.
(surrogate cmNumArgs = 0
and: [(self stackValue: 1) = 16r8169D0
and: [self stackTop = 16r53EA7]]) ifTrue:
[self halt].
^super ceSendFromInLineCacheMiss: surrogate
]
{ #category : #trampolines }
CogVMSimulator >> ceSendMustBeBoolean: anObject [
self halt.
^super ceSendMustBeBoolean: anObject
]
{ #category : #trampolines }
CogVMSimulator >> ceStackOverflow: contextSwitchIfNotNil [
"Override to bump up the byteCount from which the microsecond clock is derived."
byteCount := byteCount + 1000.
^super ceStackOverflow: contextSwitchIfNotNil
]
{ #category : #'debug support' }
CogVMSimulator >> ceTraceBlockActivation [
cogit printOnTrace ifTrue:
[transcript print: byteCount; nextPut: $/; print: (sendCount := sendCount + 1); space].
cogit assertCStackWellAligned.
super ceTraceBlockActivation.
^#continue
]
{ #category : #'debug support' }
CogVMSimulator >> ceTraceLinkedSend: theReceiver [
(sendCount := sendCount + 1) \\ 500 = 0 ifTrue:
[self changed: #byteCountText].
cogit printOnTrace ifTrue:
[transcript print: byteCount; nextPut: $/; print: sendCount; space].
cogit assertCStackWellAligned.
super ceTraceLinkedSend: theReceiver.
^#continue
]
{ #category : #'object memory support' }
CogVMSimulator >> checkStackIntegrity [
"Override to deal with incomplete initialization."
stackPages ifNil: [^true].
stackPages pages ifNil: [^true].
^super checkStackIntegrity
]
{ #category : #'debug support' }
CogVMSimulator >> classAndSelectorOfMethod: meth forReceiver: rcvr [
| mClass dict length methodArray |
mClass := objectMemory fetchClassOf: rcvr.
[dict := objectMemory fetchPointer: MethodDictionaryIndex ofObject: mClass.
length := objectMemory numSlotsOf: dict.
methodArray := objectMemory fetchPointer: MethodArrayIndex ofObject: dict.
0 to: length-SelectorStart-1 do:
[:index |
meth = (objectMemory fetchPointer: index ofObject: methodArray)
ifTrue: [^ Array
with: mClass
with: (objectMemory fetchPointer: index + SelectorStart ofObject: dict)]].
mClass := objectMemory fetchPointer: SuperclassIndex ofObject: mClass.
mClass = objectMemory nilObject]
whileFalse: [].
^ Array
with: (objectMemory fetchClassOf: rcvr)
with: (objectMemory splObj: SelectorDoesNotUnderstand)
]
{ #category : #'plugin support' }
CogVMSimulator >> classNameOf: aClass Is: className [
"Check if aClass' name is className"
| name |
(objectMemory lengthOf: aClass) <= classNameIndex ifTrue:
[^false]. "Not a class but maybe behavior"
name := objectMemory fetchPointer: classNameIndex ofObject: aClass.
(objectMemory isBytes: name) ifFalse:
[^false].
^ className = (self stringOf: name)
]
{ #category : #'I/O primitives' }
CogVMSimulator >> clipboardRead: sz Into: actualAddress At: zeroBaseIndex [
| str |
str := Clipboard clipboardText.
1 to: sz do:
[:i | objectMemory byteAt: actualAddress + zeroBaseIndex + i - 1 put: (str at: i) asciiValue]
]
{ #category : #'I/O primitives' }
CogVMSimulator >> clipboardSize [
^ Clipboard clipboardText size
]
{ #category : #'debug support' }
CogVMSimulator >> cloneSimulation [
| savedDisplayView savedDisplayForm savedQuitBlock savedTranscript |
savedDisplayView := displayView. displayView := nil.
savedDisplayForm := displayForm. displayForm = nil.
savedQuitBlock := quitBlock. quitBlock := nil.
savedTranscript := transcript. transcript := nil.
^[| theClone |
Smalltalk garbageCollect.
theClone := self veryDeepCopy.
theClone parent: self; transcript: Transcript.
theClone objectMemory parent: objectMemory.
theClone]
ensure:
[displayView := savedDisplayView.
displayForm = savedDisplayForm.
quitBlock := savedQuitBlock.
transcript := savedTranscript]
]
{ #category : #initialization }
CogVMSimulator >> close [ "close any files that ST may have opened, etc"
pluginList do: [:assoc| | plugin | plugin := assoc value. plugin ~~ self ifTrue: [plugin close]]
]
{ #category : #'primitive support' }
CogVMSimulator >> codeGeneratorToComputeAccessorDepth [
^ codeGeneratorToComputeAccessorDepth ifNil: [
(VMMaker new
vmmakerConfiguration: VMMakerConfiguration;
buildCodeGeneratorForInterpreter: CoInterpreterPrimitives
includeAPIMethods: false
initializeClasses: false)
logger: self transcript;
yourself]
]
{ #category : #'as yet unclassified' }
CogVMSimulator >> codeGeneratorToComputeAccessorDepth: aCCodeGenerator [
codeGeneratorToComputeAccessorDepth := aCCodeGenerator
]
{ #category : #'simulation only' }
CogVMSimulator >> cogit [
^cogit
]
{ #category : #'debug support' }
CogVMSimulator >> collectSends [
expectedSends := WriteStream on: (Array new: 65536).
expecting := false
]
{ #category : #'cog jit support' }
CogVMSimulator >> commenceCogCompiledCodeCompaction [
^super commenceCogCompiledCodeCompaction
]
{ #category : #'frame access' }
CogVMSimulator >> convertToMachineCodeFrame: cogHomeMethod bcpc: bcpc [
"bytecodeSetSelector ~= 0 ifTrue: [self halt]".
^super convertToMachineCodeFrame: cogHomeMethod bcpc: bcpc
]
{ #category : #'I/O primitives support' }
CogVMSimulator >> copyBits [
^ myBitBlt copyBits
]
{ #category : #'debug printing' }
CogVMSimulator >> cr [
traceOn ifTrue: [ transcript cr; flush ].
]
{ #category : #'debugging traps' }
CogVMSimulator >> createActualMessageTo: class [
class = objectMemory nilObject ifTrue: [self halt].
^super createActualMessageTo: class
]
{ #category : #'debug support' }
CogVMSimulator >> debugStackPointersFor: aMethod [
^CArrayAccessor on:
(StackDepthFinder on: (VMCompiledMethodProxy new
for: aMethod
coInterpreter: self
objectMemory: objectMemory))
stackPointers
]
{ #category : #initialization }
CogVMSimulator >> desiredCogCodeSize: anInteger [
desiredCogCodeSize := anInteger
]
{ #category : #UI }
CogVMSimulator >> desiredDisplayExtent [
^(savedWindowSize
ifNil: [640@480]
ifNotNil: [savedWindowSize >> 16 @ (savedWindowSize bitAnd: 16rFFFF)])
min: Display extent * 2 // 3
]
{ #category : #initialization }
CogVMSimulator >> desiredEdenBytes: anInteger [
desiredEdenBytes := anInteger
]
{ #category : #initialization }
CogVMSimulator >> desiredNumStackPages: anInteger [
desiredNumStackPages := anInteger
]
{ #category : #'plugin primitive support' }
CogVMSimulator >> dispatchMappedPluginEntry: n [
^(mappedPluginEntries at: n) first
perform: (mappedPluginEntries at: n) second
]
{ #category : #'interpreter shell' }
CogVMSimulator >> dispatchOn: anInteger in: selectorArray [
"Simulate a case statement via selector table lookup.
The given integer must be between 0 and selectorArray size-1, inclusive.
For speed, no range test is done, since it is done by the at: operation.
Note that, unlike many other arrays used in the Interpreter, this method expect NO CArrayAccessor wrapping - it would duplicate the +1. Maybe this would be better updated to make it all uniform"
cogit breakPC ifNil:
[cogit breakBlock ifNotNil:
[:bb| (bb value: cogit) ifTrue: [self halt: 'breakpoint reached']]].
self perform: (selectorArray at: (anInteger + 1)).
]
{ #category : #'I/O primitives support' }
CogVMSimulator >> displayLocation [
^ Display extent - displayForm extent - (10@10)
]
{ #category : #accessing }
CogVMSimulator >> displayView [
"The VM SImulator draws directly on an imageMorph named displayView
displayView is housed on a Form named displayForm
Since this is housed directly on the Morph, I have this tight compling from here->model->morph.
"
self flag: 'tty'.
^displayView
]
{ #category : #'process primitive support' }
CogVMSimulator >> doSignalExternalSemaphores: minTableSize [
"This is a non-thread-safe simulation. See platforms/Cross/vm/sqExternalSemaphores.c
for the real code. For the benefit of the SocketPluginSimulator, do a yield every 100
virtual microseconds."
| now switched |
now := self ioUTCMicroseconds.
now - lastYieldMicroseconds >= 100 ifTrue:
[lastYieldMicroseconds := now.
Processor yield].
switched := false.
1 to: (minTableSize min: externalSemaphoreSignalRequests size) do:
[:i| | responses |
responses := externalSemaphoreSignalResponses at: i.
[responses < (externalSemaphoreSignalRequests at: i)] whileTrue:
[(self doSignalSemaphoreWithIndex: i) ifTrue:
[switched := true].
externalSemaphoreSignalResponses at: i put: (responses := responses + 1)]].
^switched
]
{ #category : #'error handling' }
CogVMSimulator >> doesNotUnderstand: aMessage [
"If this is a doit and the objectMemory understands, pass it on."
(thisContext findContextSuchThat: [:ctxt| ctxt selector == #evaluate:in:to:notifying:ifFail:logged:]) ifNotNil:
[(objectMemory class whichClassIncludesSelector: aMessage selector) ifNotNil:
[:implementingClass|
(implementingClass inheritsFrom: Object) ifTrue: "i.e. VMClass and below"
[thisContext sender selector ~~ #DoIt ifTrue:
[Transcript nextPutAll: 'warning: redirecting ', aMessage selector, ' in ', thisContext sender printString, ' to objectMemory'; cr; flush].
aMessage lookupClass: nil.
^aMessage sentTo: objectMemory]].
(cogit class whichClassIncludesSelector: aMessage selector) ifNotNil:
[:implementingClass|
(implementingClass inheritsFrom: Object) ifTrue: "i.e. VMClass and below"
[thisContext sender selector ~~ #DoIt ifTrue:
[Transcript nextPutAll: 'warning: redirecting ', aMessage selector, ' in ', thisContext sender printString, ' to cogit'; cr; flush].
aMessage lookupClass: nil.
^aMessage sentTo: cogit]]].
^super doesNotUnderstand: aMessage
]
{ #category : #'I/O primitives support' }
CogVMSimulator >> drawLoopX: xDelta Y: yDelta [
^ myBitBlt drawLoopX: xDelta Y: yDelta
]
{ #category : #'debug support' }
CogVMSimulator >> dumpMethodHeader: hdr [
^ String streamContents:
[:strm |
strm nextPutAll: '<nArgs=', ((hdr >> 25) bitAnd: 16r1F) printString , '>'.
strm nextPutAll: '<nTemps=', ((hdr >> 19) bitAnd: 16r3F) printString , '>'.
strm nextPutAll: '<lgCtxt=', ((hdr >> 18) bitAnd: 16r1) printString , '>'.
strm nextPutAll: '<nLits=', ((hdr >> 10) bitAnd: 16rFF) printString , '>'.
strm nextPutAll: '<prim=', ((hdr >> 1) bitAnd: 16r1FF) printString , '>'.
]
]
{ #category : #'debug printing' }
CogVMSimulator >> elementsPerPrintOopLine [
^4
]
{ #category : #'debugging traps' }
CogVMSimulator >> enableCog: aBoolean [
enableCog := aBoolean
]
{ #category : #'frame access' }
CogVMSimulator >> ensureContextIsExecutionSafeAfterAssignToStackPointer: aContext [
"16r1934F80 = aContext ifTrue:
[self halt]."
^super ensureContextIsExecutionSafeAfterAssignToStackPointer: aContext
]
{ #category : #'frame access' }
CogVMSimulator >> ensureMethodIsCogged: methodObj maybeClosure: maybeClosure [
"Uncomment this to compact frequently and hence test if clients are ready for the shock."
"[self commenceCogCompiledCodeCompaction]
on: Halt
do: [:ex| ex resume: nil]."
^super ensureMethodIsCogged: methodObj maybeClosure: maybeClosure
]
{ #category : #'debug support' }
CogVMSimulator >> expectSends: anArray [
expectedSends := ReadStream on: anArray.
expecting := true
]
{ #category : #'miscellaneous bytecodes' }
CogVMSimulator >> extABytecode [
"224 11100000 aaaaaaaa Extend A (Ext A = Ext A prev * 256 + Ext A)"
(extA = 0 and: [extB = 0]) ifTrue:
[lastExtPC := instructionPointer].
^super extABytecode
]
{ #category : #'miscellaneous bytecodes' }
CogVMSimulator >> extBBytecode [
"225 11100001 sbbbbbbb Extend B (Ext B = Ext B prev * 256 + Ext B)"
(extA = 0 and: [extB = 0]) ifTrue:
[lastExtPC := instructionPointer].
^super extBBytecode
]
{ #category : #'jump bytecodes' }
CogVMSimulator >> extUnconditionalJump [
"242 11110010 i i i i i i i i Jump i i i i i i i i (+ Extend B * 256, where bbbbbbbb = sddddddd, e.g. -32768 = i=0, a=0, s=1)"
"| byte offset |
byte := objectMemory byteAt: localIP + 1.
offset := byte + (extB << 8).
(offset < 0 and: [(self iframeBackwardBranchByte: localFP) - 2 = 1]) ifTrue: [self halt]."
^super extUnconditionalJump
]
{ #category : #'debugging traps' }
CogVMSimulator >> externalCannotReturn: resultOop from: aContext [
self halt.
^super externalCannotReturn: resultOop from: aContext
]
{ #category : #'debugging traps' }
CogVMSimulator >> externalDivorceFrame: theFP andContext: ctxt [
"((#(16r100570 16r101BC8) includes: theFP) or: [#(16r17159A4 16r1715948) includes: ctxt]) ifTrue:
[self halt]."
^super externalDivorceFrame: theFP andContext: ctxt
]
{ #category : #'debugging traps' }
CogVMSimulator >> externalInstVar: offset ofContext: aContext [
"offset = InstructionPointerIndex ifTrue:
[transcript nextPutAll: '==================='; cr.
self printContext: 16r1715630.
self printCallStackOf: aContext currentFP: framePointer.
transcript nextPutAll: '==================='; cr.
self halt]."
| result |
"self shortPrintFrameAndCallers: framePointer.
transcript print: byteCount; tab; print: thisContext; cr.
self print: offset; cr.
self printContext: aContext.
(self confirm: 'continue?') ifFalse: [self halt]."
result := super externalInstVar: offset ofContext: aContext.
"(offset = InstructionPointerIndex
and: [(self stringOf: (self penultimateLiteralOf: (self fetchPointer: MethodIndex ofObject: aContext))) = #indexOf:startingAt:ifAbsent:]) ifTrue:
[transcript space; nextPutAll: '^pc '; nextPutAll: result hex.
(objectMemory isIntegerObject: result) ifTrue:
[transcript space; print: (objectMemory integerValueOf: result)].
transcript tab.
self shortPrintContext: aContext]."
"offset = StackPointerIndex ifTrue:
[transcript nextPutAll: '^stackp ', (self integerValueOf: result) printString; tab.
self shortPrintContext: aContext.
(#(24205456 24205732) includes: aContext) ifTrue:
[(self checkIsStillMarriedContext: aContext currentFP: framePointer)
ifTrue: [self printFrame: (self frameOfMarriedContext: aContext) WithSP: (self frameOfMarriedContext: aContext) - 48]
ifFalse: [self printContext: aContext]]]."
^result
]
{ #category : #'frame access' }
CogVMSimulator >> externalInstVar: index ofContext: aContext put: anOop [
"self shortPrintFrameAndCallers: framePointer.
Transcript print: byteCount; tab; print: thisContext; cr.
self print: index; cr.
self printContext: aContext.
self shortPrintOop: anOop.
(self confirm: 'continue?') ifFalse: [self halt]."
"(self stringOf: (self penultimateLiteralOf: (self fetchPointer: MethodIndex ofObject: aContext))) = #indexOf:startingAt:ifAbsent: ifTrue:
[self halt]."
^super externalInstVar: index ofContext: aContext put: anOop
]
{ #category : #'frame access' }
CogVMSimulator >> externalSetStackPageAndPointersForSuspendedContextOfProcess: aProcess [
"Override to check stack depth (hence in the simulator only)."
super externalSetStackPageAndPointersForSuspendedContextOfProcess: aProcess.
(self isMachineCodeFrame: framePointer) ifTrue:
[self maybeCheckStackDepth: 0
sp: stackPointer
pc: instructionPointer]
]
{ #category : #'interpreter shell' }
CogVMSimulator >> fetchByte [
^objectMemory byteAt: (instructionPointer := instructionPointer + 1)
]
{ #category : #'interpreter access' }
CogVMSimulator >> fetchPointer: fieldIndex ofObject: oop [
"index by word size, and return a pointer as long as the word size"
self assert: (objectMemory cheapIsInMemory: oop).
^objectMemory fetchPointer: fieldIndex ofObject: oop
]
{ #category : #'control primitives' }
CogVMSimulator >> filterPerformOf: selector to: receiver [
"This is to allow simulator to filter start-up items to avoid as-yet unsimulatable plugins."
performFilters ifNil: [^false].
(performFilters at: (self shortPrint: receiver) ifAbsent: []) ifNotNil:
[:messages|
^messages includes: (self stringOf: selector)].
^false
]
{ #category : #testing }
CogVMSimulator >> findNewMethodInClassTag: classTag [
"
| cName |
traceOn ifTrue:
[cName := (self sizeBitsOf: class) = 16r20
ifTrue: ['class ' , (self nameOfClass: (self fetchPointer: 6 ofObject: class))]
ifFalse: [(self nameOfClass: class)].
self cr; print: cName , '>>' , (self stringOf: messageSelector)].
"
messageSelector = (objectMemory splObj: SelectorDoesNotUnderstand) ifTrue: [self halt].
self logSend: messageSelector.
"
(sendCount > 1000 and: [sendCount\\10 = 0]) ifTrue:
[Transcript print: sendCount; space.
self validate].
"
"
(sendCount > 100150) ifTrue:
[self qvalidate.
messageQueue == nil ifTrue: [messageQueue := OrderedCollection new].
messageQueue addLast: (self stringOf: messageSelector)].
"
^super findNewMethodInClassTag: classTag
]
{ #category : #'memory access' }
CogVMSimulator >> firstIndexableField: oop [
"This is in ObjectMemory and overridden in the obj mem simulators"
self shouldNotImplement
]
{ #category : #'debug printing' }
CogVMSimulator >> flush [
<cmacro: '() fflush(stdout)'>
traceOn ifTrue: [transcript flush]
]
{ #category : #'plugin support' }
CogVMSimulator >> flushExternalPrimitives [
self initializePluginEntries.
super flushExternalPrimitives
]
{ #category : #'control primitives' }
CogVMSimulator >> forShortPrintString: shortPrintString filterPerformMessages: aCollection [
performFilters ifNil:
[performFilters := Dictionary new].
performFilters at: shortPrintString put: aCollection
]
{ #category : #'frame access' }
CogVMSimulator >> frameCallerContext: theFP [
"In the StackInterpreter the saved ip field of a base frame holds the base
frame's caller context. But in the Cog VM the first word on the stack holds
the base frame's caller context, which is immediately above the stacked
receiver. The asserts using frameStackedReceiverOffset: are simulation
only since they depend on being able to access numArgs and frameContext
from the frame's method and in a base return the frame state, being below
the stack pointer, may have already been smashed by an interrupt."
| thePage |
self assert: (self isBaseFrame: theFP).
thePage := stackPages stackPageFor: theFP.
self assert: theFP + (self frameStackedReceiverOffset: theFP) + (2 * objectMemory wordSize) = thePage baseAddress.
self assert: (stackPages longAt: thePage baseAddress - objectMemory wordSize) = (self frameContext: theFP).
^super frameCallerContext: theFP
]
{ #category : #'frame access' }
CogVMSimulator >> frameOfMarriedContext: aContext [
| senderOop |
senderOop := objectMemory fetchPointer: SenderIndex ofObject: aContext.
self assert: (objectMemory isIntegerObject: senderOop).
^self withoutSmallIntegerTags: senderOop
]
{ #category : #'debug support' }
CogVMSimulator >> framePointer [
^framePointer
]
{ #category : #'plugin primitives' }
CogVMSimulator >> functionForPrimitiveExternalCall: methodObj [
"Override to jump through the plugin simulation hoops."
| symbolOrIndex |
symbolOrIndex := super functionForPrimitiveExternalCall: methodObj.
^symbolOrIndex isSymbol
ifTrue: [symbolOrIndex]
ifFalse: [(self pluginEntryFor: symbolOrIndex) at: 3]
]
{ #category : #'interpreter shell' }
CogVMSimulator >> functionPointerFor: primIndex inClass: lookupClass [
"Override Interpreter to handle the external primitives caching. See also
internalExecuteNewMethod."
^(primIndex between: 1 and: MaxPrimitiveIndex)
ifTrue: [primitiveTable at: primIndex + 1]
ifFalse: [0]
]
{ #category : #'cog jit support' }