amtscript.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /**
  2. * @fileoverview Script Compiler / Decompiler / Runner
  3. * @author Ylian Saint-Hilaire
  4. * @copyright Intel Corporation 2018-2022
  5. * @license Apache-2.0
  6. * @version v0.1.0e
  7. */
  8. /*jslint node: true */
  9. /*jshint node: true */
  10. /*jshint strict:false */
  11. /*jshint -W097 */
  12. /*jshint esversion: 6 */
  13. "use strict";
  14. module.exports.CreateAmtScriptEngine = function () {
  15. var o = {};
  16. // Core functions
  17. const script_functionTable1 = ['nop', 'jump', 'set', 'print', 'dialog', 'getitem', 'substr', 'indexof', 'split', 'join', 'length', 'jsonparse', 'jsonstr', 'add', 'substract', 'parseint', 'wsbatchenum', 'wsput', 'wscreate', 'wsdelete', 'wsexec', 'scriptspeed', 'wssubscribe', 'wsunsubscribe', 'readchar', 'signwithdummyca'];
  18. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  19. const script_functionTable2 = ['encodeuri', 'decodeuri', 'passwordcheck', 'atob', 'btoa', 'hex2str', 'str2hex', 'random', 'md5', 'maketoarray', 'readshort', 'readshortx', 'readint', 'readsint', 'readintx', 'shorttostr', 'shorttostrx', 'inttostr', 'inttostrx'];
  20. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  21. //script_functionTableX2 = [encodeURI, decodeURI, passwordcheck, window.atob.bind(window), window.btoa.bind(window), hex2rstr, rstr2hex, random, rstr_md5, MakeToArray, ReadShort, ReadShortX, ReadInt, ReadSInt, ReadIntX, ShortToStr, ShortToStrX, IntToStr, IntToStrX];
  22. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  23. const script_functionTable3 = ['pullsystemstatus', 'pulleventlog', 'pullauditlog', 'pullcertificates', 'pullwatchdog', 'pullsystemdefense', 'pullhardware', 'pulluserinfo', 'pullremoteaccess', 'highlightblock', 'disconnect', 'getsidstring', 'getsidbytearray'];
  24. /*
  25. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  26. script_functionTableX3 = [
  27. PullSystemStatus
  28. ,
  29. // ###BEGIN###{EventLog}
  30. PullEventLog
  31. // ###END###{EventLog}
  32. ,
  33. // ###BEGIN###{AuditLog}
  34. PullAuditLog
  35. // ###END###{AuditLog}
  36. ,
  37. // ###BEGIN###{Certificates}
  38. PullCertificates
  39. // ###END###{Certificates}
  40. ,
  41. // ###BEGIN###{AgentPresence}
  42. PullWatchdog
  43. // ###END###{AgentPresence}
  44. ,
  45. // ###BEGIN###{SystemDefense}
  46. PullSystemDefense
  47. // ###END###{SystemDefense}
  48. ,
  49. // ###BEGIN###{HardwareInfo}
  50. PullHardware
  51. // ###END###{HardwareInfo}
  52. ,
  53. PullUserInfo
  54. ,
  55. // ###BEGIN###{RemoteAccess}
  56. PullRemoteAccess
  57. // ###END###{RemoteAccess}
  58. ,
  59. // ###BEGIN###{Scripting-Editor}
  60. script_HighlightBlock
  61. // ###END###{Scripting-Editor}
  62. ,
  63. // ###BEGIN###{ComputerSelector}
  64. disconnect
  65. // ###END###{ComputerSelector}
  66. ,
  67. function (runner, x) { return GetSidString(x); }
  68. ,
  69. function (runner, x) { return GetSidByteArray(x); }
  70. ];
  71. // Setup the script state
  72. o.script_setup = function(binary, startvars) {
  73. var obj = { startvars: startvars };
  74. if (binary.length < 6) { console.error('Invalid script length'); return null; } // Script must have at least 6 byte header
  75. if (ReadInt(binary, 0) != 0x247D2945) { console.error('Invalid binary script'); return null; } // Check the script magic header
  76. if (ReadShort(binary, 4) > 1) { console.error('Unsupported script version'); return null; } // Check the script version
  77. obj.script = binary.substring(6);
  78. // obj.onStep;
  79. // obj.onConsole;
  80. // Reset the script to the start
  81. obj.reset = function (stepspeed) {
  82. obj.stop();
  83. obj.ip = 0;
  84. obj.variables = startvars;
  85. obj.state = 1;
  86. }
  87. // Start the script
  88. obj.start = function (stepspeed) {
  89. obj.stop();
  90. obj.stepspeed = stepspeed;
  91. if (stepspeed > 0) { obj.timer = setInterval(function () { obj.step() }, stepspeed); }
  92. }
  93. // Stop the script
  94. obj.stop = function () {
  95. if (obj.timer != null) { clearInterval(obj.timer); }
  96. obj.timer = null;
  97. obj.stepspeed = 0;
  98. }
  99. // function used to load and store variable values
  100. obj.getVar = function (name) { if (name == undefined) return undefined; return obj.getVarEx(name.split('.'), obj.variables); }
  101. obj.getVarEx = function (name, val) { try { if (name == undefined) return undefined; if (name.length == 0) return val; return obj.getVarEx(name.slice(1), val[name[0]]); } catch (e) { return null; } }
  102. obj.setVar = function (name, val) { obj.setVarEx(name.split('.'), obj.variables, val); }
  103. obj.setVarEx = function (name, vars, val) { if (name.length == 1) { vars[name[0]] = val; } else { obj.setVarEx(name.slice(1), vars[name[0]], val); } }
  104. // Run the script one step forward
  105. obj.step = function () {
  106. if (obj.state != 1) return;
  107. if (obj.ip < obj.script.length) {
  108. var cmdid = ReadShort(obj.script, obj.ip);
  109. var cmdlen = ReadShort(obj.script, obj.ip + 2);
  110. var argcount = ReadShort(obj.script, obj.ip + 4);
  111. var argptr = obj.ip + 6;
  112. var args = [];
  113. // Clear all temp variables (This is optional)
  114. for (var i in obj.variables) { if (i.startsWith('__')) { delete obj.variables[i]; } }
  115. // Loop on each argument, moving forward by the argument length each time
  116. for (var i = 0; i < argcount; i++) {
  117. var arglen = ReadShort(obj.script, argptr);
  118. var argval = obj.script.substring(argptr + 2, argptr + 2 + arglen);
  119. var argtyp = argval.charCodeAt(0);
  120. argval = argval.substring(1);
  121. if (argtyp < 2) {
  122. // Get the value and replace all {var} with variable values
  123. while (argval.split("{").length > 1) { var t = argval.split("{").pop().split("}").shift(); argval = argval.replace('{' + t + '}', obj.getVar(t)); }
  124. if (argtyp == 1) { obj.variables['__' + i] = decodeURI(argval); argval = '__' + i; } // If argtyp is 1, this is a literal. Store in temp variable.
  125. args.push(argval);
  126. }
  127. if (argtyp == 2 || argtyp == 3) {
  128. obj.variables['__' + i] = ReadSInt(argval, 0);
  129. args.push('__' + i);
  130. }
  131. argptr += (2 + arglen);
  132. }
  133. // Move instruction pointer forward by command size
  134. obj.ip += cmdlen;
  135. // Get all variable values
  136. var argsval = [];
  137. for (var i = 0; i < 10; i++) { argsval.push(obj.getVar(args[i])); }
  138. var storeInArg0;
  139. try {
  140. if (cmdid < 10000) {
  141. // Lets run the actual command
  142. switch (cmdid) {
  143. case 0: // nop
  144. break;
  145. case 1: // jump(label) or jump(label, a, compare, b)
  146. if (argsval[2]) {
  147. if (
  148. (argsval[2] == '<' && argsval[1] < argsval[3]) ||
  149. (argsval[2] == '<=' && argsval[1] <= argsval[3]) ||
  150. (argsval[2] == '!=' && argsval[1] != argsval[3]) ||
  151. (argsval[2] == '=' && argsval[1] == argsval[3]) ||
  152. (argsval[2] == '>=' && argsval[1] >= argsval[3]) ||
  153. (argsval[2] == '>' && argsval[1] > argsval[3])
  154. ) { obj.ip = argsval[0]; }
  155. } else {
  156. obj.ip = argsval[0]; // Set the instruction pointer to the new location in the script
  157. }
  158. break;
  159. case 2: // set(variable, value)
  160. if (args[1] == undefined) delete obj.variables[args[0]]; else obj.setVar(args[0], argsval[1]);
  161. break;
  162. case 3: // print(message)
  163. if (obj.onConsole) { obj.onConsole(obj.toString(argsval[0]), obj); } else { console.log(obj.toString(argsval[0])); }
  164. // Q(obj.consoleid).value += () + '\n'); Q(obj.console).scrollTop = Q(obj.console).scrollHeight;
  165. break;
  166. case 4: // dialog(title, content, buttons)
  167. obj.state = 2;
  168. obj.dialog = true;
  169. setDialogMode(11, argsval[0], argsval[2], obj.xxStepDialogOk, argsval[1], obj);
  170. break;
  171. case 5: // getitem(a, b, c)
  172. for (var i in argsval[1]) { if (argsval[1][i][argsval[2]] == argsval[3]) { storeInArg0 = i; } };
  173. break;
  174. case 6: // substr(variable_dest, variable_src, index, len)
  175. storeInArg0 = argsval[1].substr(argsval[2], argsval[3]);
  176. break;
  177. case 7: // indexOf(variable_dest, variable_src, index, len)
  178. storeInArg0 = argsval[1].indexOf(argsval[2]);
  179. break;
  180. case 8: // split(variable_dest, variable_src, separator)
  181. storeInArg0 = argsval[1].split(argsval[2]);
  182. break;
  183. case 9: // join(variable_dest, variable_src, separator)
  184. storeInArg0 = argsval[1].join(argsval[2]);
  185. break;
  186. case 10: // length(variable_dest, variable_src)
  187. storeInArg0 = argsval[1].length;
  188. break;
  189. case 11: // jsonparse(variable_dest, json)
  190. storeInArg0 = JSON.parse(argsval[1]);
  191. break;
  192. case 12: // jsonstr(variable_dest, variable_src)
  193. storeInArg0 = JSON.stringify(argsval[1]);
  194. break;
  195. case 13: // add(variable_dest, variable_src, value)
  196. storeInArg0 = (argsval[1] + argsval[2]);
  197. break;
  198. case 14: // substract(variable_dest, variable_src, value)
  199. storeInArg0 = (argsval[1] - argsval[2]);
  200. break;
  201. case 15: // parseInt(variable_dest, variable_src)
  202. storeInArg0 = parseInt(argsval[1]);
  203. break;
  204. case 16: // wsbatchenum(name, objectList)
  205. obj.state = 2;
  206. obj.amtstack.BatchEnum(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  207. break;
  208. case 17: // wsput(name, args)
  209. obj.state = 2;
  210. obj.amtstack.Put(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  211. break;
  212. case 18: // wscreate(name, args)
  213. obj.state = 2;
  214. obj.amtstack.Create(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  215. break;
  216. case 19: // wsdelete(name, args)
  217. obj.state = 2;
  218. obj.amtstack.Delete(argsval[0], argsval[1], obj.xxWsmanReturn, obj);
  219. break;
  220. case 20: // wsexec(name, method, args, selectors)
  221. obj.state = 2;
  222. obj.amtstack.Exec(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3]);
  223. break;
  224. case 21: // Script Speed
  225. obj.stepspeed = argsval[0];
  226. if (obj.timer != null) { clearInterval(obj.timer); obj.timer = setInterval(function () { obj.step() }, obj.stepspeed); }
  227. break;
  228. case 22: // wssubscribe(name, delivery, url, selectors, opaque, user, pass)
  229. obj.state = 2;
  230. obj.amtstack.Subscribe(argsval[0], argsval[1], argsval[2], obj.xxWsmanReturn, obj, 0, argsval[3], argsval[4], argsval[5], argsval[6]);
  231. break;
  232. case 23: // wsunsubscribe(name, selectors)
  233. obj.state = 2;
  234. obj.amtstack.UnSubscribe(argsval[0], obj.xxWsmanReturn, obj, 0, argsval[1]);
  235. break;
  236. case 24: // readchar(str, pos)
  237. console.log(argsval[1], argsval[2], argsval[1].charCodeAt(argsval[2]));
  238. storeInArg0 = argsval[1].charCodeAt(argsval[2]);
  239. break;
  240. case 25: // signWithDummyCa
  241. // ###BEGIN###{Certificates}
  242. obj.state = 2;
  243. // DERKey, xxCaPrivateKey, certattributes, issuerattributes
  244. amtcert_signWithCaKey(argsval[0], null, argsval[1], { 'CN': 'Untrusted Root Certificate' }, obj.xxSignWithDummyCaReturn);
  245. // ###END###{Certificates}
  246. break;
  247. default: {
  248. obj.state = 9;
  249. console.error("Script Error, unknown command: " + cmdid);
  250. }
  251. }
  252. } else {
  253. if (cmdid < 20000) {
  254. // functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  255. storeInArg0 = script_functionTableX2[cmdid - 10000](argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]);
  256. } else {
  257. // Optional functions of type ARG1 = func(ARG2, ARG3, ARG4, ARG5, ARG6)
  258. if (script_functionTableX3 && script_functionTableX3[cmdid - 20000]) {
  259. storeInArg0 = script_functionTableX3[cmdid - 20000](obj, argsval[1], argsval[2], argsval[3], argsval[4], argsval[5], argsval[6]); // Note that optional calls start with "obj" as first argument.
  260. }
  261. }
  262. }
  263. if (storeInArg0 != undefined) obj.setVar(args[0], storeInArg0);
  264. } catch (e) {
  265. if (typeof e == 'object') { e = e.message; }
  266. obj.setVar('_exception', e);
  267. }
  268. }
  269. if (obj.state == 1 && obj.ip >= obj.script.length) { obj.state = 0; obj.stop(); }
  270. if (obj.onStep) obj.onStep(obj);
  271. return obj;
  272. };
  273. obj.xxStepDialogOk = function (button) {
  274. obj.variables['DialogSelect'] = button;
  275. obj.state = 1;
  276. obj.dialog = false;
  277. if (obj.onStep) obj.onStep(obj);
  278. };
  279. // ###BEGIN###{**ClosureAdvancedMode}
  280. obj.xxWsmanReturnFix = function (x) {
  281. if (!x || x == null) return;
  282. if (x.Header) { x['Header'] = x.Header; delete x.Header; }
  283. if (x.Body) { x['Body'] = x.Body; delete x.Body; }
  284. if (x.Responses) { x['Responses'] = x.Responses; delete x.Responses; }
  285. if (x.Response) { x['Response'] = x.Response; delete x.Response; }
  286. if (x.ReturnValueStr) { x['ReturnValueStr'] = x.ReturnValueStr; delete x.ReturnValueStr; }
  287. };
  288. // ###END###{**ClosureAdvancedMode}
  289. obj.xxWsmanReturn = function (stack, name, responses, status) {
  290. // ###BEGIN###{**ClosureAdvancedMode}
  291. // This is required when Google Closure is used
  292. if (responses) {
  293. obj.xxWsmanReturnFix(responses);
  294. for (var i in responses) {
  295. obj.xxWsmanReturnFix(responses[i]);
  296. for (var j in responses[i]) { obj.xxWsmanReturnFix(responses[i][j]); }
  297. }
  298. }
  299. // ###END###{**ClosureAdvancedMode}
  300. obj.setVar(name, responses);
  301. obj.setVar('wsman_result', status);
  302. obj.setVar('wsman_result_str', ((httpErrorTable[status]) ? (httpErrorTable[status]) : ('Error #' + status)));
  303. obj.state = 1;
  304. if (obj.onStep) obj.onStep(obj);
  305. };
  306. // ###BEGIN###{Certificates}
  307. obj.xxSignWithDummyCaReturn = function (cert) {
  308. obj.setVar('signed_cert', btoa(_arrayBufferToString(cert)));
  309. obj.state = 1;
  310. if (obj.onStep) obj.onStep(obj);
  311. };
  312. // ###END###{Certificates}
  313. obj.toString = function (x) { if (typeof x == 'object') return JSON.stringify(x); return x; };
  314. obj.reset();
  315. return obj;
  316. }
  317. */
  318. var ReadShort = function (v, p) { return (v.charCodeAt(p) << 8) + v.charCodeAt(p + 1); };
  319. var ReadShortX = function (v, p) { return (v.charCodeAt(p + 1) << 8) + v.charCodeAt(p); };
  320. var ReadInt = function (v, p) { return (v.charCodeAt(p) * 0x1000000) + (v.charCodeAt(p + 1) << 16) + (v.charCodeAt(p + 2) << 8) + v.charCodeAt(p + 3); }; // We use "*0x1000000" instead of "<<24" because the shift converts the number to signed int32.
  321. var ReadIntX = function (v, p) { return (v.charCodeAt(p + 3) * 0x1000000) + (v.charCodeAt(p + 2) << 16) + (v.charCodeAt(p + 1) << 8) + v.charCodeAt(p); };
  322. var ShortToStr = function (v) { return String.fromCharCode((v >> 8) & 0xFF, v & 0xFF); };
  323. var ShortToStrX = function (v) { return String.fromCharCode(v & 0xFF, (v >> 8) & 0xFF); };
  324. var IntToStr = function (v) { return String.fromCharCode((v >> 24) & 0xFF, (v >> 16) & 0xFF, (v >> 8) & 0xFF, v & 0xFF); };
  325. var IntToStrX = function (v) { return String.fromCharCode(v & 0xFF, (v >> 8) & 0xFF, (v >> 16) & 0xFF, (v >> 24) & 0xFF); };
  326. // Argument types: 0 = Variable, 1 = String, 2 = Integer, 3 = Label
  327. o.script_compile = function (script, onmsg) {
  328. var r = '', scriptlines = script.split('\n'), labels = {}, labelswap = [], swaps = [];
  329. // Go thru each script line and encode it
  330. for (var i in scriptlines) {
  331. var scriptline = scriptlines[i];
  332. if (scriptline.startsWith('##SWAP ')) { var x = scriptline.split(' '); if (x.length == 3) { swaps[x[1]] = x[2]; } } // Add a swap instance
  333. if (scriptline[0] == '#' || scriptline.length == 0) continue; // Skip comments & blank lines
  334. for (var x in swaps) { scriptline = scriptline.split(x).join(swaps[x]); } // Apply all swaps
  335. var keywords = scriptline.match(/"[^"]*"|[^\s"]+/g);
  336. if ((keywords == null) || (keywords.length == 0)) continue; // Skip blank lines
  337. if (scriptline[0] == ':') { labels[keywords[0].toUpperCase()] = r.length; continue; } // Mark a label position
  338. var funcIndex = script_functionTable1.indexOf(keywords[0].toLowerCase());
  339. if (funcIndex == -1) { funcIndex = script_functionTable2.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 10000; }
  340. if (funcIndex == -1) { funcIndex = script_functionTable3.indexOf(keywords[0].toLowerCase()); if (funcIndex >= 0) funcIndex += 20000; } // Optional methods
  341. if (funcIndex == -1) { if (onmsg) { onmsg("Unabled to compile, unknown command: " + keywords[0]); } return ''; }
  342. // Encode CommandId, CmdSize, ArgCount, Arg1Len, Arg1, Arg2Len, Arg2...
  343. var cmd = ShortToStr(keywords.length - 1);
  344. for (var j in keywords) {
  345. if (j == 0) continue;
  346. if (keywords[j][0] == ':') {
  347. labelswap.push([keywords[j], r.length + cmd.length + 7]); // Add a label swap
  348. cmd += ShortToStr(5) + String.fromCharCode(3) + IntToStr(0xFFFFFFFF); // Put an empty label
  349. } else {
  350. var argint = parseInt(keywords[j]);
  351. if (argint == keywords[j]) {
  352. cmd += ShortToStr(5) + String.fromCharCode(2) + IntToStr(argint);
  353. } else {
  354. if (keywords[j][0] == '"' && keywords[j][keywords[j].length - 1] == '"') {
  355. cmd += ShortToStr(keywords[j].length - 1) + String.fromCharCode(1) + keywords[j].substring(1, keywords[j].length - 1);
  356. } else {
  357. cmd += ShortToStr(keywords[j].length + 1) + String.fromCharCode(0) + keywords[j];
  358. }
  359. }
  360. }
  361. }
  362. cmd = ShortToStr(funcIndex) + ShortToStr(cmd.length + 4) + cmd;
  363. r += cmd;
  364. }
  365. // Perform all the needed label swaps
  366. for (i in labelswap) {
  367. var label = labelswap[i][0].toUpperCase(), position = labelswap[i][1], target = labels[label];
  368. if (target == undefined) { if (onmsg) { onmsg("Unabled to compile, unknown label: " + label); } return ''; }
  369. r = r.substr(0, position) + IntToStr(target) + r.substr(position + 4);
  370. }
  371. return IntToStr(0x247D2945) + ShortToStr(1) + r;
  372. };
  373. // Decompile the script, intended for debugging only
  374. o.script_decompile = function (binary, onecmd) {
  375. var r = '', ptr = 6, labels = {};
  376. if (onecmd >= 0) {
  377. ptr = onecmd; // If we are decompiling just one command, set the ptr to that command.
  378. } else {
  379. if (binary.length < 6) { return '# Invalid script length'; }
  380. var magic = ReadInt(binary, 0);
  381. var version = ReadShort(binary, 4);
  382. if (magic != 0x247D2945) { return '# Invalid binary script: ' + magic; }
  383. if (version != 1) { return '# Invalid script version'; }
  384. }
  385. // Loop on each command, moving forward by the command length each time.
  386. while (ptr < binary.length) {
  387. var cmdid = ReadShort(binary, ptr);
  388. var cmdlen = ReadShort(binary, ptr + 2);
  389. var argcount = ReadShort(binary, ptr + 4);
  390. var argptr = ptr + 6;
  391. var argstr = '';
  392. if (!(onecmd >= 0)) { r += ":label" + (ptr - 6) + "\n"; }
  393. // Loop on each argument, moving forward by the argument length each time
  394. for (var i = 0; i < argcount; i++) {
  395. var arglen = ReadShort(binary, argptr);
  396. var argval = binary.substring(argptr + 2, argptr + 2 + arglen);
  397. var argtyp = argval.charCodeAt(0);
  398. if (argtyp == 0) { argstr += ' ' + argval.substring(1); } // Variable
  399. else if (argtyp == 1) { argstr += ' \"' + argval.substring(1) + '\"'; } // String
  400. else if (argtyp == 2) { argstr += ' ' + ReadInt(argval, 1); } // Integer
  401. else if (argtyp == 3) { // Label
  402. var target = ReadInt(argval, 1);
  403. var label = labels[target];
  404. if (!label) { label = ":label" + target; labels[label] = target; }
  405. argstr += ' ' + label;
  406. }
  407. argptr += (2 + arglen);
  408. }
  409. // Go in the script function table to decode the function
  410. if (cmdid < 10000) {
  411. r += script_functionTable1[cmdid] + argstr + "\n";
  412. } else {
  413. if (cmdid >= 20000) {
  414. r += script_functionTable3[cmdid - 20000] + argstr + "\n"; // Optional methods
  415. } else {
  416. r += script_functionTable2[cmdid - 10000] + argstr + "\n";
  417. }
  418. }
  419. ptr += cmdlen;
  420. if (onecmd >= 0) return r; // If we are decompiling just one command, exit now
  421. }
  422. // Remove all unused labels
  423. var scriptlines = r.split('\n');
  424. r = '';
  425. for (var i in scriptlines) {
  426. var line = scriptlines[i];
  427. if (line[0] != ':') { r += line + '\n'; } else { if (labels[line]) { r += line + '\n'; } }
  428. }
  429. return r;
  430. };
  431. // Convert the list of blocks into a script that can be compiled
  432. o.script_blocksToScript = function (script_BuildingBlocks, script_BlockScript) {
  433. var script = '';
  434. if (script_BuildingBlocks) {
  435. if (script_BuildingBlocks['_start']) { script += '##### Starting Block #####\r\n' + script_BuildingBlocks['_start']['code'] + '\r\n\r\n'; }
  436. for (var i in script_BlockScript) {
  437. var code = script_BlockScript[i]['code'];
  438. code = code.split("%%%~%%%").join(i);
  439. for (var j in script_BlockScript[i]['vars']) { code = code.split("%%%" + j + "%%%").join(script_BlockScript[i]['vars'][j]['value']); }
  440. script += '##### Block: ' + script_BlockScript[i]['name'] + ' #####\r\nHighlightBlock __t ' + i + '\r\n' + code + '\r\n\r\n';
  441. }
  442. if (script_BuildingBlocks['_end']) { script += '##### Ending Block #####\r\n' + script_BuildingBlocks['_end']['code'] + '\r\nHighlightBlock\r\n'; }
  443. }
  444. return script;
  445. };
  446. return o;
  447. };