quickjs-pure 0.14.2

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
Documentation
//! The memory report behind `qjs -d` / `--dump` and `JS_ComputeMemoryUsage`.
//!
//! # Why this is a walk and not a set of counters
//!
//! Tracking every number the reference tracks would mean a counter incremented at each of
//! the two hundred places that define a property or push an element, and one forgotten site
//! makes the report quietly wrong — the exact failure mode `Heap::measure_used` avoids for
//! the memory limit (see its comment). So the numbers here are **measured**: walk the live
//! boxes once, downcast, and add up. `JS_ComputeMemoryUsage` in the reference is also a walk
//! over its object lists, so this is the same design rather than a substitute for it.
//!
//! # What is real and what is zero
//!
//! | row | how |
//! |---|---|
//! | `memory allocated` | the heap's live registry; headers plus payload |
//! | `strings` | every live [`JsString`], by byte length |
//! | `objects` | every live [`JsObject`] |
//! | `  properties` | sum of `props.len()` over those objects, by slot capacity |
//! | `  shapes` | **always 0** — this engine has no hidden-class sharing |
//! | `bytecode functions`, `  bytecode` | live [`CompiledCode`], by instruction bytes |
//! | `C functions` | callables that are native or host closures |
//! | `arrays`, `  fast arrays`, `  elements` | `ObjectKind::Array` and its element vector |
//! | `binary objects` | `ArrayBuffer`, `TypedArray`, `DataView` |
//! | `atoms` | **not printed** — property keys are ordinary strings here |
//!
//! A zero that means "not modelled" is labelled as such in the rendered report, because the
//! one thing worse than a missing number is a wrong one that looks measured
//! (`docs/test262-status.md` §4.37).

use std::any::Any;

use crate::Heap;
use crate::object::{Callable, CompiledCode, JsObject, ObjectKind, Property, PropertyKey};
use crate::value::{JsString, Value};

/// What one runtime occupies, in the reference's `JSMemoryUsage` field names.
///
/// The names are the C header's on purpose: `quickjs-capi` copies this into a
/// `JSMemoryUsage` field for field, and a C program reading `s->prop_count` has to get the
/// number this measured.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MemoryUsage {
    /// Live heap blocks.
    pub malloc_count: i64,
    /// Bytes those blocks hold: headers plus payloads.
    pub malloc_size: i64,
    /// The reference's `memory used` count. Equal to [`MemoryUsage::malloc_count`], and
    /// filled only so a C host reading the field gets an answer: the row is not printed,
    /// because the reference's version is this number minus an allocator overhead this
    /// engine cannot see, and two rows with the same value under two names is noise.
    pub memory_used_count: i64,
    /// The reference's `memory used` bytes. See [`MemoryUsage::memory_used_count`].
    pub memory_used_size: i64,
    /// `--memory-limit`, or **-1** when unlimited.
    ///
    /// -1 rather than 0 because 0 is a legitimate limit meaning "no memory at all" — the
    /// reference's field is a `size_t` initialised to `-1` for exactly this reason (see
    /// `docs/m15-plan.md`'s note that `JS_SetMemoryLimit(rt, 0)` is not "cancel the limit").
    /// Reinterpreting 0 as "unlimited" in the renderer would make the one limit that refuses
    /// every allocation print as no limit at all.
    pub malloc_limit: i64,
    /// Strings.
    pub str_count: i64,
    /// Their bytes.
    pub str_size: i64,
    /// Objects.
    pub obj_count: i64,
    /// Their bytes.
    pub obj_size: i64,
    /// Own properties, over all objects.
    pub prop_count: i64,
    /// Their slot bytes.
    pub prop_size: i64,
    /// Hidden classes. Always 0: see the module docs.
    pub shape_count: i64,
    /// Their bytes. Always 0.
    pub shape_size: i64,
    /// Functions compiled from JavaScript.
    pub js_func_count: i64,
    /// Their allocations.
    pub js_func_size: i64,
    /// Instruction bytes.
    pub js_func_code_size: i64,
    /// Functions carrying a pc-to-line table.
    pub js_func_pc2line_count: i64,
    /// Bytes of those tables.
    pub js_func_pc2line_size: i64,
    /// Builtin and host functions.
    pub c_func_count: i64,
    /// Array objects.
    pub array_count: i64,
    /// Arrays whose elements are a dense vector.
    pub fast_array_count: i64,
    /// Elements in those.
    pub fast_array_elements: i64,
    /// `ArrayBuffer`, `TypedArray`, `DataView`.
    pub binary_object_count: i64,
    /// Their bytes.
    pub binary_object_size: i64,
}

/// The per-class census that the reference prints between the header and the table.
///
/// Ours is keyed by this engine's own [`ObjectKind`] vocabulary, not by class ids, so the
/// names are different from the reference's on purpose: the counters would not line up
/// anyway, and printing `12 Function` next to the reference's `117 12 Function` would invite
/// exactly the wrong comparison.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ClassCensus {
    entries: Vec<(String, usize)>,
}

