microvium
Version:
A compact, embeddable scripting engine for microcontrollers for executing small scripts written in a subset of JavaScript.
45 lines • 2.49 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.validateSnapshotBinary = exports.stringifySnapshotIL = exports.ENGINE_MINOR_VERSION = exports.HEADER_SIZE = exports.ENGINE_MAJOR_VERSION = void 0;
const utils_1 = require("./utils");
const stringify_il_1 = require("./stringify-il");
const crc_1 = require("crc");
exports.ENGINE_MAJOR_VERSION = 8 /* aka MVM_BYTECODE_VERSION */;
exports.HEADER_SIZE = 28;
exports.ENGINE_MINOR_VERSION = 0 /* aka MVM_ENGINE_VERSION */;
function stringifySnapshotIL(snapshot, opts = {}) {
return `${(0, utils_1.entriesInOrder)(snapshot.exports)
.map(([k, v]) => `export ${k} = ${(0, stringify_il_1.stringifyValue)(v)};`)
.join('\n')}\n\n${(0, utils_1.entriesInOrder)(snapshot.globalSlots)
.map(([k, v]) => `slot ${(0, utils_1.stringifyIdentifier)(k)} = ${(0, stringify_il_1.stringifyValue)(v.value)};`)
.join('\n')}\n\n${(0, utils_1.entriesInOrder)(snapshot.functions)
.map(([, v]) => (0, stringify_il_1.stringifyFunction)(v, '', opts))
.join('\n\n')}\n\n${(0, utils_1.entriesInOrder)(snapshot.allocations)
.map(([k, v]) => `${stringifyAllocationRegion(v.memoryRegion)}allocation ${k} = ${(0, stringify_il_1.stringifyAllocation)(v)};`)
.join('\n\n')}`;
}
exports.stringifySnapshotIL = stringifySnapshotIL;
function stringifyAllocationRegion(region) {
return !region || region === 'gc' ? '' : region + ' ';
}
function validateSnapshotBinary(bytecode) {
// The first 8 bytes include the integrity metadata
if (bytecode.length < 8)
return { err: 'Too short' };
const headerSize = bytecode.readUInt8(1);
if (headerSize != exports.HEADER_SIZE)
return { err: `Header size mismatch` };
const bytecodeSize = bytecode.readUInt16LE(4);
if (bytecodeSize != bytecode.length)
return { err: `Bytecode size mismatch` };
const calculatedCrc = (0, crc_1.crc16ccitt)(bytecode.slice(8));
const recordedCrc = bytecode.readUInt16LE(6);
if (calculatedCrc !== recordedCrc)
return { err: `CRC fail` };
const actualBytecodeVersion = bytecode.readUInt8(0);
if (actualBytecodeVersion !== exports.ENGINE_MAJOR_VERSION) {
return { err: `Supported bytecode version is ${exports.ENGINE_MAJOR_VERSION} but file is version ${actualBytecodeVersion}` };
}
}
exports.validateSnapshotBinary = validateSnapshotBinary;
//# sourceMappingURL=snapshot-il.js.map