-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMQuickJsRuntime.cpp
More file actions
411 lines (357 loc) · 11.8 KB
/
Copy pathMQuickJsRuntime.cpp
File metadata and controls
411 lines (357 loc) · 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//------------------------------ tabstop = 4 ----------------------------------
//
// If not stated otherwise in this file or this component's LICENSE file the
// following copyright and licenses apply:
//
// Copyright 2026 Comcast Cable Communications Management, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
//------------------------------ tabstop = 4 ----------------------------------
//
// Created by tlea on 2/18/26
//
#define LOG_TAG "MQuickJsRuntime"
#define logFmt(fmt) "(%s): " fmt, __func__
#include "MQuickJsRuntime.h"
#include "SbmdJsUtil.h"
#include "matter/sbmd/SafeJSValue.h"
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <string>
extern "C" {
#include <icLog/logging.h>
#include <mquickjs/mquickjs.h>
// The js_stdlib variable is defined in MQuickJsStdlib.c (compiled as C)
// and provides the mquickjs standard library (console, performance, JSON, etc.)
extern const JSSTDLibraryDef js_stdlib;
}
namespace barton
{
using namespace mquickjs;
// Static member initialization
uint8_t *MQuickJsRuntime::memBuffer = nullptr;
size_t MQuickJsRuntime::memSize = 0;
JSContext *MQuickJsRuntime::ctx = nullptr;
std::mutex MQuickJsRuntime::mutex;
bool MQuickJsRuntime::initialized = false;
size_t MQuickJsRuntime::peakHeapUsed = 0;
std::chrono::steady_clock::time_point MQuickJsRuntime::deadline {};
namespace
{
/**
* Interrupt handler for script execution timeout.
*
* Called periodically by the mquickjs engine during bytecode execution.
* Returns non-zero to abort the running script when the deadline has passed.
* When no deadline is active (epoch value), always returns 0.
*/
int ScriptInterruptHandler(JSContext * /*ctx*/, void * /*opaque*/)
{
auto currentDeadline = MQuickJsRuntime::GetDeadline();
// No deadline set, allow script to run uninterrupted
if (currentDeadline == std::chrono::steady_clock::time_point {})
{
return 0;
}
if (std::chrono::steady_clock::now() > currentDeadline)
{
icError("SBMD script execution timeout: script exceeded the configured time limit");
return 1;
}
return 0;
}
} // anonymous namespace
bool MQuickJsRuntime::Initialize(size_t memorySize)
{
if (initialized)
{
icDebug("Shared mquickjs context already initialized");
return true;
}
icInfo("Initializing shared mquickjs context for SBMD scripts (%zu bytes)...", memorySize);
peakHeapUsed = 0;
// Allocate the memory buffer for the mquickjs context
memBuffer = static_cast<uint8_t *>(malloc(memorySize));
if (!memBuffer)
{
icError("Failed to allocate %zu bytes for mquickjs context", memorySize);
return false;
}
memSize = memorySize;
// Create the context with pre-allocated memory and default stdlib
ctx = JS_NewContext(memBuffer, memSize, &js_stdlib);
if (!ctx)
{
icError("Failed to create shared mquickjs context");
free(memBuffer);
memBuffer = nullptr;
memSize = 0;
return false;
}
// Install URL polyfill (required by some JS libraries)
// Use JS_EVAL_REPL so var declarations persist as global variables
const char *urlPolyfill = R"(
var URL = function URL(url, base) {
this.href = url;
this.protocol = '';
this.host = '';
this.hostname = '';
this.port = '';
this.pathname = url;
this.search = '';
this.hash = '';
this.origin = '';
};
URL.prototype.toString = function() { return this.href; };
globalThis.URL = URL;
)";
JSValue urlResult = JS_Eval(ctx, urlPolyfill, strlen(urlPolyfill), "<url-polyfill>", JS_EVAL_REPL);
if (JS_IsException(urlResult))
{
icError("Failed to install URL polyfill: %s", GetExceptionString(ctx).c_str());
{
std::lock_guard<std::mutex> lock(mutex);
LogMemoryUsage("polyfill-failed", IC_LOG_ERROR, true);
}
JS_FreeContext(ctx);
ctx = nullptr;
free(memBuffer);
memBuffer = nullptr;
memSize = 0;
return false;
}
// Check if polyfill installation left an exception
std::string exMsg;
if (CheckAndClearPendingException(ctx, &exMsg))
{
icError("Polyfill installation left a pending exception: %s - this is a bug", exMsg.c_str());
}
initialized = true;
// Install the script execution timeout interrupt handler
JS_SetInterruptHandler(ctx, ScriptInterruptHandler);
icDebug("Script execution interrupt handler installed");
{
std::lock_guard<std::mutex> lock(mutex);
LogMemoryUsage("post-init (context + stdlib + polyfills)", IC_LOG_DEBUG);
}
icInfo("Shared mquickjs context initialized successfully");
return true;
}
void MQuickJsRuntime::Shutdown()
{
if (!initialized)
{
return;
}
icInfo("Shutting down shared mquickjs context...");
if (ctx)
{
JS_FreeContext(ctx);
ctx = nullptr;
}
if (memBuffer)
{
free(memBuffer);
memBuffer = nullptr;
memSize = 0;
}
initialized = false;
icInfo("Shared mquickjs context shutdown complete");
}
JSContext *MQuickJsRuntime::GetSharedContext()
{
return ctx;
}
std::mutex &MQuickJsRuntime::GetMutex()
{
return mutex;
}
bool MQuickJsRuntime::IsInitialized()
{
return initialized;
}
bool MQuickJsRuntime::CheckAndClearPendingException(JSContext *ctx, std::string *outExceptionMsg)
{
if (!ctx)
{
return false;
}
JSValue pendingExRaw = JS_GetException(ctx);
// JS_GetException returns JS_NULL or JS_UNDEFINED when no exception is pending
bool hasException = !JS_IsNull(pendingExRaw) && !JS_IsUndefined(pendingExRaw) && !JS_IsUninitialized(pendingExRaw);
if (!hasException)
{
return false;
}
// mquickjs uses a moving/compacting GC: every JS allocation (including each JS_GetPropertyStr /
// JS_ToCString below) can relocate live objects, invalidating any raw JSValue held in a C
// local. Root the exception so it stays valid across the multiple property reads used to build
// the diagnostic message; otherwise the second and later reads dereference a stale pointer.
SafeJSValue pendingEx(ctx, pendingExRaw);
// Extract exception message if caller wants it
if (outExceptionMsg)
{
std::string exMsg;
// Try ToCString for string exceptions
if (JS_IsString(ctx, pendingEx.Get()))
{
JSCStringBuf buf;
const char *str = JS_ToCString(ctx, pendingEx.Get(), &buf);
if (str)
{
exMsg = str;
}
}
else if (JS_IsPtr(pendingEx.Get()))
{
// Try "message" property for Error objects
SafeJSValue msgVal(ctx, JS_GetPropertyStr(ctx, pendingEx.Get(), "message"));
if (JS_IsString(ctx, msgVal.Get()))
{
JSCStringBuf buf;
const char *msgStr = JS_ToCString(ctx, msgVal.Get(), &buf);
if (msgStr)
{
exMsg = msgStr;
}
}
// Also try to get stack trace for debugging
SafeJSValue stackVal(ctx, JS_GetPropertyStr(ctx, pendingEx.Get(), "stack"));
if (JS_IsString(ctx, stackVal.Get()))
{
JSCStringBuf buf;
const char *stackStr = JS_ToCString(ctx, stackVal.Get(), &buf);
if (stackStr)
{
if (!exMsg.empty())
{
exMsg += " | Stack: ";
}
exMsg += stackStr;
}
}
// Pull name/fileName/lineNumber to help localize throws that carry no
// useful stack (e.g. exceptions raised from native bindings).
for (const char *prop : {"name", "fileName", "lineNumber"})
{
SafeJSValue propVal(ctx, JS_GetPropertyStr(ctx, pendingEx.Get(), prop));
JSCStringBuf buf;
const char *propStr = JS_ToCString(ctx, propVal.Get(), &buf);
if (propStr)
{
exMsg += " | ";
exMsg += prop;
exMsg += "=";
exMsg += propStr;
}
}
}
else
{
// Try ToCString as fallback for other types
JSCStringBuf buf;
const char *str = JS_ToCString(ctx, pendingEx.Get(), &buf);
if (str)
{
exMsg = str;
}
}
if (exMsg.empty())
{
exMsg = "unknown exception";
}
*outExceptionMsg = std::move(exMsg);
}
return true;
}
void MQuickJsRuntime::LogMemoryUsage(const char *label, logPriority priority, bool walkHeap)
{
if (!ctx)
{
return;
}
int flags = walkHeap ? JS_MEMUSAGE_WALK_HEAP : 0;
JSMemoryUsage usage = {};
if (JS_GetMemoryUsage(ctx, &usage, flags) != 0)
{
icWarn("Failed to get mquickjs memory usage at '%s'", label);
return;
}
bool heapWalked = (usage.flags & JS_MEMUSAGE_WALK_HEAP) != 0;
if (heapWalked)
{
// Net heap = heap region minus free blocks reclaimed by GC
size_t netHeapUsed = 0;
if (usage.heap_used >= usage.heap_free_blocks)
{
netHeapUsed = usage.heap_used - usage.heap_free_blocks;
}
if (netHeapUsed > peakHeapUsed)
{
peakHeapUsed = netHeapUsed;
}
icLogMsg(__FILE__,
sizeof(__FILE__) - 1,
__func__,
sizeof(__func__) - 1,
__LINE__,
LOG_TAG,
priority,
logFmt("[%s] mquickjs memory: arena=%zu heap=%zu (net=%zu, free_blocks=%zu) "
"stack=%zu free_gap=%zu overhead=%zu peak_heap=%zu"),
label,
usage.arena_size,
usage.heap_used,
netHeapUsed,
usage.heap_free_blocks,
usage.stack_used,
usage.free_size,
usage.overhead,
peakHeapUsed);
}
else
{
icLogMsg(__FILE__,
sizeof(__FILE__) - 1,
__func__,
sizeof(__func__) - 1,
__LINE__,
LOG_TAG,
priority,
logFmt("[%s] mquickjs memory: arena=%zu heap=%zu "
"stack=%zu free_gap=%zu overhead=%zu (heap_free_blocks not computed)"),
label,
usage.arena_size,
usage.heap_used,
usage.stack_used,
usage.free_size,
usage.overhead);
}
}
void MQuickJsRuntime::SetDeadline(std::chrono::steady_clock::time_point value)
{
deadline = value;
}
void MQuickJsRuntime::ClearDeadline()
{
deadline = std::chrono::steady_clock::time_point {};
}
std::chrono::steady_clock::time_point MQuickJsRuntime::GetDeadline()
{
return deadline;
}
} // namespace barton