impl ClassCensus {
    /// `(name, count)` pairs, biggest first.
    pub fn entries(&self) -> &[(String, usize)] {
        &self.entries
    }
}

fn bump(census: &mut ClassCensus, name: &str) {
    match census.entries.iter_mut().find(|(key, _)| key == name) {
        Some((_, count)) => *count += 1,
        None => census.entries.push((name.to_string(), 1)),
    }
}

fn width_of<T>() -> usize {
    std::mem::size_of::<T>()
}

/// Measure `heap`.
///
/// Takes the heap rather than an interpreter, because `JS_ComputeMemoryUsage` is handed a
/// runtime and nothing else — and because the walk needs nothing an interpreter has.
pub fn compute(heap: &Heap) -> (MemoryUsage, ClassCensus) {
    let mut usage = MemoryUsage {
        malloc_limit: heap
            .memory_limit()
            .map_or(-1, |limit| i64::try_from(limit).unwrap_or(i64::MAX)),
        ..MemoryUsage::default()
    };
    let mut census = ClassCensus::default();
    // The property tables, totalled separately because the heap's own accounting excludes
    // them on purpose (see `impl Trace for JsObject`: it reports no payload for the property
    // vector, so that a growth nothing charges for cannot be subtracted twice at free time).
    // They are real bytes all the same, and the reference's `malloc_size` counts them
    // (`js_malloc` sees every allocation), so the report adds them back — otherwise
    // `properties` would be a row larger than the total it is part of, which is the kind of
    // arithmetic that makes a reader stop believing the whole table.
    let mut prop_bytes = 0i64;

    heap.for_each_live(&mut |value: &dyn Any| {
        usage.malloc_count += 1;
        if let Some(object) = value.downcast_ref::<JsObject>() {
            usage.obj_count += 1;
            usage.obj_size += width_of::<JsObject>() as i64;
            usage.prop_count += object.props_len() as i64;
            // A property slot is a key and a `Property`; capacity rather than length,
            // because that is what the allocator is holding.
            let slots = (object.props_capacity() * width_of::<(PropertyKey, Property)>()) as i64;
            usage.prop_size += slots;
            prop_bytes += slots;
            classify(object, &mut usage, &mut census);
        } else if let Some(text) = value.downcast_ref::<JsString>() {
            usage.str_count += 1;
            usage.str_size += (width_of::<JsString>() + text.byte_len()) as i64;
        } else if let Some(code) = value.downcast_ref::<CompiledCode>() {
            usage.js_func_count += 1;
            usage.js_func_size += width_of::<CompiledCode>() as i64;
            usage.js_func_code_size += code.code.code.len() as i64;
            if !code.code.positions.is_empty() {
                usage.js_func_pc2line_count += 1;
                usage.js_func_pc2line_size += (code.code.positions.len()
                    * width_of::<js_compile::bytecode::LineCol>())
                    as i64;
            }
        }
        // Everything else — captured bindings, symbols, closure environments — is a block and
        // nothing more. It is counted in `malloc_count`/`malloc_size` above and appears in no
        // row, which is exactly what "this engine has no category for it" should look like.
    });

    // `allocated_bytes` already includes each box's header (`Heap::register` adds
    // `Header::size`), so adding the property tables back gives the whole footprint and
    // double counts nothing.
    usage.malloc_size = i64::try_from(heap.allocated_bytes()).unwrap_or(i64::MAX) + prop_bytes;
    usage.memory_used_count = usage.malloc_count;
    usage.memory_used_size = usage.malloc_size;
    census
        .entries
        .sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    (usage, census)
}

/// Classify one object: arrays, elements, functions and binary objects.
fn classify(object: &JsObject, usage: &mut MemoryUsage, census: &mut ClassCensus) {
    object.with_kind(|kind| {
        let name = match kind {
            // An array is "fast" here exactly when it has elements at all: this engine has
            // no dictionary representation, only a dense prefix plus a logical length (see
            // `ObjectKind::Array`), so the two rows differ only by emptiness. They are both
            // printed because `elements` is where the memory actually is, and a reader
            // comparing against the reference needs to see that the row was considered.
            ObjectKind::Array { elements, .. } => {
                usage.array_count += 1;
                if !elements.is_empty() {
                    usage.fast_array_count += 1;
                    usage.fast_array_elements += elements.len() as i64;
                }
                "Array"
            }
            // The reference's own table separates these two, and the separation is the
            // interesting part: 117 native `Function`s next to one bytecode function says
            // something completely different from 118 of either.
            ObjectKind::Function(callable) => match callable {
                Callable::Bytecode { .. } => "Function (bytecode)",
                Callable::Bound { .. } => "Function (bound)",
                Callable::Revoker(_) | Callable::ModuleBinding { .. } => "Function (shim)",
                _ => {
                    usage.c_func_count += 1;
                    "Function (native)"
                }
            },
            ObjectKind::ArrayBuffer(storage) => {
                usage.binary_object_count += 1;
                // `try_borrow`: a report is not worth a panic, and a buffer borrowed by the
                // engine right now reports as empty rather than aborting the dump.
                usage.binary_object_size += storage
                    .try_borrow()
                    .map_or(0, |storage| storage.bytes.len())
                    as i64;
                "ArrayBuffer"
            }
            // A view owns nothing: its bytes belong to the buffer, which is its own object
            // and its own row. Counting them twice is how a memory report loses trust.
            ObjectKind::TypedArray { .. } => {
                usage.binary_object_count += 1;
                "TypedArray"
            }
            ObjectKind::DataView { .. } => {
                usage.binary_object_count += 1;
                "DataView"
            }
            other => other.variant_name(),
        };
        bump(census, name);
    });
}

