nsh-js 0.6.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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
//! 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 call is charged the time its thread runs ([`charged_now`]): time
//! the system keeps the app frozen or suspended in the background is not
//! the call's.
//!
//! 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,
    rc::Rc,
    sync::{
        Arc,
        atomic::{AtomicBool, Ordering},
    },
};

use nsh_core::js::Limits;
#[cfg(not(unix))]
use nsh_core::time::Instant;
use rquickjs::{Ctx, allocator::Allocator};

/// 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,
    /// Whether a call is running (nested calls share its budget).
    running: Cell<bool>,
    /// When the running call must have returned, on the clock calls are
    /// charged on (`None`: no budget, as an app on its own has none).
    deadline: Rc<Cell<Option<Charged>>>,
    /// The call that overran, until its error is reported.
    tripped: Rc<Cell<Option<Phase>>>,
    /// The running call's kind.
    phase: Rc<Cell<Phase>>,
}

/// A call's clock ([`Budget::run`]), stopped when it drops.
pub(crate) struct Running<'a> {
    budget: &'a Budget,
    started: bool,
}

impl Drop for Running<'_> {
    fn drop(&mut self) {
        self.budget.end(self.started);
    }
}

impl Budget {
    pub(crate) fn new(limits: Limits) -> Self {
        Self {
            limits,
            running: Cell::new(false),
            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), until the guard drops: an unwind
    /// out of the call stops it too.
    pub(crate) fn run(&self, phase: Phase) -> Running<'_> {
        Running {
            budget: self,
            started: self.begin(phase),
        }
    }

    fn begin(&self, phase: Phase) -> bool {
        if self.running.replace(true) {
            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);
        // `Duration::MAX` (no limit) is past any reading: no deadline.
        self.deadline.set(charged_now().checked_add(budget));
        true
    }

    fn end(&self, started: bool) {
        if started {
            self.running.set(false);
            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 charged_now() > d => {
                    tripped.set(Some(phase.get()));
                    true
                }
                _ => false,
            }
        })
    }
}

/// A reading of the clock calls are charged on ([`charged_now`]).
#[cfg(unix)]
type Charged = std::time::Duration;
#[cfg(not(unix))]
type Charged = Instant;

/// Now on the clock calls are charged on: the time the current thread has
/// run (its CPU time) on Linux, Android, macOS and iOS, monotonic time
/// elsewhere. A call is cut off for running too long, not for being stopped:
/// a mobile system freezes an app in the background (Android's app freezers,
/// iOS suspending it) whatever it is doing, and on a monotonic clock a call
/// it froze for more than its budget was cut off on thaw, wherever it was.
/// Nor is the time a thread waits for a CPU on a busy device the call's.
/// Every call is made, and every interrupt check runs, on the VM's thread.
#[cfg(unix)]
fn charged_now() -> Charged {
    let mut now = libc::timespec {
        tv_sec: 0,
        tv_nsec: 0,
    };
    // SAFETY: `now` is a valid `timespec` for the call to fill.
    let read = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut now) };
    // Every unix nsh runs on keeps it; were one not to, no call would be
    // cut off there.
    debug_assert_eq!(read, 0, "the thread's CPU-time clock");
    Charged::new(now.tv_sec as u64, now.tv_nsec as u32)
}

/// Now on the clock calls are charged on: monotonic time on Windows (whose
/// desktop apps are not frozen in the background) and in WebAssembly.
#[cfg(not(unix))]
fn charged_now() -> Charged {
    Instant::now()
}

/// 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(cx: &Ctx<'_>) -> rquickjs::Result<()> {
    cx.eval::<(), _>(HARDEN)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn an_unwind_out_of_a_call_stops_its_clock() {
        let budget = Budget::new(Limits::default());
        let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let _running = budget.run(Phase::Call);
            panic!("out of the call");
        }));
        assert!(unwound.is_err());
        // No clock left running: the next call starts its own.
        assert!(budget.run(Phase::Call).started);
    }

    /// A thread that does not run (the app frozen or suspended in the
    /// background; here, asleep) spends none of its call's budget; running,
    /// it does.
    #[cfg(unix)]
    #[test]
    fn a_call_is_charged_the_time_it_runs_not_the_time_it_is_stopped() {
        use std::time::{Duration, Instant};

        let budget = Budget::new(Limits {
            call_budget: Duration::from_millis(50),
            ..Limits::default()
        });
        let mut interrupt = budget.interrupt_handler(None);
        let _running = budget.run(Phase::Call);
        std::thread::sleep(Duration::from_millis(200));
        assert!(!interrupt(), "cut off for time it did not run");
        let spinning = Instant::now();
        let mut tripped = false;
        while spinning.elapsed() < Duration::from_secs(5) {
            if interrupt() {
                tripped = true;
                break;
            }
        }
        assert!(tripped, "never cut off while it ran");
        assert!(budget.take_trip().unwrap().contains("budget of 50 ms"));
    }

    #[test]
    fn calls_without_a_budget_are_never_interrupted() {
        let budget = Budget::new(Limits::standalone());
        let mut interrupt = budget.interrupt_handler(None);
        let outer = budget.run(Phase::Load);
        assert!(outer.started);
        assert!(budget.deadline.get().is_none());
        // Nested calls still share the outer one's (absent) budget.
        assert!(!budget.run(Phase::Call).started);
        assert!(!interrupt());
        drop(outer);
        assert!(budget.run(Phase::Call).started);
        assert!(budget.take_trip().is_none());
    }
}