nsh-js 0.1.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
Documentation
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
412
413
414
415
416
417
418
419
420
421
422
423
//! The VM sandbox: resource limits, per-call time budgets and language
//! hardening.
//!
//! Every surface runs its own QuickJS runtime, so the limits are per VM. The
//! heap's allocator ([`HeapAllocator`]) enforces its ceiling and records
//! reaching it; the stack's is a runtime setting. Time is budgeted per call
//! from Rust into JS (a bundle evaluation, an event, a timer, the microtask
//! drain, ...): QuickJS calls the interrupt handler periodically while it
//! interprets, and returning `true` unwinds the call with an exception no
//! `catch` can swallow. A long-lived app therefore never accumulates time
//! toward a limit; only a single call that does not return in time is cut
//! off.
//!
//! A bundle holds only the app's code (nsh's runtime is native), so
//! nothing in JS is trusted: limits and checks are enforced here, in Rust,
//! never in JS.

use std::{
    cell::Cell,
    ffi::c_int,
    rc::Rc,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use nsh_core::{js::Limits, time::Instant};
use rquickjs::{Ctx, allocator::Allocator, qjs};

/// The VM's allocator: enforces the heap limit itself and records a refused
/// allocation. QuickJS reports running out in several ways (an
/// `InternalError`, a `null` exception when even that cannot be allocated,
/// or an exception the app catches), so the record, not the error, tells
/// that the heap is full.
///
/// It allocates as QuickJS does without one (the system's `malloc`, sizes
/// from the allocator): no header per allocation, many of which are a few
/// dozen bytes. WebAssembly has no such `malloc`; it uses Rust's.
pub(crate) struct HeapAllocator {
    /// Bytes allocated, as `usable_size` counts them.
    used: usize,
    /// Most bytes allocated at once (0: no limit).
    limit: usize,
    exhausted: Arc<AtomicBool>,
    #[cfg(target_arch = "wasm32")]
    inner: rquickjs::allocator::RustAllocator,
}

impl HeapAllocator {
    /// An allocator of at most `limit` bytes (0: no limit) and the flag it
    /// sets when it refuses an allocation.
    pub(crate) fn new(limit: usize) -> (Self, Arc<AtomicBool>) {
        let exhausted = Arc::new(AtomicBool::new(false));
        let allocator = Self {
            used: 0,
            limit,
            exhausted: exhausted.clone(),
            #[cfg(target_arch = "wasm32")]
            inner: rquickjs::allocator::RustAllocator,
        };
        (allocator, exhausted)
    }

    /// Whether `size` more bytes fit; records a refusal.
    fn fits(&self, size: usize) -> bool {
        let fits = self.limit == 0 || self.used.saturating_add(size) <= self.limit;
        if !fits {
            self.exhausted.store(true, Ordering::Relaxed);
        }
        fits
    }

    /// Counts an allocation just made (null: none).
    fn counted(&mut self, ptr: *mut u8) -> *mut u8 {
        if !ptr.is_null() {
            // SAFETY: an allocation of this allocator.
            self.used += unsafe { <Self as Allocator>::usable_size(ptr) };
        }
        ptr
    }
}

#[cfg(not(target_arch = "wasm32"))]
mod system {
    use std::ffi::c_void;

    pub(super) use libc::{calloc, free, malloc, realloc};

    /// The usable size of a live `malloc` allocation.
    pub(super) unsafe fn usable_size(ptr: *mut c_void) -> usize {
        // SAFETY: guaranteed by the caller.
        unsafe {
            #[cfg(target_vendor = "apple")]
            return libc::malloc_size(ptr);
            #[cfg(windows)]
            return _msize(ptr);
            #[cfg(not(any(target_vendor = "apple", windows)))]
            return libc::malloc_usable_size(ptr);
        }
    }

    #[cfg(windows)]
    unsafe extern "C" {
        fn _msize(ptr: *mut c_void) -> usize;
    }
}

// SAFETY: allocations come from the system's `malloc` (aligned for any
// type, `usable_size` from it) or from `RustAllocator`, which meets the
// trait's requirements; this only refuses some (returning null, as
// allowed) and counts what it hands out.
unsafe impl Allocator for HeapAllocator {
    fn alloc(&mut self, size: usize) -> *mut u8 {
        if !self.fits(size) {
            return std::ptr::null_mut();
        }
        #[cfg(not(target_arch = "wasm32"))]
        // SAFETY: a plain allocation.
        let ptr = unsafe { system::malloc(size) }.cast();
        #[cfg(target_arch = "wasm32")]
        let ptr = self.inner.alloc(size);
        self.counted(ptr)
    }

    fn calloc(&mut self, count: usize, size: usize) -> *mut u8 {
        let Some(total) = count.checked_mul(size) else {
            return std::ptr::null_mut();
        };
        if !self.fits(total) {
            return std::ptr::null_mut();
        }
        #[cfg(not(target_arch = "wasm32"))]
        // SAFETY: a plain allocation.
        let ptr = unsafe { system::calloc(count, size) }.cast();
        #[cfg(target_arch = "wasm32")]
        let ptr = self.inner.calloc(count, size);
        self.counted(ptr)
    }

    unsafe fn dealloc(&mut self, ptr: *mut u8) {
        // SAFETY: the caller hands back an allocation of this allocator.
        unsafe {
            self.used -= Self::usable_size(ptr);
            #[cfg(not(target_arch = "wasm32"))]
            system::free(ptr.cast());
            #[cfg(target_arch = "wasm32")]
            self.inner.dealloc(ptr);
        }
    }

    unsafe fn realloc(&mut self, ptr: *mut u8, new_size: usize) -> *mut u8 {
        // SAFETY: the caller hands over an allocation of this allocator.
        let old = unsafe { Self::usable_size(ptr) };
        if new_size > old && !self.fits(new_size - old) {
            return std::ptr::null_mut();
        }
        // SAFETY: as above; on failure the old allocation stays.
        #[cfg(not(target_arch = "wasm32"))]
        let new: *mut u8 = unsafe { system::realloc(ptr.cast(), new_size) }.cast();
        // SAFETY: as above.
        #[cfg(target_arch = "wasm32")]
        let new = unsafe { self.inner.realloc(ptr, new_size) };
        if !new.is_null() {
            self.used -= old;
        }
        self.counted(new)
    }

    unsafe fn usable_size(ptr: *mut u8) -> usize {
        // SAFETY: the caller hands over an allocation of this allocator.
        unsafe {
            #[cfg(not(target_arch = "wasm32"))]
            return system::usable_size(ptr.cast());
            #[cfg(target_arch = "wasm32")]
            return rquickjs::allocator::RustAllocator::usable_size(ptr);
        }
    }
}

/// The kind of call into JS, which decides its budget.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Phase {
    /// Evaluating the bundle (or a development update).
    Load,
    /// Everything else.
    Call,
}