/// One context's report, as `qjs -d` prints it.
pub fn dump(usage: &MemoryUsage, census: &ClassCensus) -> String {
    use std::fmt::Write;
    let mut out = String::new();
    let version = crate::COMPAT_VERSION;
    let bits = std::mem::size_of::<usize>() * 8;
    let limit = usage.malloc_limit;
    let _ = writeln!(
        out,
        "QuickJS memory usage -- {version} version, {bits}-bit, malloc limit: {limit}\n"
    );

    if !census.entries().is_empty() {
        let _ = writeln!(out, "JSObject classes");
        for (name, count) in census.entries() {
            let _ = writeln!(out, "  {count:5}  {name}");
        }
        let _ = writeln!(out);
    }

    let _ = writeln!(out, "{:<20} {:>8} {:>8}", "NAME", "COUNT", "SIZE");
    let row = |out: &mut String, name: &str, count: i64, size: i64, note: &str| {
        let _ = writeln!(out, "{name:<20} {count:>8} {size:>8}{note}");
    };
    let per = |size: i64, count: i64, unit: &str| {
        if count > 0 {
            format!("  ({:.1} per {unit})", size as f64 / count as f64)
        } else {
            String::new()
        }
    };

    if usage.malloc_count > 0 {
        // The reference's own first row. Its `memory used` row is the same number minus an
        // allocator overhead this engine cannot see, so it is not printed rather than printed
        // twice under two names.
        row(
            &mut out,
            "memory allocated",
            usage.malloc_count,
            usage.malloc_size,
            &per(usage.malloc_size, usage.malloc_count, "block"),
        );
    }
    if usage.str_count > 0 {
        row(
            &mut out,
            "strings",
            usage.str_count,
            usage.str_size,
            &per(usage.str_size, usage.str_count, "string"),
        );
    }
    if usage.obj_count > 0 {
        row(
            &mut out,
            "objects",
            usage.obj_count,
            usage.obj_size,
            &per(usage.obj_size, usage.obj_count, "object"),
        );
        row(
            &mut out,
            "  properties",
            usage.prop_count,
            usage.prop_size,
            &per(usage.prop_count, usage.obj_count, "object"),
        );
        // Printed even at zero, because the reference's table has the row and a reader
        // comparing the two reports needs to see that it was considered, not forgotten.
        row(&mut out, "  shapes", 0, 0, "  (not modelled)");
    }
    if usage.js_func_count > 0 {
        row(
            &mut out,
            "bytecode functions",
            usage.js_func_count,
            usage.js_func_size,
            "",
        );
        row(
            &mut out,
            "  bytecode",
            usage.js_func_count,
            usage.js_func_code_size,
            &per(usage.js_func_code_size, usage.js_func_count, "function"),
        );
        if usage.js_func_pc2line_count > 0 {
            row(
                &mut out,
                "  pc2line",
                usage.js_func_pc2line_count,
                usage.js_func_pc2line_size,
                &per(
                    usage.js_func_pc2line_size,
                    usage.js_func_pc2line_count,
                    "function",
                ),
            );
        }
    }
    if usage.c_func_count > 0 {
        row(&mut out, "C functions", usage.c_func_count, 0, "");
    }
    if usage.array_count > 0 {
        row(&mut out, "arrays", usage.array_count, 0, "");
        if usage.fast_array_count > 0 {
            row(&mut out, "  fast arrays", usage.fast_array_count, 0, "");
            row(
                &mut out,
                "  elements",
                usage.fast_array_elements,
                usage.fast_array_elements * width_of::<Value>() as i64,
                &per(
                    usage.fast_array_elements,
                    usage.fast_array_count,
                    "fast array",
                ),
            );
        }
    }
    if usage.binary_object_count > 0 {
        row(
            &mut out,
            "binary objects",
            usage.binary_object_count,
            usage.binary_object_size,
            "",
        );
    }
    // The reference's rows that this engine does not have. Named rather than omitted: a
    // reader diffing the two reports has to be able to tell "zero" from "absent", and the
    // whole point of `scripts/host-gaps.py` is that a gap nobody writes down stops being
    // visible (docs/test262-status.md §4.37).
    let _ = writeln!(
        out,
        "\nnot accounted for by this engine:\n  \
         memory used (allocator overhead), atoms (property keys are ordinary strings),\n  \
         the JSRuntime/JSContext/JSObject/JSString sizeof rows (Rust types, not C structs)"
    );
    out
}