-
Notifications
You must be signed in to change notification settings - Fork 30
/
VM.java
449 lines (365 loc) · 13.4 KB
/
VM.java
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
package som;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary;
import com.oracle.truffle.api.debug.Debugger;
import com.oracle.truffle.api.instrumentation.Tag;
import com.oracle.truffle.api.nodes.GraphPrintVisitor;
import com.oracle.truffle.api.source.Source;
import com.oracle.truffle.api.source.SourceSection;
import com.oracle.truffle.api.vm.PolyglotEngine;
import com.oracle.truffle.api.vm.PolyglotEngine.Builder;
import com.oracle.truffle.api.vm.PolyglotEngine.Value;
import com.oracle.truffle.api.vm.PolyglotRuntime.Instrument;
import com.oracle.truffle.tools.profiler.CPUSampler;
import bd.inlining.InlinableNodes;
import coveralls.truffle.Coverage;
import som.compiler.MixinDefinition;
import som.compiler.SourcecodeCompiler;
import som.interpreter.Method;
import som.interpreter.SomLanguage;
import som.interpreter.TruffleCompiler;
import som.interpreter.actors.Actor;
import som.interpreter.actors.Actor.ActorProcessingThreadFactory;
import som.interpreter.actors.SFarReference;
import som.interpreter.actors.SPromise;
import som.interpreter.actors.SPromise.SResolver;
import som.primitives.processes.ChannelPrimitives;
import som.primitives.processes.ChannelPrimitives.ProcessThreadFactory;
import som.primitives.threading.TaskThreads.ForkJoinThreadFactory;
import som.primitives.threading.ThreadingModule;
import som.vm.ObjectSystem;
import som.vm.Primitives;
import som.vm.VmOptions;
import som.vm.VmSettings;
import som.vmobjects.SClass;
import som.vmobjects.SObjectWithClass.SObjectWithoutFields;
import som.vmobjects.SSymbol;
import tools.concurrency.KomposTrace;
import tools.concurrency.TracingActors;
import tools.concurrency.TracingBackend;
import tools.debugger.WebDebugger;
import tools.debugger.session.Breakpoints;
import tools.dym.DynamicMetrics;
import tools.language.StructuralProbe;
import tools.superinstructions.CandidateIdentifier;
//@SuppressWarnings("deprecation")
public final class VM {
@CompilationFinal private PolyglotEngine engine;
@CompilationFinal private StructuralProbe structuralProbe;
@CompilationFinal private WebDebugger webDebugger;
@CompilationFinal private CPUSampler truffleProfiler;
private final ForkJoinPool actorPool;
private final ForkJoinPool forkJoinPool;
private final ForkJoinPool processesPool;
private final ForkJoinPool threadPool;
private final boolean avoidExitForTesting;
@CompilationFinal private ObjectSystem objectSystem;
@CompilationFinal private SomLanguage language;
private int lastExitCode = 0;
private volatile boolean shouldExit = false;
private final VmOptions options;
@CompilationFinal private SObjectWithoutFields vmMirror;
@CompilationFinal private Actor mainActor;
private static final int MAX_THREADS = 0x7fff;
public VM(final VmOptions vmOptions, final boolean avoidExitForTesting) {
this.avoidExitForTesting = avoidExitForTesting;
options = vmOptions;
actorPool = new ForkJoinPool(VmSettings.NUM_THREADS,
new ActorProcessingThreadFactory(), new UncaughtExceptions(this), true);
processesPool = new ForkJoinPool(VmSettings.NUM_THREADS,
new ProcessThreadFactory(), new UncaughtExceptions(this), true);
forkJoinPool = new ForkJoinPool(VmSettings.NUM_THREADS,
new ForkJoinThreadFactory(), new UncaughtExceptions(this), false);
threadPool = new ForkJoinPool(MAX_THREADS,
new ForkJoinThreadFactory(), new UncaughtExceptions(this), false);
}
/**
* Used by language server.
*/
public VM(final VmOptions vmOptions) {
this.avoidExitForTesting = true;
this.options = vmOptions;
actorPool = null;
processesPool = null;
forkJoinPool = null;
threadPool = null;
}
public WebDebugger getWebDebugger() {
return webDebugger;
}
public Breakpoints getBreakpoints() {
return webDebugger.getBreakpoints();
}
private final Map<String, Object> exports = new HashMap<>();
@TruffleBoundary
public boolean registerExport(final String name, final Object value) {
boolean wasExportedAlready = exports.containsKey(name);
exports.put(name, value);
return wasExportedAlready;
}
@TruffleBoundary
public Object getExport(final String name) {
return exports.get(name);
}
public SObjectWithoutFields getVmMirror() {
return vmMirror;
}
/**
* Used by language server.
*/
public SomLanguage getLanguage() {
return language;
}
/**
* Used in {@link som.tests.BasicInterpreterTests} to identify which basic test method to
* invoke.
*/
public String getTestSelector() {
return options.testSelector;
}
public Primitives getPrimitives() {
return objectSystem.getPrimitives();
}
public InlinableNodes<SSymbol> getInlinableNodes() {
return objectSystem.getInlinableNodes();
}
public static void thisMethodNeedsToBeOptimized(final String msg) {
if (VmSettings.FAIL_ON_MISSING_OPTIMIZATIONS) {
CompilerAsserts.neverPartOfCompilation(msg);
}
}
public static void callerNeedsToBeOptimized(final String msg) {
if (VmSettings.FAIL_ON_MISSING_OPTIMIZATIONS) {
CompilerAsserts.neverPartOfCompilation(msg);
}
}
private static final Object dynamicInstrumentationLock = new Object();
private static void outputToIGV(final Method method) {
GraphPrintVisitor graphPrinter = new GraphPrintVisitor();
graphPrinter.beginGraph(method.toString()).visit(method);
graphPrinter.printToNetwork(true);
graphPrinter.close();
}
public ForkJoinPool getActorPool() {
return actorPool;
}
public ForkJoinPool getProcessPool() {
return processesPool;
}
public ForkJoinPool getForkJoinPool() {
return forkJoinPool;
}
public ForkJoinPool getThreadPool() {
return threadPool;
}
/**
* @return true, if there are no scheduled submissions,
* and no active threads in the pool, false otherwise.
* This is only best effort, it does not look at the actor's
* message queues.
*/
public boolean isPoolIdle() {
// TODO: this is not working when a thread blocks, then it seems
// not to be considered running
return actorPool.isQuiescent() && processesPool.isQuiescent()
&& forkJoinPool.isQuiescent() && threadPool.isQuiescent();
}
public void reportSyntaxElement(final Class<? extends Tag> type,
final SourceSection source) {
if (webDebugger != null) {
webDebugger.reportSyntaxElement(type, source);
}
}
public void reportParsedRootNode(final Method rootNode) {
if (webDebugger != null) {
webDebugger.reportRootNodeAfterParsing(rootNode);
}
if (VmSettings.IGV_DUMP_AFTER_PARSING) {
outputToIGV(rootNode);
}
}
public void reportLoadedSource(final Source source) {
if (webDebugger != null) {
webDebugger.reportLoadedSource(source);
}
}
public boolean shouldExit() {
return shouldExit;
}
public int lastExitCode() {
return lastExitCode;
}
public Object[] getArguments() {
return options.args;
}
private void shutdownPools() {
ForkJoinPool[] pools =
new ForkJoinPool[] {actorPool, processesPool, forkJoinPool, threadPool};
for (ForkJoinPool pool : pools) {
pool.shutdown();
try {
pool.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
/**
* Does minimal cleanup and disposes the polyglot engine, before doing a hard
* exit. This method is expected to be called from main thread.
*/
@TruffleBoundary
public void shutdownAndExit(final int errorCode) {
if (truffleProfiler != null) {
truffleProfiler.printHistograms(System.err);
}
shutdownPools();
TracingBackend.waitForTrace();
int code = errorCode;
if (TracingActors.ReplayActor.printMissingMessages() && errorCode == 0) {
code = 1;
}
engine.dispose();
if (VmSettings.MEMORY_TRACING) {
TracingBackend.reportPeakMemoryUsage();
}
System.exit(code);
}
/**
* Request a shutdown and exit from the VM. This does not happen immediately.
* Instead, we instruct the main thread to do it, and merely kill the current
* thread.
*
* @param errorCode to be returned as exit code from the program
*/
public void requestExit(final int errorCode) {
TruffleCompiler.transferToInterpreter("exit");
lastExitCode = errorCode;
shouldExit = true;
objectSystem.releaseMainThread(errorCode);
throw new ThreadDeath();
}
public void errorExit(final String message) {
TruffleCompiler.transferToInterpreter("errorExit");
Output.errorPrintln("Run-time Error: " + message);
requestExit(1);
}
public boolean isAvoidingExit() {
return avoidExitForTesting;
}
public void initalize(final SomLanguage lang) throws IOException {
Actor.initializeActorSystem(language);
assert objectSystem == null;
objectSystem = new ObjectSystem(new SourcecodeCompiler(lang), structuralProbe, this);
objectSystem.loadKernelAndPlatform(options.platformFile, options.kernelFile);
assert vmMirror == null : "VM seems to be initialized already";
assert mainActor == null : "VM seems to be initialized already";
mainActor = Actor.createActor(this);
vmMirror = objectSystem.initialize();
if (VmSettings.ACTOR_TRACING || VmSettings.KOMPOS_TRACING) {
TracingBackend.startTracingBackend();
}
if (VmSettings.KOMPOS_TRACING) {
KomposTrace.recordMainActor(mainActor, objectSystem);
}
language = lang;
}
public Object execute(final String selector) {
return objectSystem.execute(selector);
}
public void execute() {
objectSystem.executeApplication(vmMirror, mainActor);
}
public static void main(final String[] args) {
VmOptions vmOptions = new VmOptions(args);
if (!vmOptions.configUsable()) {
return;
}
VM vm = new VM(vmOptions, false);
Builder builder = vm.createPolyglotBuilder();
vm.startExecution(builder);
}
public Builder createPolyglotBuilder() {
Builder builder = PolyglotEngine.newBuilder();
builder.config(SomLanguage.MIME_TYPE, SomLanguage.VM_OBJECT, this);
return builder;
}
private void startExecution(final Builder builder) {
engine = builder.build();
Map<String, ? extends Instrument> instruments = engine.getRuntime().getInstruments();
if (options.profilingEnabled) {
truffleProfiler = CPUSampler.find(engine);
truffleProfiler.setCollecting(true);
}
Debugger debugger = null;
if (VmSettings.TRUFFLE_DEBUGGER_ENABLED) {
debugger = Debugger.find(engine);
}
if (options.webDebuggerEnabled) {
assert VmSettings.TRUFFLE_DEBUGGER_ENABLED && debugger != null;
Instrument webDebuggerInst = instruments.get(WebDebugger.ID);
webDebuggerInst.setEnabled(true);
webDebugger = webDebuggerInst.lookup(WebDebugger.class);
webDebugger.startServer(debugger, this);
}
if (options.coverageEnabled) {
Instrument coveralls = instruments.get(Coverage.ID);
coveralls.setEnabled(true);
Coverage cov = coveralls.lookup(Coverage.class);
try {
cov.setOutputFile(options.coverageFile);
} catch (IOException e) {
Output.errorPrint("Failed to setup coverage tracking: " + e.getMessage());
}
}
if (options.dynamicMetricsEnabled) {
assert VmSettings.DYNAMIC_METRICS;
Instrument dynM = instruments.get(DynamicMetrics.ID);
dynM.setEnabled(true);
structuralProbe = dynM.lookup(StructuralProbe.class);
assert structuralProbe != null : "Initialization of DynamicMetrics tool incomplete";
}
if (options.siCandidateIdentifierEnabled) {
assert !options.dynamicMetricsEnabled : "Currently, DynamicMetrics and CandidateIdentifer are not compatible";
Instrument siCI = instruments.get(CandidateIdentifier.ID);
siCI.setEnabled(true);
structuralProbe = siCI.lookup(StructuralProbe.class);
assert structuralProbe != null : "Initialization of CandidateIdentifer tool incomplete";
}
Value returnCode = engine.eval(SomLanguage.START);
shutdownAndExit(returnCode.as(Integer.class));
}
public SClass loadExtensionModule(final String filename) {
return objectSystem.loadExtensionModule(filename);
}
public MixinDefinition loadModule(final String filename) throws IOException {
return objectSystem.loadModule(filename);
}
public MixinDefinition loadModule(final Source source) throws IOException {
return objectSystem.loadModule(source);
}
/** This is only meant to be used in unit tests. */
public static void resetClassReferences(final boolean callFromUnitTest) {
assert callFromUnitTest;
SFarReference.setSOMClass(null);
SPromise.setPairClass(null);
SPromise.setSOMClass(null);
SResolver.setSOMClass(null);
ThreadingModule.ThreadingModule = null;
ThreadingModule.ThreadClass = null;
ThreadingModule.ThreadClassId = null;
ThreadingModule.TaskClass = null;
ThreadingModule.TaskClassId = null;
ThreadingModule.MutexClass = null;
ThreadingModule.MutexClassId = null;
ThreadingModule.ConditionClass = null;
ThreadingModule.ConditionClassId = null;
ChannelPrimitives.resetClassReferences();
}
}