/// The clock of the call in progress, shared with the interrupt handler.
pub(crate) struct Budget {
    limits: Limits,
    /// When the running call must have returned.
    deadline: Rc<Cell<Option<Instant>>>,
    /// The call that overran, until its error is reported.
    tripped: Rc<Cell<Option<Phase>>>,
    /// The running call's kind.
    phase: Rc<Cell<Phase>>,
}

impl Budget {
    pub(crate) fn new(limits: Limits) -> Self {
        Self {
            limits,
            deadline: Rc::default(),
            tripped: Rc::default(),
            phase: Rc::new(Cell::new(Phase::Call)),
        }
    }

    pub(crate) fn limits(&self) -> &Limits {
        &self.limits
    }

    /// Starts the clock of a call, unless one is running (nested calls
    /// share the outermost call's budget). Returns whether it started one,
    /// which the caller passes to [`Budget::end`].
    pub(crate) fn begin(&self, phase: Phase) -> bool {
        if self.deadline.get().is_some() {
            return false;
        }
        let budget = match phase {
            Phase::Load => self.limits.load_budget,
            Phase::Call => self.limits.call_budget,
        };
        self.phase.set(phase);
        self.tripped.set(None);
        self.deadline.set(Instant::now().checked_add(budget));
        true
    }

    pub(crate) fn end(&self, started: bool) {
        if started {
            self.deadline.set(None);
        }
    }

