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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3260 - (hide annotations) (download)
Wed May 31 21:07:44 2017 UTC (6 years, 10 months ago) by schoenebeck
File size: 18744 byte(s)
* NKSP language: Added support for "synchronized .. end synchronized"
  code blocks.
* Bumped version (2.0.0.svn60).

1 schoenebeck 2581 /*
2 schoenebeck 3076 * Copyright (c) 2014 - 2017 Christian Schoenebeck
3 schoenebeck 2581 *
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 schoenebeck 2588 #include <string.h>
13 schoenebeck 2619 #include <assert.h>
14 schoenebeck 2581 #include "../common/global_private.h"
15     #include "tree.h"
16 schoenebeck 2885 #include "CoreVMFunctions.h"
17 schoenebeck 2942 #include "CoreVMDynVars.h"
18 schoenebeck 2885 #include "editor/NkspScanner.h"
19 schoenebeck 2581
20     #define DEBUG_SCRIPTVM_CORE 0
21    
22 schoenebeck 2974 /**
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 schoenebeck 2581 int InstrScript_parse(LinuxSampler::ParserContext*);
60    
61     namespace LinuxSampler {
62    
63 schoenebeck 3034 #if DEBUG_SCRIPTVM_CORE
64 schoenebeck 2581 static void _printIndents(int n) {
65     for (int i = 0; i < n; ++i) printf(" ");
66     fflush(stdout);
67     }
68 schoenebeck 3034 #endif
69 schoenebeck 2581
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 schoenebeck 3260
121     case STMT_SYNC: {
122     #if DEBUG_SCRIPTVM_CORE
123     _printIndents(depth);
124     printf("-> STMT_SYNC\n");
125     #endif
126     SyncBlock* syncStmt = (SyncBlock*) statement;
127     if (syncStmt->statements())
128     return _requiredMaxStackSizeFor( syncStmt->statements() ) + 1;
129     else
130     return 1;
131     }
132 schoenebeck 2581 }
133    
134     return 1; // actually just to avoid compiler warning
135     }
136    
137     static int _requiredMaxStackSizeFor(EventHandlers* handlers) {
138     int max = 1;
139     for (int i = 0; i < handlers->size(); ++i) {
140     int size = _requiredMaxStackSizeFor(handlers->eventHandler(i));
141     if (max < size) max = size;
142     }
143     return max;
144     }
145    
146 schoenebeck 2974 ScriptVM::ScriptVM() : m_eventHandler(NULL), m_parserContext(NULL), m_autoSuspend(true) {
147 schoenebeck 2885 m_fnMessage = new CoreVMFunction_message;
148     m_fnExit = new CoreVMFunction_exit;
149     m_fnWait = new CoreVMFunction_wait(this);
150     m_fnAbs = new CoreVMFunction_abs;
151     m_fnRandom = new CoreVMFunction_random;
152     m_fnNumElements = new CoreVMFunction_num_elements;
153 schoenebeck 2945 m_fnInc = new CoreVMFunction_inc;
154     m_fnDec = new CoreVMFunction_dec;
155 schoenebeck 3076 m_fnInRange = new CoreVMFunction_in_range;
156 schoenebeck 2942 m_varRealTimer = new CoreVMDynVar_NKSP_REAL_TIMER;
157     m_varPerfTimer = new CoreVMDynVar_NKSP_PERF_TIMER;
158 schoenebeck 2965 m_fnShLeft = new CoreVMFunction_sh_left;
159     m_fnShRight = new CoreVMFunction_sh_right;
160 schoenebeck 2970 m_fnMin = new CoreVMFunction_min;
161     m_fnMax = new CoreVMFunction_max;
162 schoenebeck 3221 m_fnArrayEqual = new CoreVMFunction_array_equal;
163     m_fnSearch = new CoreVMFunction_search;
164     m_fnSort = new CoreVMFunction_sort;
165 schoenebeck 2581 }
166    
167     ScriptVM::~ScriptVM() {
168 schoenebeck 2885 delete m_fnMessage;
169     delete m_fnExit;
170     delete m_fnWait;
171     delete m_fnAbs;
172     delete m_fnRandom;
173     delete m_fnNumElements;
174 schoenebeck 2945 delete m_fnInc;
175     delete m_fnDec;
176 schoenebeck 3076 delete m_fnInRange;
177 schoenebeck 2965 delete m_fnShLeft;
178     delete m_fnShRight;
179 schoenebeck 2970 delete m_fnMin;
180     delete m_fnMax;
181 schoenebeck 3221 delete m_fnArrayEqual;
182     delete m_fnSearch;
183     delete m_fnSort;
184 schoenebeck 2942 delete m_varRealTimer;
185     delete m_varPerfTimer;
186 schoenebeck 2581 }
187    
188 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(const String& s) {
189 schoenebeck 2581 std::istringstream iss(s);
190 schoenebeck 2588 return loadScript(&iss);
191 schoenebeck 2581 }
192    
193 schoenebeck 2588 VMParserContext* ScriptVM::loadScript(std::istream* is) {
194     ParserContext* context = new ParserContext(this);
195     //printf("parserCtx=0x%lx\n", (uint64_t)context);
196 schoenebeck 2594
197     context->registerBuiltInConstIntVariables( builtInConstIntVariables() );
198     context->registerBuiltInIntVariables( builtInIntVariables() );
199     context->registerBuiltInIntArrayVariables( builtInIntArrayVariables() );
200 schoenebeck 2942 context->registerBuiltInDynVariables( builtInDynamicVariables() );
201 schoenebeck 2594
202 schoenebeck 2588 context->createScanner(is);
203 schoenebeck 2581
204 schoenebeck 2588 InstrScript_parse(context);
205 persson 2837 dmsg(2,("Allocating %ld bytes of global int VM memory.\n", long(context->globalIntVarCount * sizeof(int))));
206 schoenebeck 2611 dmsg(2,("Allocating %d of global VM string variables.\n", context->globalStrVarCount));
207 schoenebeck 2588 if (!context->globalIntMemory)
208     context->globalIntMemory = new ArrayList<int>();
209     if (!context->globalStrMemory)
210     context->globalStrMemory = new ArrayList<String>();
211     context->globalIntMemory->resize(context->globalIntVarCount);
212     memset(&((*context->globalIntMemory)[0]), 0, context->globalIntVarCount * sizeof(int));
213    
214     context->globalStrMemory->resize(context->globalStrVarCount);
215 schoenebeck 2581
216 schoenebeck 2588 context->destroyScanner();
217 schoenebeck 2581
218 schoenebeck 2588 return context;
219 schoenebeck 2581 }
220    
221 schoenebeck 2588 void ScriptVM::dumpParsedScript(VMParserContext* context) {
222     ParserContext* ctx = dynamic_cast<ParserContext*>(context);
223     if (!ctx) {
224 schoenebeck 2581 std::cerr << "No VM context. So nothing to dump.\n";
225     return;
226     }
227 schoenebeck 2588 if (!ctx->handlers) {
228 schoenebeck 2581 std::cerr << "No event handlers defined in script. So nothing to dump.\n";
229     return;
230     }
231 schoenebeck 2588 if (!ctx->globalIntMemory) {
232 schoenebeck 2581 std::cerr << "Internal error: no global memory assigend to script VM.\n";
233     return;
234     }
235 schoenebeck 2588 ctx->handlers->dump();
236 schoenebeck 2581 }
237    
238 schoenebeck 2588 VMExecContext* ScriptVM::createExecContext(VMParserContext* parserContext) {
239     ParserContext* parserCtx = dynamic_cast<ParserContext*>(parserContext);
240     ExecContext* execCtx = new ExecContext();
241    
242     if (parserCtx->requiredMaxStackSize < 0) {
243     parserCtx->requiredMaxStackSize =
244     _requiredMaxStackSizeFor(&*parserCtx->handlers);
245     }
246     execCtx->stack.resize(parserCtx->requiredMaxStackSize);
247 persson 2837 dmsg(2,("Created VM exec context with %ld bytes VM stack size.\n",
248     long(parserCtx->requiredMaxStackSize * sizeof(ExecContext::StackFrame))));
249 schoenebeck 2588 //printf("execCtx=0x%lx\n", (uint64_t)execCtx);
250     const int polySize = parserCtx->polyphonicIntVarCount;
251     execCtx->polyphonicIntMemory.resize(polySize);
252     memset(&execCtx->polyphonicIntMemory[0], 0, polySize * sizeof(int));
253    
254 persson 2837 dmsg(2,("Allocated %ld bytes polyphonic memory.\n", long(polySize * sizeof(int))));
255 schoenebeck 2588 return execCtx;
256 schoenebeck 2581 }
257    
258 schoenebeck 2885 std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(const String& s) {
259     std::istringstream iss(s);
260     return syntaxHighlighting(&iss);
261     }
262    
263     std::vector<VMSourceToken> ScriptVM::syntaxHighlighting(std::istream* is) {
264     NkspScanner scanner(is);
265     std::vector<SourceToken> tokens = scanner.tokens();
266     std::vector<VMSourceToken> result;
267     result.resize(tokens.size());
268     for (int i = 0; i < tokens.size(); ++i) {
269     SourceToken* st = new SourceToken;
270     *st = tokens[i];
271     result[i] = VMSourceToken(st);
272     }
273     return result;
274     }
275    
276 schoenebeck 2581 VMFunction* ScriptVM::functionByName(const String& name) {
277 schoenebeck 2885 if (name == "message") return m_fnMessage;
278     else if (name == "exit") return m_fnExit;
279     else if (name == "wait") return m_fnWait;
280     else if (name == "abs") return m_fnAbs;
281     else if (name == "random") return m_fnRandom;
282     else if (name == "num_elements") return m_fnNumElements;
283 schoenebeck 2945 else if (name == "inc") return m_fnInc;
284     else if (name == "dec") return m_fnDec;
285 schoenebeck 3076 else if (name == "in_range") return m_fnInRange;
286 schoenebeck 2965 else if (name == "sh_left") return m_fnShLeft;
287     else if (name == "sh_right") return m_fnShRight;
288 schoenebeck 2970 else if (name == "min") return m_fnMin;
289     else if (name == "max") return m_fnMax;
290 schoenebeck 3221 else if (name == "array_equal") return m_fnArrayEqual;
291     else if (name == "search") return m_fnSearch;
292     else if (name == "sort") return m_fnSort;
293 schoenebeck 2581 return NULL;
294     }
295 schoenebeck 2588
296 schoenebeck 2594 std::map<String,VMIntRelPtr*> ScriptVM::builtInIntVariables() {
297     return std::map<String,VMIntRelPtr*>();
298     }
299    
300     std::map<String,VMInt8Array*> ScriptVM::builtInIntArrayVariables() {
301     return std::map<String,VMInt8Array*>();
302     }
303    
304 schoenebeck 2942 std::map<String,VMDynVar*> ScriptVM::builtInDynamicVariables() {
305     std::map<String,VMDynVar*> m;
306    
307     m["$NKSP_PERF_TIMER"] = m_varPerfTimer;
308     m["$NKSP_REAL_TIMER"] = m_varRealTimer;
309     m["$KSP_TIMER"] = m_varRealTimer;
310    
311     return m;
312     }
313    
314 schoenebeck 2594 std::map<String,int> ScriptVM::builtInConstIntVariables() {
315 schoenebeck 2948 std::map<String,int> m;
316    
317     m["$NI_CB_TYPE_INIT"] = VM_EVENT_HANDLER_INIT;
318     m["$NI_CB_TYPE_NOTE"] = VM_EVENT_HANDLER_NOTE;
319     m["$NI_CB_TYPE_RELEASE"] = VM_EVENT_HANDLER_RELEASE;
320     m["$NI_CB_TYPE_CONTROLLER"] = VM_EVENT_HANDLER_CONTROLLER;
321    
322     return m;
323 schoenebeck 2594 }
324    
325 schoenebeck 2879 VMEventHandler* ScriptVM::currentVMEventHandler() {
326     return m_eventHandler;
327     }
328    
329 schoenebeck 2588 VMParserContext* ScriptVM::currentVMParserContext() {
330     return m_parserContext;
331     }
332    
333 schoenebeck 2581 VMExecContext* ScriptVM::currentVMExecContext() {
334 schoenebeck 2588 if (!m_parserContext) return NULL;
335     return m_parserContext->execContext;
336 schoenebeck 2581 }
337    
338 schoenebeck 2974 void ScriptVM::setAutoSuspendEnabled(bool b) {
339     m_autoSuspend = b;
340     }
341    
342     bool ScriptVM::isAutoSuspendEnabled() const {
343     return m_autoSuspend;
344     }
345    
346 schoenebeck 2588 VMExecStatus_t ScriptVM::exec(VMParserContext* parserContext, VMExecContext* execContex, VMEventHandler* handler) {
347     m_parserContext = dynamic_cast<ParserContext*>(parserContext);
348     if (!m_parserContext) {
349     std::cerr << "No VM parser context provided. Did you load a script?.\n";
350 schoenebeck 2581 return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
351     }
352    
353 schoenebeck 2611 // a ParserContext object is always tied to exactly one ScriptVM object
354     assert(m_parserContext->functionProvider == this);
355    
356 schoenebeck 2581 ExecContext* ctx = dynamic_cast<ExecContext*>(execContex);
357     if (!ctx) {
358     std::cerr << "Invalid VM exec context.\n";
359     return VMExecStatus_t(VM_EXEC_NOT_RUNNING | VM_EXEC_ERROR);
360     }
361     EventHandler* h = dynamic_cast<EventHandler*>(handler);
362     if (!h) return VM_EXEC_NOT_RUNNING;
363 schoenebeck 2879 m_eventHandler = handler;
364 schoenebeck 2581
365 schoenebeck 2588 m_parserContext->execContext = ctx;
366 schoenebeck 2581
367     ctx->status = VM_EXEC_RUNNING;
368 schoenebeck 3221 ctx->instructionsCount = 0;
369 schoenebeck 2581 StmtFlags_t flags = STMT_SUCCESS;
370 schoenebeck 2974 int instructionsCounter = 0;
371 schoenebeck 3260 int synced = m_autoSuspend ? 0 : 1;
372 schoenebeck 2581
373     int& frameIdx = ctx->stackFrame;
374     if (frameIdx < 0) { // start condition ...
375     frameIdx = -1;
376     ctx->pushStack(h);
377     }
378    
379     while (flags == STMT_SUCCESS && frameIdx >= 0) {
380     if (frameIdx >= ctx->stack.size()) { // should never happen, otherwise it's a bug ...
381     std::cerr << "CRITICAL: VM stack overflow! (" << frameIdx << ")\n";
382     flags = StmtFlags_t(STMT_ABORT_SIGNALLED | STMT_ERROR_OCCURRED);
383     break;
384     }
385    
386     ExecContext::StackFrame& frame = ctx->stack[frameIdx];
387     switch (frame.statement->statementType()) {
388     case STMT_LEAF: {
389     #if DEBUG_SCRIPTVM_CORE
390     _printIndents(frameIdx);
391     printf("-> STMT_LEAF\n");
392     #endif
393     LeafStatement* leaf = (LeafStatement*) frame.statement;
394     flags = leaf->exec();
395     ctx->popStack();
396     break;
397     }
398    
399     case STMT_LIST: {
400     #if DEBUG_SCRIPTVM_CORE
401     _printIndents(frameIdx);
402     printf("-> STMT_LIST subidx=%d\n", frame.subindex);
403     #endif
404     Statements* stmts = (Statements*) frame.statement;
405     if (stmts->statement(frame.subindex)) {
406     ctx->pushStack(
407     stmts->statement(frame.subindex++)
408     );
409     } else {
410     #if DEBUG_SCRIPTVM_CORE
411     _printIndents(frameIdx);
412     printf("[END OF LIST] subidx=%d\n", frame.subindex);
413     #endif
414     ctx->popStack();
415     }
416     break;
417     }
418    
419     case STMT_BRANCH: {
420     #if DEBUG_SCRIPTVM_CORE
421     _printIndents(frameIdx);
422     printf("-> STMT_BRANCH\n");
423     #endif
424     if (frame.subindex < 0) ctx->popStack();
425     else {
426     BranchStatement* branchStmt = (BranchStatement*) frame.statement;
427     frame.subindex = branchStmt->evalBranch();
428     if (frame.subindex >= 0) {
429     ctx->pushStack(
430     branchStmt->branch(frame.subindex)
431     );
432     frame.subindex = -1;
433     } else ctx->popStack();
434     }
435     break;
436     }
437    
438     case STMT_LOOP: {
439     #if DEBUG_SCRIPTVM_CORE
440     _printIndents(frameIdx);
441     printf("-> STMT_LOOP\n");
442     #endif
443     While* whileStmt = (While*) frame.statement;
444     if (whileStmt->evalLoopStartCondition() && whileStmt->statements()) {
445     ctx->pushStack(
446     whileStmt->statements()
447     );
448 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
449 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_SOFT)
450     {
451     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
452     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
453     }
454 schoenebeck 2581 } else ctx->popStack();
455 schoenebeck 2974 break;
456 schoenebeck 2581 }
457 schoenebeck 3260
458     case STMT_SYNC: {
459     #if DEBUG_SCRIPTVM_CORE
460     _printIndents(frameIdx);
461     printf("-> STMT_SYNC\n");
462     #endif
463     SyncBlock* syncStmt = (SyncBlock*) frame.statement;
464     if (!frame.subindex++ && syncStmt->statements()) {
465     ++synced;
466     ctx->pushStack(
467     syncStmt->statements()
468     );
469     } else {
470     ctx->popStack();
471     --synced;
472     }
473     break;
474     }
475 schoenebeck 2581 }
476 schoenebeck 2974
477 schoenebeck 3260 if (flags == STMT_SUCCESS && !synced &&
478 schoenebeck 2974 instructionsCounter > SCRIPTVM_MAX_INSTR_PER_CYCLE_HARD)
479     {
480     flags = StmtFlags_t(STMT_SUSPEND_SIGNALLED);
481     ctx->suspendMicroseconds = SCRIPT_VM_FORCE_SUSPENSION_MICROSECONDS;
482     }
483    
484     ++instructionsCounter;
485 schoenebeck 2581 }
486    
487     if (flags & STMT_SUSPEND_SIGNALLED) {
488     ctx->status = VM_EXEC_SUSPENDED;
489     } else {
490     ctx->status = VM_EXEC_NOT_RUNNING;
491     if (flags & STMT_ERROR_OCCURRED)
492     ctx->status = VM_EXEC_ERROR;
493     ctx->reset();
494     }
495    
496 schoenebeck 3221 ctx->instructionsCount = instructionsCounter;
497    
498 schoenebeck 2879 m_eventHandler = NULL;
499 schoenebeck 2588 m_parserContext->execContext = NULL;
500     m_parserContext = NULL;
501 schoenebeck 2581 return ctx->status;
502     }
503    
504     } // namespace LinuxSampler

  ViewVC Help
Powered by ViewVC