use std::any::Any;
use crate::Heap;
use crate::object::{Callable, CompiledCode, JsObject, ObjectKind, Property, PropertyKey};
use crate::value::{JsString, Value};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct MemoryUsage {
pub malloc_count: i64,
pub malloc_size: i64,
pub memory_used_count: i64,
pub memory_used_size: i64,
pub malloc_limit: i64,
pub str_count: i64,
pub str_size: i64,
pub obj_count: i64,
pub obj_size: i64,
pub prop_count: i64,
pub prop_size: i64,
pub shape_count: i64,
pub shape_size: i64,
pub js_func_count: i64,
pub js_func_size: i64,
pub js_func_code_size: i64,
pub js_func_pc2line_count: i64,
pub js_func_pc2line_size: i64,
pub c_func_count: i64,
pub array_count: i64,
pub fast_array_count: i64,
pub fast_array_elements: i64,
pub binary_object_count: i64,
pub binary_object_size: i64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ClassCensus {
entries: Vec<(String, usize)>,
}
impl ClassCensus {
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>()
}
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();
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;
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;
}
}
});
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)
}
fn classify(object: &JsObject, usage: &mut MemoryUsage, census: &mut ClassCensus) {
object.with_kind(|kind| {
let name = match kind {
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"
}
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;
usage.binary_object_size += storage
.try_borrow()
.map_or(0, |storage| storage.bytes.len())
as i64;
"ArrayBuffer"
}
ObjectKind::TypedArray { .. } => {
usage.binary_object_count += 1;
"TypedArray"
}
ObjectKind::DataView { .. } => {
usage.binary_object_count += 1;
"DataView"
}
other => other.variant_name(),
};
bump(census, name);
});
}
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 {
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"),
);
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,
"",
);
}
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
}