    /// Why the last call was cut off, if it overran its budget.
    pub(crate) fn take_trip(&self) -> Option<String> {
        self.tripped.take().map(|phase| {
            let (what, budget) = match phase {
                Phase::Load => ("loading the bundle", self.limits.load_budget),
                Phase::Call => ("a call into JS", self.limits.call_budget),
            };
            format!(
                "the script was interrupted: {what} exceeded its budget of {} ms",
                budget.as_millis()
            )
        })
    }

    /// The runtime's interrupt handler: true once the running call is past
    /// its deadline or the engine is stopping.
    pub(crate) fn interrupt_handler(
        &self,
        stop: Option<std::sync::Arc<std::sync::atomic::AtomicBool>>,
    ) -> Box<dyn FnMut() -> bool> {
        let deadline = self.deadline.clone();
        let tripped = self.tripped.clone();
        let phase = self.phase.clone();
        Box::new(move || {
            if stop
                .as_ref()
                .is_some_and(|s| s.load(std::sync::atomic::Ordering::Relaxed))
            {
                return true;
            }
            match deadline.get() {
                Some(d) if Instant::now() > d => {
                    tripped.set(Some(phase.get()));
                    true
                }
                _ => false,
            }
        })
    }
}

/// Removes every way from a string to code (`eval`, the function
/// constructors) and freezes the prototypes all modules share, so one
/// module cannot change `Array.prototype` or `for…in` for the others.
/// Development bundles keep them (REPL-style debugging; hot updates are
/// evaluated from Rust and need neither).
const HARDEN: &str = r#"
(() => {
  const deny = (label) => function () {
    throw new TypeError(label + " is disabled: nsh runs no code from strings (development builds allow it)");
  };
  const replace = (fn, value) => {
    Object.defineProperty(Object.getPrototypeOf(fn), "constructor", {
      value, writable: false, enumerable: false, configurable: false,
    });
  };
  const blocked = deny("the Function constructor");
  blocked.prototype = Function.prototype;
  replace(function () {}, blocked);
  replace(async function () {}, deny("the AsyncFunction constructor"));
  replace(function* () {}, deny("the GeneratorFunction constructor"));
  replace(async function* () {}, deny("the AsyncGeneratorFunction constructor"));
  Object.defineProperty(globalThis, "Function", { value: blocked, writable: false, configurable: false });
  delete globalThis.eval;
  // Assigning a property an object inherits read-only fails (the
  // "override mistake"): `Sub.prototype.constructor = Sub` or
  // `obj.toString = …` would throw once these prototypes are frozen. Their
  // commonly overridden members become accessors whose setter defines the
  // property on the object assigned to, as on an unfrozen prototype (the
  // prototype itself still cannot change).
  const tamed = [
    "constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf",
    "propertyIsEnumerable", "toJSON",
  ];
  const tame = (proto) => {
    for (const name of tamed) {
      const d = Object.getOwnPropertyDescriptor(proto, name);
      if (!d || !("value" in d) || !d.writable) continue;
      const value = d.value;
      Object.defineProperty(proto, name, {
        get() { return value; },
        set(v) {
          if (this === proto) throw new TypeError(`Cannot assign to read only property '${name}'`);
          Object.defineProperty(this, name, { value: v, writable: true, enumerable: true, configurable: true });
        },
        enumerable: d.enumerable,
        configurable: false,
      });
    }
  };
  // Not Error.prototype: `this.name = "MyError"` in a subclass constructor
  // assigns a property it has.
  for (const proto of [
    Object.prototype, Array.prototype, Function.prototype, String.prototype, Number.prototype,
    Boolean.prototype, Symbol.prototype, RegExp.prototype, Promise.prototype, Map.prototype,
    Set.prototype, WeakMap.prototype, WeakSet.prototype, Date.prototype,
    Object.getPrototypeOf(Uint8Array.prototype),
  ]) {
    tame(proto);
    Object.freeze(proto);
  }
})();
"#;

