/[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 3221 - (show annotations) (download)
Fri May 26 18:30:42 2017 UTC (6 years, 11 months ago) by schoenebeck
File size: 17621 byte(s)
* NKSP Fix: Never suspend "init" event handlers.
* NKSP: Implemented built-in script function "array_equal()".
* NKSP: Implemented built-in script function "search()".
* NKSP: Implemented built-in script function "sort()".
* Bumped version (2.0.0.svn52).

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

  ViewVC Help
Powered by ViewVC