/[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 2974 - (show annotations) (download)
Fri Jul 22 15:51:40 2016 UTC (7 years, 8 months ago) by schoenebeck
File size: 16956 byte(s)
* ScriptVM: Implemented automatic suspension of RT safety
  threatening scripts.
* Bumped version (2.0.0.svn25).

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

  ViewVC Help
Powered by ViewVC