quickjs/memory.rs
1//! The memory report behind `qjs -d` / `--dump` and `JS_ComputeMemoryUsage`.
2//!
3//! # Why this is a walk and not a set of counters
4//!
5//! Tracking every number the reference tracks would mean a counter incremented at each of
6//! the two hundred places that define a property or push an element, and one forgotten site
7//! makes the report quietly wrong — the exact failure mode `Heap::measure_used` avoids for
8//! the memory limit (see its comment). So the numbers here are **measured**: walk the live
9//! boxes once, downcast, and add up. `JS_ComputeMemoryUsage` in the reference is also a walk
10//! over its object lists, so this is the same design rather than a substitute for it.
11//!
12//! # What is real and what is zero
13//!
14//! | row | how |
15//! |---|---|
16//! | `memory allocated` | the heap's live registry; headers plus payload |
17//! | `strings` | every live [`JsString`], by byte length |
18//! | `objects` | every live [`JsObject`] |
19//! | ` properties` | sum of `props.len()` over those objects, by slot capacity |
20//! | ` shapes` | **always 0** — this engine has no hidden-class sharing |
21//! | `bytecode functions`, ` bytecode` | live [`CompiledCode`], by instruction bytes |
22//! | `C functions` | callables that are native or host closures |
23//! | `arrays`, ` fast arrays`, ` elements` | `ObjectKind::Array` and its element vector |
24//! | `binary objects` | `ArrayBuffer`, `TypedArray`, `DataView` |
25//! | `atoms` | **not printed** — property keys are ordinary strings here |
26//!
27//! A zero that means "not modelled" is labelled as such in the rendered report, because the
28//! one thing worse than a missing number is a wrong one that looks measured
29//! (`docs/test262-status.md` §4.37).
30
31use std::any::Any;
32
33use crate::Heap;
34use crate::object::{Callable, CompiledCode, JsObject, ObjectKind, Property, PropertyKey};
35use crate::value::{JsString, Value};
36
37/// What one runtime occupies, in the reference's `JSMemoryUsage` field names.
38///
39/// The names are the C header's on purpose: `quickjs-capi` copies this into a
40/// `JSMemoryUsage` field for field, and a C program reading `s->prop_count` has to get the
41/// number this measured.
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
43pub struct MemoryUsage {
44 /// Live heap blocks.
45 pub malloc_count: i64,
46 /// Bytes those blocks hold: headers plus payloads.
47 pub malloc_size: i64,
48 /// The reference's `memory used` count. Equal to [`MemoryUsage::malloc_count`], and
49 /// filled only so a C host reading the field gets an answer: the row is not printed,
50 /// because the reference's version is this number minus an allocator overhead this
51 /// engine cannot see, and two rows with the same value under two names is noise.
52 pub memory_used_count: i64,
53 /// The reference's `memory used` bytes. See [`MemoryUsage::memory_used_count`].
54 pub memory_used_size: i64,
55 /// `--memory-limit`, or **-1** when unlimited.
56 ///
57 /// -1 rather than 0 because 0 is a legitimate limit meaning "no memory at all" — the
58 /// reference's field is a `size_t` initialised to `-1` for exactly this reason (see
59 /// `docs/m15-plan.md`'s note that `JS_SetMemoryLimit(rt, 0)` is not "cancel the limit").
60 /// Reinterpreting 0 as "unlimited" in the renderer would make the one limit that refuses
61 /// every allocation print as no limit at all.
62 pub malloc_limit: i64,
63 /// Strings.
64 pub str_count: i64,
65 /// Their bytes.
66 pub str_size: i64,
67 /// Objects.
68 pub obj_count: i64,
69 /// Their bytes.
70 pub obj_size: i64,
71 /// Own properties, over all objects.
72 pub prop_count: i64,
73 /// Their slot bytes.
74 pub prop_size: i64,
75 /// Hidden classes. Always 0: see the module docs.
76 pub shape_count: i64,
77 /// Their bytes. Always 0.
78 pub shape_size: i64,
79 /// Functions compiled from JavaScript.
80 pub js_func_count: i64,
81 /// Their allocations.
82 pub js_func_size: i64,
83 /// Instruction bytes.
84 pub js_func_code_size: i64,
85 /// Functions carrying a pc-to-line table.
86 pub js_func_pc2line_count: i64,
87 /// Bytes of those tables.
88 pub js_func_pc2line_size: i64,
89 /// Builtin and host functions.
90 pub c_func_count: i64,
91 /// Array objects.
92 pub array_count: i64,
93 /// Arrays whose elements are a dense vector.
94 pub fast_array_count: i64,
95 /// Elements in those.
96 pub fast_array_elements: i64,
97 /// `ArrayBuffer`, `TypedArray`, `DataView`.
98 pub binary_object_count: i64,
99 /// Their bytes.
100 pub binary_object_size: i64,
101}
102
103/// The per-class census that the reference prints between the header and the table.
104///
105/// Ours is keyed by this engine's own [`ObjectKind`] vocabulary, not by class ids, so the
106/// names are different from the reference's on purpose: the counters would not line up
107/// anyway, and printing `12 Function` next to the reference's `117 12 Function` would invite
108/// exactly the wrong comparison.
109#[derive(Debug, Clone, Default, PartialEq, Eq)]
110pub struct ClassCensus {
111 entries: Vec<(String, usize)>,
112}
113
114impl ClassCensus {
115 /// `(name, count)` pairs, biggest first.
116 pub fn entries(&self) -> &[(String, usize)] {
117 &self.entries
118 }
119}
120
121fn bump(census: &mut ClassCensus, name: &str) {
122 match census.entries.iter_mut().find(|(key, _)| key == name) {
123 Some((_, count)) => *count += 1,
124 None => census.entries.push((name.to_string(), 1)),
125 }
126}
127
128fn width_of<T>() -> usize {
129 std::mem::size_of::<T>()
130}
131
132/// Measure `heap`.
133///
134/// Takes the heap rather than an interpreter, because `JS_ComputeMemoryUsage` is handed a
135/// runtime and nothing else — and because the walk needs nothing an interpreter has.
136pub fn compute(heap: &Heap) -> (MemoryUsage, ClassCensus) {
137 let mut usage = MemoryUsage {
138 malloc_limit: heap
139 .memory_limit()
140 .map_or(-1, |limit| i64::try_from(limit).unwrap_or(i64::MAX)),
141 ..MemoryUsage::default()
142 };
143 let mut census = ClassCensus::default();
144 // The property tables, totalled separately because the heap's own accounting excludes
145 // them on purpose (see `impl Trace for JsObject`: it reports no payload for the property
146 // vector, so that a growth nothing charges for cannot be subtracted twice at free time).
147 // They are real bytes all the same, and the reference's `malloc_size` counts them
148 // (`js_malloc` sees every allocation), so the report adds them back — otherwise
149 // `properties` would be a row larger than the total it is part of, which is the kind of
150 // arithmetic that makes a reader stop believing the whole table.
151 let mut prop_bytes = 0i64;
152
153 heap.for_each_live(&mut |value: &dyn Any| {
154 usage.malloc_count += 1;
155 if let Some(object) = value.downcast_ref::<JsObject>() {
156 usage.obj_count += 1;
157 usage.obj_size += width_of::<JsObject>() as i64;
158 usage.prop_count += object.props_len() as i64;
159 // A property slot is a key and a `Property`; capacity rather than length,
160 // because that is what the allocator is holding.
161 let slots = (object.props_capacity() * width_of::<(PropertyKey, Property)>()) as i64;
162 usage.prop_size += slots;
163 prop_bytes += slots;
164 classify(object, &mut usage, &mut census);
165 } else if let Some(text) = value.downcast_ref::<JsString>() {
166 usage.str_count += 1;
167 usage.str_size += (width_of::<JsString>() + text.byte_len()) as i64;
168 } else if let Some(code) = value.downcast_ref::<CompiledCode>() {
169 usage.js_func_count += 1;
170 usage.js_func_size += width_of::<CompiledCode>() as i64;
171 usage.js_func_code_size += code.code.code.len() as i64;
172 if !code.code.positions.is_empty() {
173 usage.js_func_pc2line_count += 1;
174 usage.js_func_pc2line_size += (code.code.positions.len()
175 * width_of::<js_compile::bytecode::LineCol>())
176 as i64;
177 }
178 }
179 // Everything else — captured bindings, symbols, closure environments — is a block and
180 // nothing more. It is counted in `malloc_count`/`malloc_size` above and appears in no
181 // row, which is exactly what "this engine has no category for it" should look like.
182 });
183
184 // `allocated_bytes` already includes each box's header (`Heap::register` adds
185 // `Header::size`), so adding the property tables back gives the whole footprint and
186 // double counts nothing.
187 usage.malloc_size = i64::try_from(heap.allocated_bytes()).unwrap_or(i64::MAX) + prop_bytes;
188 usage.memory_used_count = usage.malloc_count;
189 usage.memory_used_size = usage.malloc_size;
190 census
191 .entries
192 .sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
193 (usage, census)
194}
195
196/// Classify one object: arrays, elements, functions and binary objects.
197fn classify(object: &JsObject, usage: &mut MemoryUsage, census: &mut ClassCensus) {
198 object.with_kind(|kind| {
199 let name = match kind {
200 // An array is "fast" here exactly when it has elements at all: this engine has
201 // no dictionary representation, only a dense prefix plus a logical length (see
202 // `ObjectKind::Array`), so the two rows differ only by emptiness. They are both
203 // printed because `elements` is where the memory actually is, and a reader
204 // comparing against the reference needs to see that the row was considered.
205 ObjectKind::Array { elements, .. } => {
206 usage.array_count += 1;
207 if !elements.is_empty() {
208 usage.fast_array_count += 1;
209 usage.fast_array_elements += elements.len() as i64;
210 }
211 "Array"
212 }
213 // The reference's own table separates these two, and the separation is the
214 // interesting part: 117 native `Function`s next to one bytecode function says
215 // something completely different from 118 of either.
216 ObjectKind::Function(callable) => match callable {
217 Callable::Bytecode { .. } => "Function (bytecode)",
218 Callable::Bound { .. } => "Function (bound)",
219 Callable::Revoker(_) | Callable::ModuleBinding { .. } => "Function (shim)",
220 _ => {
221 usage.c_func_count += 1;
222 "Function (native)"
223 }
224 },
225 ObjectKind::ArrayBuffer(storage) => {
226 usage.binary_object_count += 1;
227 // `try_borrow`: a report is not worth a panic, and a buffer borrowed by the
228 // engine right now reports as empty rather than aborting the dump.
229 usage.binary_object_size += storage
230 .try_borrow()
231 .map_or(0, |storage| storage.bytes.len())
232 as i64;
233 "ArrayBuffer"
234 }
235 // A view owns nothing: its bytes belong to the buffer, which is its own object
236 // and its own row. Counting them twice is how a memory report loses trust.
237 ObjectKind::TypedArray { .. } => {
238 usage.binary_object_count += 1;
239 "TypedArray"
240 }
241 ObjectKind::DataView { .. } => {
242 usage.binary_object_count += 1;
243 "DataView"
244 }
245 other => other.variant_name(),
246 };
247 bump(census, name);
248 });
249}
250
251/// One context's report, as `qjs -d` prints it.
252pub fn dump(usage: &MemoryUsage, census: &ClassCensus) -> String {
253 use std::fmt::Write;
254 let mut out = String::new();
255 let version = crate::COMPAT_VERSION;
256 let bits = std::mem::size_of::<usize>() * 8;
257 let limit = usage.malloc_limit;
258 let _ = writeln!(
259 out,
260 "QuickJS memory usage -- {version} version, {bits}-bit, malloc limit: {limit}\n"
261 );
262
263 if !census.entries().is_empty() {
264 let _ = writeln!(out, "JSObject classes");
265 for (name, count) in census.entries() {
266 let _ = writeln!(out, " {count:5} {name}");
267 }
268 let _ = writeln!(out);
269 }
270
271 let _ = writeln!(out, "{:<20} {:>8} {:>8}", "NAME", "COUNT", "SIZE");
272 let row = |out: &mut String, name: &str, count: i64, size: i64, note: &str| {
273 let _ = writeln!(out, "{name:<20} {count:>8} {size:>8}{note}");
274 };
275 let per = |size: i64, count: i64, unit: &str| {
276 if count > 0 {
277 format!(" ({:.1} per {unit})", size as f64 / count as f64)
278 } else {
279 String::new()
280 }
281 };
282
283 if usage.malloc_count > 0 {
284 // The reference's own first row. Its `memory used` row is the same number minus an
285 // allocator overhead this engine cannot see, so it is not printed rather than printed
286 // twice under two names.
287 row(
288 &mut out,
289 "memory allocated",
290 usage.malloc_count,
291 usage.malloc_size,
292 &per(usage.malloc_size, usage.malloc_count, "block"),
293 );
294 }
295 if usage.str_count > 0 {
296 row(
297 &mut out,
298 "strings",
299 usage.str_count,
300 usage.str_size,
301 &per(usage.str_size, usage.str_count, "string"),
302 );
303 }
304 if usage.obj_count > 0 {
305 row(
306 &mut out,
307 "objects",
308 usage.obj_count,
309 usage.obj_size,
310 &per(usage.obj_size, usage.obj_count, "object"),
311 );
312 row(
313 &mut out,
314 " properties",
315 usage.prop_count,
316 usage.prop_size,
317 &per(usage.prop_count, usage.obj_count, "object"),
318 );
319 // Printed even at zero, because the reference's table has the row and a reader
320 // comparing the two reports needs to see that it was considered, not forgotten.
321 row(&mut out, " shapes", 0, 0, " (not modelled)");
322 }
323 if usage.js_func_count > 0 {
324 row(
325 &mut out,
326 "bytecode functions",
327 usage.js_func_count,
328 usage.js_func_size,
329 "",
330 );
331 row(
332 &mut out,
333 " bytecode",
334 usage.js_func_count,
335 usage.js_func_code_size,
336 &per(usage.js_func_code_size, usage.js_func_count, "function"),
337 );
338 if usage.js_func_pc2line_count > 0 {
339 row(
340 &mut out,
341 " pc2line",
342 usage.js_func_pc2line_count,
343 usage.js_func_pc2line_size,
344 &per(
345 usage.js_func_pc2line_size,
346 usage.js_func_pc2line_count,
347 "function",
348 ),
349 );
350 }
351 }
352 if usage.c_func_count > 0 {
353 row(&mut out, "C functions", usage.c_func_count, 0, "");
354 }
355 if usage.array_count > 0 {
356 row(&mut out, "arrays", usage.array_count, 0, "");
357 if usage.fast_array_count > 0 {
358 row(&mut out, " fast arrays", usage.fast_array_count, 0, "");
359 row(
360 &mut out,
361 " elements",
362 usage.fast_array_elements,
363 usage.fast_array_elements * width_of::<Value>() as i64,
364 &per(
365 usage.fast_array_elements,
366 usage.fast_array_count,
367 "fast array",
368 ),
369 );
370 }
371 }
372 if usage.binary_object_count > 0 {
373 row(
374 &mut out,
375 "binary objects",
376 usage.binary_object_count,
377 usage.binary_object_size,
378 "",
379 );
380 }
381 // The reference's rows that this engine does not have. Named rather than omitted: a
382 // reader diffing the two reports has to be able to tell "zero" from "absent", and the
383 // whole point of `scripts/host-gaps.py` is that a gap nobody writes down stops being
384 // visible (docs/test262-status.md §4.37).
385 let _ = writeln!(
386 out,
387 "\nnot accounted for by this engine:\n \
388 memory used (allocator overhead), atoms (property keys are ordinary strings),\n \
389 the JSRuntime/JSContext/JSObject/JSString sizeof rows (Rust types, not C structs)"
390 );
391 out
392}