/// Installs the hardening. Runs after the host's own globals and before the
/// bundle.
pub(crate) fn harden(ctx: &Ctx<'_>) -> rquickjs::Result<()> {
    ctx.eval::<(), _>(HARDEN)
}

/// The hardening compiled to bytecode ([`harden_from`]), for runtimes
/// without QuickJS' parser (`bytecode-only`), which cannot compile it.
/// The CLI makes it when it compiles the app, so it always matches the
/// QuickJS the app's bytecode is for ([`crate::BYTECODE_VERSION`]).
pub fn compile_harden() -> Result<Vec<u8>, crate::JsError> {
    let rt = rquickjs::Runtime::new()?;
    let ctx = rquickjs::Context::full(&rt)?;
    ctx.with(|ctx| {
        let raw = ctx.as_raw().as_ptr();
        let source = std::ffi::CString::new(HARDEN).expect("no NUL in the hardening");
        // SAFETY: a live context; the source is NUL-terminated; the
        // function value is freed and the written buffer copied and freed.
        unsafe {
            // As `ctx.eval` runs it: a strict global script.
            let function = qjs::JS_Eval(
                raw,
                source.as_ptr(),
                HARDEN.len() as _,
                c"harden.js".as_ptr(),
                (qjs::JS_EVAL_TYPE_GLOBAL
                    | qjs::JS_EVAL_FLAG_STRICT
                    | qjs::JS_EVAL_FLAG_COMPILE_ONLY) as c_int,
            );
            if qjs::JS_IsException(function) {
                return Err(crate::JsError::from_engine(
                    &ctx,
                    rquickjs::Error::Exception,
                ));
            }
            let mut len = 0;
            let flags = qjs::JS_WRITE_OBJ_BYTECODE
                | qjs::JS_WRITE_OBJ_STRIP_SOURCE
                | qjs::JS_WRITE_OBJ_STRIP_DEBUG;
            let buf = qjs::JS_WriteObject(raw, &mut len, function, flags as c_int);
            qjs::JS_FreeValue(raw, function);
            if buf.is_null() {
                return Err(crate::JsError::from_engine(
                    &ctx,
                    rquickjs::Error::Exception,
                ));
            }
            let bytes = std::slice::from_raw_parts(buf, len as usize).to_vec();
            qjs::js_free(raw, buf.cast());
            Ok(bytes)
        }
    })
}

/// [`harden`] from the bytecode [`compile_harden`] made.
///
/// # Safety
///
/// `bytecode` comes from [`compile_harden`] of the same QuickJS build:
/// QuickJS does not validate it.
pub(crate) unsafe fn harden_from(ctx: &Ctx<'_>, bytecode: &[u8]) -> rquickjs::Result<()> {
    let raw = ctx.as_raw().as_ptr();
    // SAFETY: a live context; trusted bytecode per the contract; the
    // function value is consumed by `JS_EvalFunction`, its result freed.
    unsafe {
        let function = qjs::JS_ReadObject(
            raw,
            bytecode.as_ptr(),
            bytecode.len() as _,
            qjs::JS_READ_OBJ_BYTECODE as c_int,
        );
        if qjs::JS_IsException(function) {
            return Err(rquickjs::Error::Exception);
        }
        let result = qjs::JS_EvalFunction(raw, function);
        if qjs::JS_IsException(result) {
            return Err(rquickjs::Error::Exception);
        }
        qjs::JS_FreeValue(raw, result);
    }
    Ok(())
}