/[svn]/linuxsampler/trunk/src/scriptvm/ScriptVM.cpp
ViewVC logotype

Contents of /linuxsampler/trunk/src/scriptvm/ScriptVM.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3034 - (show annotations) (download)
Mon Oct 31 00:05:00 2016 UTC (7 years, 5 months ago) by schoenebeck
File size: 16995 byte(s)
* Fixed a bunch of minor issues (mostly compiler warnings).
* Bumped version (2.0.0.svn31).

1 /*
2 * Copyright (c) 2014 - 2016 Christian Schoenebeck
3 *
4 * http://www.linuxsampler.org
5 *
6 * This file is part of LinuxSampler and released under the same terms.
7 * See README file for details.
8 */
9
10 #include "ScriptVM.h"
11
12 #include <string.h>
13 #include <assert.h>
14 #include "../common/global_private.h"
15 #include "tree.h"
16 #include "CoreVMFunctions.h"
17 #include "CoreVMDynVars.h"
18 #include "editor/NkspScanner.h"
19
20 #define DEBUG_SCRIPTVM_CORE 0
21
22 /**
23 * Maximum amount of VM instructions to be executed per ScriptVM::exec() call
24 * in case loops are involved, before the script got automatically suspended
25 * for a certain amount of time to avoid any RT instability issues.
26 *
27 * The following value takes a max. execution time of 300 microseconds as aimed
28 * target, assuming an execution time of approximately 5 microseconds per
29 * instruction this leads to the very approximate value set below.
30 */
31 #define SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT 70
32
33 /**
34 * Absolute maximum amount of VM instructions to be executed per
35 * ScriptVM::exec() call (even if no loops are involved), before the script got
36 * automatically suspended for a certain amount of time to avoid any RT
37 * instability issues.
38 *
39 * A distinction between "soft" and "hard" limit is done here ATM because a
40 * script author typically expects that his script might be interrupted
41 * automatically if he is using while() loops, however he might not be
42 * prepared that his script might also be interrupted if no loop is involved
43 * (i.e. on very large scripts).
44 *
45 * The following value takes a max. execution time of 1000 microseconds as
46 * aimed target, assuming an execution time of approximately 5 microseconds per
47 * instruction this leads to the very approximate value set below.
48 */
49 #define SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD 210
50
51 /**
52 * In case either SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT or
53 * SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD was exceeded when calling
54 * ScriptVM::exec() : the amount of microseconds the respective script
55 * execution instance should be automatically suspended by the VM.
56 */
57 #define SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS 1000
58
59 int InstrScript_parse(LinuxSampler::ParserContext*);
60
61 namespace LinuxSampler {
62
63 #if DEBUG_SCRIPTVM_CORE
64 static void _printIndents(int n) {
65 for (int i = 0; i < n; ++i) printf(" ");
66 fflush(stdout);
67 }
68 #endif
69
70 static int _requiredMaxStackSizeFor(Statement* statement, int depth = 0) {
71 if (!statement) return 1;
72
73 switch (statement->statementType()) {
74 case STMT_LEAF:
75 #if DEBUG_SCRIPTVM_CORE
76 _printIndents(depth);
77 printf("-> STMT_LEAF\n");
78 #endif
79 return 1;
80
81 case STMT_LIST: {
82 #if DEBUG_SCRIPTVM_CORE
83 _printIndents(depth);
84 printf("-> STMT_LIST\n");
85 #endif
86 Statements* stmts = (Statements*) statement;
87 int max = 0;
88 for (int i = 0; stmts->statement(i); ++i) {
89 int size = _requiredMaxStackSizeFor( stmts->statement(i), depth+1 );
90 if (max < size) max = size;
91 }
92 return max + 1;
93 }
94
95 case STMT_BRANCH: {
96 #if DEBUG_SCRIPTVM_CORE
97 _printIndents(depth);
98 printf("-> STMT_BRANCH\n");
99 #endif
100 BranchStatement* branchStmt = (BranchStatement*) statement;
101 int max = 0;
102 for (int i = 0; branchStmt->branch(i); ++i) {
103 int size = _requiredMaxStackSizeFor( branchStmt->branch(i), depth+1 );
104 if (max < size) max = size;
105 }
106 return max + 1;
107 }
108
109 case STMT_LOOP: {
110 #if DEBUG_SCRIPTVM_CORE
111 _printIndents(depth);
112 printf("-> STMT_LOOP\n");
113 #endif
114 While* whileStmt = (While*) statement;
115 if (whileStmt->statements())
116 return _requiredMaxStackSizeFor( whileStmt->statements() ) + 1;
117 else
118 return 1;
119 }
120 }
121
122 return 1; // actually just to avoid compiler warning
123 }
124
125 static int _requiredMaxStackSizeFor(EventHandlers* handlers) {
126 int max = 1;
127 for (int i = 0; i < handlers->size(); ++i) {
128 int size = _requiredMaxStackSizeFor(handlers->eventHandler(i));
129 if (max < size) max = size;
130 }
131 return max;
132 }
133
134 ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
135 m_fnMessage = new CoreVMFunction_message;
136 m_fnExit = new CoreVMFunction_exit;
137 m_fnWait = new CoreVMFunction_wait(this);
138 m_fnAbs = new CoreVMFunction_abs;
139 m_fnRandom = new CoreVMFunction_random;
140 m_fnNumElements = new CoreVMFunction_num_elements;
141 m_fnInc = new CoreVMFunction_inc;
142 m_fnDec = new CoreVMFunction_dec;
143 m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
144 m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
145 m_fnShLeft = new CoreVMFunction_sh_left;
146 m_fnShRight = new CoreVMFunction_sh_right;
147 m_fnMin = new CoreVMFunction_min;
148 m_fnMax = new CoreVMFunction_max;
149 }
150
151 ScriptVM::~ScriptVM() {
152 delete m_fnMessage;
153 delete m_fnExit;
154 delete m_fnWait;
155 delete m_fnAbs;
156 delete m_fnRandom;
157 delete m_fnNumElements;
158 delete m_fnInc;
159 delete m_fnDec;
160 delete m_fnShLeft;
161 delete m_fnShRight;
162 delete m_fnMin;
163 delete m_fnMax;
164 delete m_varRealTimer;
165 delete m_varPerfTimer;
166 }
167
168 VMParserContext* ScriptVM::loadScript(const String& s) {
169 std::istringstream iss(s);
170 return loadScript(&iss);
171 }
172
173 VMParserContext* ScriptVM::loadScript(std::istream* is) {
174 ParserContext* context = new ParserContext(this);
175 //printf("parserCtx=0x%lx\n", (uint64_t)context);
176
177 context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
178 context->registerBuiltInIntVariables( builtInIntVariables() );
179 context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
180 context->registerBuiltInDynVariables( builtInDynamicVariables() );
181
182 context->createScanner(is);
183
184 InstrScript_parse(context);
185 dmsg(2,("Allocating %ld bytes of global int VM memory.\n", long(context->globalIntVarCount * sizeof(int))));
186 dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
187 if (!context->globalIntMemory)
188 context->globalIntMemory = new ArrayList<int>();
189 if (!context->globalStrMemory)
190 context->globalStrMemory = new ArrayList<String>();
191 context->globalIntMemory->resize(context->globalIntVarCount);
192 memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(int));
193
194 context->globalStrMemory->resize(context->globalStrVarCount);
195
196 context->destroyScanner();
197
198 return context;
199 }
200
201 void ScriptVM::dumpParsedScript(VMParserContext* context) {
202 ParserContext* ctx = dynamic_cast<ParserContext*>(context);
203 if (!ctx) {
204 std::cerr << "No VM context. So nothing to dump.\n";
205 return;
206 }
207 if (!ctx->handlers) {
208 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
209 return;
210 }
211 if (!ctx->globalIntMemory) {
212 std::cerr << "Internal error: no global memory assigend to script VM.\n";
213 return;
214 }
215 ctx->handlers->dump();
216 }
217
218 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
219 ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
220 ExecContext* execCtx = new ExecContext();
221
222 if (parserCtx->requiredMaxStackSize < 0) {
223 parserCtx->requiredMaxStackSize =
224 _requiredMaxStackSizeFor(&*parserCtx->handlers);
225 }
226 execCtx->stack.resize(parserCtx->requiredMaxStackSize);
227 dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
228 long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
229 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
230 const int polySize = parserCtx->polyphonicIntVarCount;
231 execCtx->polyphonicIntMemory.resize(polySize);
232 memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
233
234 dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
235 return execCtx;
236 }
237
238 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
239 std::istringstream iss(s);
240 return syntaxHighlighting(&iss);
241 }
242
243 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
244 NkspScanner scanner(is);
245 std::vector<SourceToken> tokens = scanner.tokens();
246 std::vector<VMSourceToken> result;
247 result.resize(tokens.size());
248 for (int i = 0; i < tokens.size(); ++i) {
249 SourceToken* st = new SourceToken;
250 *st = tokens[i];
251 result[i] = VMSourceToken(st);
252 }
253 return result;
254 }
255
256 VMFunction* ScriptVM::functionByName(const String& name) {
257 if (name == "message") return m_fnMessage;
258 else if (name == "exit") return m_fnExit;
259 else if (name == "wait") return m_fnWait;
260 else if (name == "abs") return m_fnAbs;
261 else if (name == "random") return m_fnRandom;
262 else if (name == "num_elements") return m_fnNumElements;
263 else if (name == "inc") return m_fnInc;
264 else if (name == "dec") return m_fnDec;
265 else if (name == "sh_left") return m_fnShLeft;
266 else if (name == "sh_right") return m_fnShRight;
267 else if (name == "min") return m_fnMin;
268 else if (name == "max") return m_fnMax;
269 return NULL;
270 }
271
272 std::map<String,VMIntRelPtr*> ScriptVM::builtInIntVariables() {
273 return std::map<String,VMIntRelPtr*>();
274 }
275
276 std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
277 return std::map<String,VMInt8Array*>();
278 }
279
280 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
281 std::map<String,VMDynVar*> m;
282
283 m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
284 m["$NKSP_REAL_TIMER"] = m_varRealTimer;
285 m["$KSP_TIMER"] = m_varRealTimer;
286
287 return m;
288 }
289
290 std::map<String,int> ScriptVM::builtInConstIntVariables() {
291 std::map<String,int> m;
292
293 m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
294 m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
295 m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
296 m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
297
298 return m;
299 }
300
301 VMEventHandler* ScriptVM::currentVMEventHandler() {
302 return m_eventHandler;
303 }
304
305 VMParserContext* ScriptVM::currentVMParserContext() {
306 return m_parserContext;
307 }
308
309 VMExecContext* ScriptVM::currentVMExecContext() {
310 if (!m_parserContext) return NULL;
311 return m_parserContext->execContext;
312 }
313
314 void ScriptVM::setAutoSuspendEnabled(bool b) {
315 m_autoSuspend = b;
316 }
317
318 bool ScriptVM::isAutoSuspendEnabled() const {
319 return m_autoSuspend;
320 }
321
322 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
323 m_parserContext = dynamic_cast<ParserContext*>(parserContext);
324 if (!m_parserContext) {
325 std::cerr << "No VM parser context provided. Did you load a script?.\n";
326 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
327 }
328
329 // a ParserContext object is always tied to exactly one ScriptVM object
330 assert(m_parserContext->functionProvider == this);
331
332 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
333 if (!ctx) {
334 std::cerr << "Invalid VM exec context.\n";
335 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
336 }
337 EventHandler* h = dynamic_cast<EventHandler*>(handler);
338 if (!h) return VM_EXEC_NOT_RUNNING;
339 m_eventHandler = handler;
340
341 m_parserContext->execContext = ctx;
342
343 ctx->status = VM_EXEC_RUNNING;
344 StmtFlags_t flags = STMT_SUCCESS;
345 int instructionsCounter = 0;
346
347 int& frameIdx = ctx->stackFrame;
348 if (frameIdx < 0) { // start condition ...
349 frameIdx = -1;
350 ctx->pushStack(h);
351 }
352
353 while (flags == STMT_SUCCESS && frameIdx >= 0) {
354 if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
355 std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
356 flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
357 break;
358 }
359
360 ExecContext::StackFrame& frame = ctx->stack[frameIdx];
361 switch (frame.statement->statementType()) {
362 case STMT_LEAF: {
363 #if DEBUG_SCRIPTVM_CORE
364 _printIndents(frameIdx);
365 printf("-> STMT_LEAF\n");
366 #endif
367 LeafStatement* leaf = (LeafStatement*) frame.statement;
368 flags = leaf->exec();
369 ctx->popStack();
370 break;
371 }
372
373 case STMT_LIST: {
374 #if DEBUG_SCRIPTVM_CORE
375 _printIndents(frameIdx);
376 printf("-> STMT_LIST subidx=%d\n", frame.subindex);
377 #endif
378 Statements* stmts = (Statements*) frame.statement;
379 if (stmts->statement(frame.subindex)) {
380 ctx->pushStack(
381 stmts->statement(frame.subindex++)
382 );
383 } else {
384 #if DEBUG_SCRIPTVM_CORE
385 _printIndents(frameIdx);
386 printf("[END OF LIST] subidx=%d\n", frame.subindex);
387 #endif
388 ctx->popStack();
389 }
390 break;
391 }
392
393 case STMT_BRANCH: {
394 #if DEBUG_SCRIPTVM_CORE
395 _printIndents(frameIdx);
396 printf("-> STMT_BRANCH\n");
397 #endif
398 if (frame.subindex < 0) ctx->popStack();
399 else {
400 BranchStatement* branchStmt = (BranchStatement*) frame.statement;
401 frame.subindex = branchStmt->evalBranch();
402 if (frame.subindex >= 0) {
403 ctx->pushStack(
404 branchStmt->branch(frame.subindex)
405 );
406 frame.subindex = -1;
407 } else ctx->popStack();
408 }
409 break;
410 }
411
412 case STMT_LOOP: {
413 #if DEBUG_SCRIPTVM_CORE
414 _printIndents(frameIdx);
415 printf("-> STMT_LOOP\n");
416 #endif
417 While* whileStmt = (While*) frame.statement;
418 if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
419 ctx->pushStack(
420 whileStmt->statements()
421 );
422 if (flags == STMT_SUCCESS && m_autoSuspend &&
423 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
424 {
425 flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
426 ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
427 }
428 } else ctx->popStack();
429 break;
430 }
431 }
432
433 if (flags == STMT_SUCCESS && m_autoSuspend &&
434 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
435 {
436 flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
437 ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
438 }
439
440 ++instructionsCounter;
441 }
442
443 if (flags & STMT_SUSPEND_SIGNALLED) {
444 ctx->status = VM_EXEC_SUSPENDED;
445 } else {
446 ctx->status = VM_EXEC_NOT_RUNNING;
447 if (flags & STMT_ERROR_OCCURRED)
448 ctx->status = VM_EXEC_ERROR;
449 ctx->reset();
450 }
451
452 m_eventHandler = NULL;
453 m_parserContext->execContext = NULL;
454 m_parserContext = NULL;
455 return ctx->status;
456 }
457
458 } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC