1use alloc::rc::Rc;
29use alloc::vec::Vec;
30use core::cell::RefCell;
31
32use super::interp::Scope;
33use super::value::{GenCompletion, GenState, Obj, ObjKind, PromiseState, Value};
34use alloc::collections::BTreeMap;
35
36use core::sync::atomic::{AtomicUsize, Ordering};
37
38pub use super::gc_policy::{calc_next_interval_pure, should_collect_pure, MIN_INTERVAL};
39
40static MADE: AtomicUsize = AtomicUsize::new(0);
42static NEXT_AT: AtomicUsize = AtomicUsize::new(MIN_INTERVAL);
44
45pub fn calc_next_interval(live: usize) -> usize {
47 let (used, total) = crate::os_lib::platform::heap_stats();
48 calc_next_interval_pure(live, used, total)
49}
50
51pub fn should_collect() -> bool {
55 let made = MADE.load(Ordering::Relaxed);
56 let next_at = NEXT_AT.load(Ordering::Relaxed);
57 let (used, total) = crate::os_lib::platform::heap_stats();
58 should_collect_pure(made, next_at, used, total)
59}
60
61pub fn maybe_collect() -> Option<GcStats> {
63 if !should_collect() {
64 return None;
65 }
66 let st = collect(true);
67 let live = (st.objs + st.scopes).saturating_sub(st.garbage_objs + st.garbage_scopes);
68 let next = calc_next_interval(live);
69 NEXT_AT.store(next, Ordering::Relaxed);
70 Some(st)
71}
72
73pub const NO_SLOT: u32 = u32::MAX;
75
76struct Registry {
79 objs: ChunkVec<usize>,
80 obj_free: Vec<u32>,
81 scopes: ChunkVec<usize>,
82 scope_free: Vec<u32>,
83}
84
85static REGISTRY: crate::os_lib::platform::Locked<Registry> = crate::os_lib::platform::Locked::new(Registry {
88 objs: ChunkVec::new(),
89 obj_free: Vec::new(),
90 scopes: ChunkVec::new(),
91 scope_free: Vec::new(),
92});
93
94pub fn force_release_lock(cid: i16) {
96 unsafe { REGISTRY.force_release_if_core(cid) }
98}
99
100fn put(list: &mut ChunkVec<usize>, free: &mut Vec<u32>, p: usize) -> u32 {
101 if let Some(i) = free.pop() {
102 if let Some(e) = list.get_mut(i as usize) {
103 *e = p;
104 return i;
105 }
106 }
107 list.push(p);
108 (list.len() - 1) as u32
109}
110
111pub fn track_obj(rc: Rc<RefCell<Obj>>) -> Rc<RefCell<Obj>> {
113 MADE.fetch_add(1, Ordering::Relaxed);
114 let p = Rc::as_ptr(&rc) as usize;
115 let slot = {
116 let mut r = REGISTRY.lock();
117 let Registry { objs, obj_free, .. } = &mut *r;
118 put(objs, obj_free, p)
119 };
120 if let Ok(mut b) = rc.try_borrow_mut() {
121 b.gc_slot = slot;
122 }
123 rc
124}
125
126pub fn track_scope(rc: Rc<RefCell<Scope>>) -> Rc<RefCell<Scope>> {
128 MADE.fetch_add(1, Ordering::Relaxed);
129 let p = Rc::as_ptr(&rc) as usize;
130 let slot = {
131 let mut r = REGISTRY.lock();
132 let Registry { scopes, scope_free, .. } = &mut *r;
133 put(scopes, scope_free, p)
134 };
135 if let Ok(mut b) = rc.try_borrow_mut() {
136 b.gc_slot = slot;
137 }
138 rc
139}
140
141pub fn untrack_obj(slot: u32) {
143 if slot == NO_SLOT {
144 return;
145 }
146 let mut r = REGISTRY.lock();
147 if let Some(e) = r.objs.get_mut(slot as usize) {
148 *e = 0;
149 r.obj_free.push(slot);
150 }
151}
152
153pub fn untrack_scope(slot: u32) {
155 if slot == NO_SLOT {
156 return;
157 }
158 let mut r = REGISTRY.lock();
159 if let Some(e) = r.scopes.get_mut(slot as usize) {
160 *e = 0;
161 r.scope_free.push(slot);
162 }
163}
164
165
166enum Node {
174 O(Rc<RefCell<Obj>>),
175 S(Rc<RefCell<Scope>>),
176 P(Rc<RefCell<PromiseState>>),
177 G(Rc<RefCell<GenState>>),
178}
179
180impl Node {
181 fn strong(&self) -> usize {
182 match self {
183 Node::O(r) => Rc::strong_count(r),
184 Node::S(r) => Rc::strong_count(r),
185 Node::P(r) => Rc::strong_count(r),
186 Node::G(r) => Rc::strong_count(r),
187 }
188 }
189}
190
191struct ChunkVec<T> {
196 chunks: Vec<Vec<T>>,
197 len: usize,
198}
199
200const GC_CHUNK: usize = 16 * 1024;
201
202impl<T> ChunkVec<T> {
203 const fn new() -> Self {
204 ChunkVec { chunks: Vec::new(), len: 0 }
205 }
206
207 fn push(&mut self, v: T) {
208 if self.len.is_multiple_of(GC_CHUNK) {
209 self.chunks.push(Vec::with_capacity(GC_CHUNK));
210 }
211 if let Some(c) = self.chunks.last_mut() {
212 c.push(v);
213 self.len += 1;
214 }
215 }
216
217 fn len(&self) -> usize {
218 self.len
219 }
220
221 fn get(&self, i: usize) -> Option<&T> {
222 self.chunks.get(i / GC_CHUNK).and_then(|c| c.get(i % GC_CHUNK))
223 }
224
225 fn get_mut(&mut self, i: usize) -> Option<&mut T> {
226 self.chunks.get_mut(i / GC_CHUNK).and_then(|c| c.get_mut(i % GC_CHUNK))
227 }
228
229 fn iter(&self) -> impl Iterator<Item = &T> {
230 self.chunks.iter().flatten()
231 }
232}
233
234impl<T: Copy> ChunkVec<T> {
235 fn filled(n: usize, v: T) -> Self {
236 let mut c = ChunkVec::new();
237 for _ in 0..n {
238 c.push(v);
239 }
240 c
241 }
242}
243
244impl<T> core::ops::Index<usize> for ChunkVec<T> {
245 type Output = T;
246 fn index(&self, i: usize) -> &T {
247 match self.get(i) {
248 Some(v) => v,
249 None => panic!("ChunkVec index out of range"),
250 }
251 }
252}
253
254impl<T> core::ops::IndexMut<usize> for ChunkVec<T> {
255 fn index_mut(&mut self, i: usize) -> &mut T {
256 match self.get_mut(i) {
257 Some(v) => v,
258 None => panic!("ChunkVec index out of range"),
259 }
260 }
261}
262
263type InterMap = BTreeMap<usize, usize>;
265
266fn discover_intermediates(nodes: &mut ChunkVec<Option<Node>>) -> InterMap {
268 let mut map = InterMap::new();
269 let add = |nodes: &mut ChunkVec<Option<Node>>, map: &mut InterMap, n: Node, p: usize| {
270 if let alloc::collections::btree_map::Entry::Vacant(e) = map.entry(p) {
271 e.insert(nodes.len());
272 nodes.push(Some(n));
273 }
274 };
275 let base = nodes.len();
276 for i in 0..base {
277 let found = match &nodes[i] {
278 Some(Node::O(o)) => match o.try_borrow() {
279 Ok(b) => match &b.kind {
280 ObjKind::PromiseObj(st) | ObjKind::Resolver { state: st, .. } => Some(Node::P(st.clone())),
281 ObjKind::Generator(g) => Some(Node::G(g.clone())),
282 _ => None,
283 },
284 Err(_) => None,
285 },
286 _ => None,
287 };
288 if let Some(n) = found {
289 let p = match &n {
290 Node::P(r) => Rc::as_ptr(r) as usize,
291 Node::G(r) => Rc::as_ptr(r) as usize,
292 _ => 0,
293 };
294 add(nodes, &mut map, n, p);
295 }
296 }
297 let mut i = base;
299 while i < nodes.len() {
300 let derived: Vec<Rc<RefCell<PromiseState>>> = match &nodes[i] {
301 Some(Node::P(st)) => match st.try_borrow() {
302 Ok(b) => b.reactions.iter().map(|r| r.result.clone()).collect(),
303 Err(_) => Vec::new(),
304 },
305 _ => Vec::new(),
306 };
307 for d in derived {
308 let p = Rc::as_ptr(&d) as usize;
309 add(nodes, &mut map, Node::P(d), p);
310 }
311 i += 1;
312 }
313 map
314}
315
316fn children(n: &Node, n_objs: usize, inter: &InterMap, out: &mut Vec<usize>) -> bool {
320 let obj = |o: &Rc<RefCell<Obj>>, out: &mut Vec<usize>| {
321 if let Ok(b) = o.try_borrow() {
322 if b.gc_slot != NO_SLOT {
323 out.push(b.gc_slot as usize);
324 }
325 }
326 };
327 let scope = |s: &Rc<RefCell<Scope>>, out: &mut Vec<usize>| {
328 if let Ok(b) = s.try_borrow() {
329 if b.gc_slot != NO_SLOT {
330 out.push(n_objs + b.gc_slot as usize);
331 }
332 }
333 };
334 let val = |v: &Value, out: &mut Vec<usize>| {
335 if let Value::Object(o) = v {
336 obj(o, out);
337 }
338 };
339 let promise = |st: &Rc<RefCell<PromiseState>>, out: &mut Vec<usize>| {
340 if let Some(&j) = inter.get(&(Rc::as_ptr(st) as usize)) {
341 out.push(j);
342 }
343 };
344 match n {
345 Node::P(st) => {
346 let Ok(b) = st.try_borrow() else { return false };
347 val(&b.value, out);
348 for r in &b.reactions {
349 if let Some(f) = &r.on_fulfilled {
350 val(f, out);
351 }
352 if let Some(f) = &r.on_rejected {
353 val(f, out);
354 }
355 promise(&r.result, out);
356 }
357 true
358 }
359 Node::G(g) => {
360 let Ok(b) = g.try_borrow() else { return false };
361 scope(&b.func.closure, out);
362 if let Some(bt) = &b.func.bound_this {
363 val(bt, out);
364 }
365 for v in &b.args {
366 val(v, out);
367 }
368 val(&b.this, out);
369 for c in &b.sent {
370 match c {
371 GenCompletion::Normal(v) | GenCompletion::Throw(v) | GenCompletion::Return(v) => val(v, out),
372 }
373 }
374 val(&b.returned, out);
375 if let Some(fr) = &b.vm {
377 fr.gc_children(&mut |e| match e {
378 super::interp::gen_vm::GcEdge::Val(v) => val(v, out),
379 super::interp::gen_vm::GcEdge::Scope(s) => scope(s, out),
380 });
381 }
382 true
383 }
384 Node::S(s) => {
385 let Ok(b) = s.try_borrow() else { return false };
386 if let Some(p) = &b.parent {
387 scope(p, out);
388 }
389 for v in b.vars.values() {
390 val(v, out);
391 }
392 true
393 }
394 Node::O(o) => {
395 let Ok(b) = o.try_borrow() else { return false };
396 if let Some(p) = &b.proto {
397 obj(p, out);
398 }
399 for v in b.props.values() {
400 val(v, out);
401 }
402 if let Some(rare) = b.rare_data() {
403 for (_, a) in rare.accessors.iter() {
404 if let Some(g) = &a.get {
405 val(g, out);
406 }
407 if let Some(s) = &a.set {
408 val(s, out);
409 }
410 }
411 for (_, _, v) in &rare.private_fields {
412 val(v, out);
413 }
414 }
415 match &b.kind {
416 ObjKind::Array(items) | ObjKind::SetObj(items) => {
417 for v in items {
418 val(v, out);
419 }
420 }
421 ObjKind::MapObj(entries) => {
422 for (k, v) in entries {
423 val(k, out);
424 val(v, out);
425 }
426 }
427 ObjKind::Function(f) => {
428 scope(&f.closure, out);
429 if let Some(bt) = &f.bound_this {
430 val(bt, out);
431 }
432 }
433 ObjKind::Proxy(p) => {
434 obj(&p.target, out);
435 obj(&p.handler, out);
436 }
437 ObjKind::PromiseObj(st) | ObjKind::Resolver { state: st, .. } => promise(st, out),
438 ObjKind::Generator(g) => {
439 if let Some(&j) = inter.get(&(Rc::as_ptr(g) as usize)) {
440 out.push(j);
441 }
442 }
443 ObjKind::Bound(b) => {
444 val(&b.target, out);
445 val(&b.bound_this, out);
446 for v in &b.bound_args {
447 val(v, out);
448 }
449 }
450 ObjKind::PrivateDesc(pd) => match &pd.kind {
451 crate::os_lib::ecma::value::PrivateKind::Method(v)
452 | crate::os_lib::ecma::value::PrivateKind::StaticMethod(v) => val(v, out),
453 crate::os_lib::ecma::value::PrivateKind::Accessor { get, set }
454 | crate::os_lib::ecma::value::PrivateKind::StaticAccessor { get, set } => {
455 if let Some(g) = get {
456 val(g, out);
457 }
458 if let Some(s) = set {
459 val(s, out);
460 }
461 }
462 _ => {}
463 },
464 _ => {}
466 }
467 true
468 }
469 }
470}
471
472#[derive(Debug, Default, Clone, Copy)]
474pub struct GcStats {
475 pub objs: usize,
476 pub scopes: usize,
477 pub garbage_objs: usize,
478 pub garbage_scopes: usize,
479 pub count_plain: usize,
480 pub count_func: usize,
481 pub count_array: usize,
482 pub count_dom: usize,
483 pub count_promise: usize,
484 pub count_other: usize,
485}
486
487pub fn collect(free: bool) -> GcStats {
489 let (nodes, n_objs) = {
492 let r = REGISTRY.lock();
493 MADE.store(0, Ordering::Relaxed);
494 let n_objs = r.objs.len();
495 let mut nodes: ChunkVec<Option<Node>> = ChunkVec::new();
496 for &p in r.objs.iter() {
497 nodes.push((p != 0).then(|| {
498 Node::O(unsafe {
501 let p = p as *const RefCell<Obj>;
502 Rc::increment_strong_count(p);
503 Rc::from_raw(p)
504 })
505 }));
506 }
507 for &p in r.scopes.iter() {
508 nodes.push((p != 0).then(|| {
509 Node::S(unsafe {
511 let p = p as *const RefCell<Scope>;
512 Rc::increment_strong_count(p);
513 Rc::from_raw(p)
514 })
515 }));
516 }
517 (nodes, n_objs)
518 };
519 let mut nodes = nodes;
520 let inter = discover_intermediates(&mut nodes);
521 let n = nodes.len();
522 let mut stats = GcStats::default();
523 for x in nodes.iter().flatten() {
524 match x {
525 Node::O(_) => stats.objs += 1,
526 Node::S(_) => stats.scopes += 1,
527 Node::P(_) | Node::G(_) => {}
528 }
529 }
530
531 const MARK: u32 = 1 << 31;
534 let mut st: ChunkVec<u32> = ChunkVec::filled(n, 0);
535 let mut buf: Vec<usize> = Vec::new();
536 for (i, x) in nodes.iter().enumerate() {
537 let Some(x) = x else { continue };
538 buf.clear();
539 if !children(x, n_objs, &inter, &mut buf) {
540 st[i] |= MARK;
541 continue;
542 }
543 for &j in &buf {
544 if j < n && nodes[j].is_some() && (st[j] & !MARK) < (MARK - 1) {
545 st[j] += 1;
546 }
547 }
548 }
549
550 let mut stack: Vec<usize> = Vec::new();
552 for (i, x) in nodes.iter().enumerate() {
553 let Some(x) = x else { continue };
554 let internal = (st[i] & !MARK) as usize;
556 if st[i] & MARK != 0 || x.strong().saturating_sub(1) > internal {
557 st[i] |= MARK;
558 stack.push(i);
559 }
560 }
561 while let Some(i) = stack.pop() {
562 let Some(x) = &nodes[i] else { continue };
563 buf.clear();
564 if !children(x, n_objs, &inter, &mut buf) {
565 continue;
566 }
567 for &j in &buf {
568 if j < n && nodes[j].is_some() && st[j] & MARK == 0 {
569 st[j] |= MARK;
570 stack.push(j);
571 }
572 }
573 }
574 drop(stack);
575 drop(buf);
576
577 let mut taken: Vec<Value> = Vec::new();
579 let mut taken_scopes: Vec<Rc<RefCell<Scope>>> = Vec::new();
580 let mut taken_kinds: Vec<ObjKind> = Vec::new();
581 let mut taken_reactions: Vec<super::value::Reaction> = Vec::new();
582 let mut taken_sent: Vec<GenCompletion> = Vec::new();
583 let mut taken_frames: Vec<alloc::boxed::Box<super::interp::gen_vm::GenFrame>> = Vec::new();
584 for (i, x) in nodes.iter().enumerate() {
585 let Some(x) = x else { continue };
586 if st[i] & MARK != 0 {
587 if let Node::O(o) = x {
588 if let Ok(b) = o.try_borrow() {
589 match &b.kind {
590 ObjKind::Plain => stats.count_plain += 1,
591 ObjKind::Function(_) | ObjKind::Native { .. } | ObjKind::Bound(_) => stats.count_func += 1,
592 ObjKind::Array(_) | ObjKind::Bytes(_) => stats.count_array += 1,
593 ObjKind::HostRef(_) => stats.count_dom += 1,
594 ObjKind::PromiseObj(_) | ObjKind::Resolver { .. } => stats.count_promise += 1,
595 _ => stats.count_other += 1,
596 }
597 }
598 }
599 continue;
600 }
601 match x {
602 Node::O(o) => {
603 stats.garbage_objs += 1;
604 if free {
605 if let Ok(mut b) = o.try_borrow_mut() {
606 if let Some(p) = b.proto.take() {
607 taken.push(Value::Object(p));
608 }
609 let props = core::mem::take(&mut b.props);
610 taken.extend(props.into_iter().map(|(_, v)| v));
611 if let Some(rare) = b.rare.take() {
612 for (_, a) in rare.accessors {
613 taken.extend(a.get);
614 taken.extend(a.set);
615 }
616 for (_, _, v) in rare.private_fields {
617 taken.push(v);
618 }
619 }
620 taken_kinds.push(core::mem::replace(&mut b.kind, ObjKind::Plain));
621 }
622 }
623 }
624 Node::P(p) => {
625 if free {
626 if let Ok(mut b) = p.try_borrow_mut() {
627 taken.push(core::mem::replace(&mut b.value, Value::Undefined));
628 taken_reactions.extend(core::mem::take(&mut b.reactions));
629 }
630 }
631 }
632 Node::G(g) => {
633 if free {
634 if let Ok(mut b) = g.try_borrow_mut() {
635 taken.extend(core::mem::take(&mut b.args));
636 taken.push(core::mem::replace(&mut b.this, Value::Undefined));
637 taken.push(core::mem::replace(&mut b.returned, Value::Undefined));
638 taken_sent.extend(core::mem::take(&mut b.sent));
639 if let Some(fr) = b.vm.take() {
640 taken_frames.push(fr);
641 }
642 if let Some(bt) = b.func.bound_this.take() {
643 taken.push((*bt).clone());
644 }
645 }
646 }
647 }
648 Node::S(s) => {
649 stats.garbage_scopes += 1;
650 if free {
651 if let Ok(mut b) = s.try_borrow_mut() {
652 if let Some(p) = b.parent.take() {
653 taken_scopes.push(p);
654 }
655 let vars = core::mem::take(&mut b.vars);
656 taken.extend(vars.into_values());
657 }
658 }
659 }
660 }
661 }
662 drop(st);
663 drop(taken);
665 drop(taken_scopes);
666 drop(taken_kinds);
667 drop(taken_reactions);
668 drop(taken_sent);
669 drop(taken_frames);
670 drop(nodes);
673 stats
674}