FinalizationGroupObject.cpp 25.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
 * vim: set ts=8 sts=2 et sw=2 tw=80:
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

// Implementation of JS FinalizationGroup objects.

#include "builtin/FinalizationGroupObject.h"

11
12
#include "mozilla/ScopeExit.h"

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
#include "gc/Zone.h"
#include "vm/GlobalObject.h"

#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"

using namespace js;

///////////////////////////////////////////////////////////////////////////
// FinalizationRecordObject

const JSClass FinalizationRecordObject::class_ = {
    "FinalizationRecord", JSCLASS_HAS_RESERVED_SLOTS(SlotCount),
    JS_NULL_CLASS_OPS, JS_NULL_CLASS_SPEC};

/* static */
FinalizationRecordObject* FinalizationRecordObject::create(
    JSContext* cx, HandleFinalizationGroupObject group, HandleValue holdings) {
  MOZ_ASSERT(group);

  auto record = NewObjectWithNullTaggedProto<FinalizationRecordObject>(cx);
  if (!record) {
    return nullptr;
  }

  record->initReservedSlot(GroupSlot, ObjectValue(*group));
  record->initReservedSlot(HoldingsSlot, holdings);

  return record;
}

FinalizationGroupObject* FinalizationRecordObject::group() const {
  Value value = getReservedSlot(GroupSlot);
  if (value.isNull()) {
    return nullptr;
  }
  return &value.toObject().as<FinalizationGroupObject>();
}

Value FinalizationRecordObject::holdings() const {
  return getReservedSlot(HoldingsSlot);
}

56
57
58
59
60
bool FinalizationRecordObject::wasCleared() const {
  MOZ_ASSERT_IF(!group(), holdings().isUndefined());
  return !group();
}

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
void FinalizationRecordObject::clear() {
  MOZ_ASSERT(group());
  setReservedSlot(GroupSlot, NullValue());
  setReservedSlot(HoldingsSlot, UndefinedValue());
}

///////////////////////////////////////////////////////////////////////////
// FinalizationRecordVectorObject

const JSClass FinalizationRecordVectorObject::class_ = {
    "FinalizationRecordVector",
    JSCLASS_HAS_RESERVED_SLOTS(SlotCount) | JSCLASS_BACKGROUND_FINALIZE,
    &classOps_, JS_NULL_CLASS_SPEC};

const JSClassOps FinalizationRecordVectorObject::classOps_ = {
    nullptr, /* addProperty */
    nullptr, /* delProperty */
    nullptr, /* enumerate   */
    nullptr, /* newEnumerate */
    nullptr, /* resolve     */
    nullptr, /* mayResolve  */
    FinalizationRecordVectorObject::finalize,
    nullptr, /* call        */
    nullptr, /* hasInstance */
    nullptr, /* construct   */
    FinalizationRecordVectorObject::trace};

/* static */
FinalizationRecordVectorObject* FinalizationRecordVectorObject::create(
    JSContext* cx) {
91
  auto records = cx->make_unique<FinalizationRecordVector>(cx->zone());
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
  if (!records) {
    return nullptr;
  }

  auto object =
      NewObjectWithNullTaggedProto<FinalizationRecordVectorObject>(cx);
  if (!object) {
    return nullptr;
  }

  InitReservedSlot(object, RecordsSlot, records.release(),
                   MemoryUse::FinalizationRecordVector);

  return object;
}

/* static */
void FinalizationRecordVectorObject::trace(JSTracer* trc, JSObject* obj) {
  auto rv = &obj->as<FinalizationRecordVectorObject>();
111
112
113
  if (auto* records = rv->records()) {
    records->trace(trc);
  }
114
115
116
117
118
}

/* static */
void FinalizationRecordVectorObject::finalize(JSFreeOp* fop, JSObject* obj) {
  auto rv = &obj->as<FinalizationRecordVectorObject>();
119
  fop->delete_(obj, rv->records(), MemoryUse::FinalizationRecordVector);
120
121
}

122
123
inline FinalizationRecordVector* FinalizationRecordVectorObject::records() {
  return static_cast<FinalizationRecordVector*>(privatePtr());
124
125
}

126
127
128
inline const FinalizationRecordVector* FinalizationRecordVectorObject::records()
    const {
  return static_cast<const FinalizationRecordVector*>(privatePtr());
129
130
131
}

inline void* FinalizationRecordVectorObject::privatePtr() const {
132
133
134
135
136
  Value value = getReservedSlot(RecordsSlot);
  if (value.isUndefined()) {
    return nullptr;
  }
  void* ptr = value.toPrivate();
137
138
139
140
141
  MOZ_ASSERT(ptr);
  return ptr;
}

inline bool FinalizationRecordVectorObject::isEmpty() const {
142
143
  MOZ_ASSERT(records());
  return records()->empty();
144
145
146
147
}

inline bool FinalizationRecordVectorObject::append(
    HandleFinalizationRecordObject record) {
148
149
  MOZ_ASSERT(records());
  return records()->append(record);
150
151
152
153
}

inline void FinalizationRecordVectorObject::remove(
    HandleFinalizationRecordObject record) {
154
155
  MOZ_ASSERT(records());
  records()->eraseIfEqual(record);
156
157
158
159
160
}

///////////////////////////////////////////////////////////////////////////
// FinalizationGroupObject

161
162
163
// Bug 1600300: FinalizationGroupObject is foreground finalized so that HeapPtr
// destructors never see referents with released arenas. When this is fixed we
// may be able to make this background finalized again.
164
165
166
const JSClass FinalizationGroupObject::class_ = {
    "FinalizationGroup",
    JSCLASS_HAS_CACHED_PROTO(JSProto_FinalizationGroup) |
167
        JSCLASS_HAS_RESERVED_SLOTS(SlotCount) | JSCLASS_FOREGROUND_FINALIZE,
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
    &classOps_, &classSpec_};

const JSClass FinalizationGroupObject::protoClass_ = {
    "FinalizationGroupPrototype",
    JSCLASS_HAS_CACHED_PROTO(JSProto_FinalizationGroup), JS_NULL_CLASS_OPS,
    &classSpec_};

const JSClassOps FinalizationGroupObject::classOps_ = {
    nullptr, /* addProperty */
    nullptr, /* delProperty */
    nullptr, /* enumerate   */
    nullptr, /* newEnumerate */
    nullptr, /* resolve     */
    nullptr, /* mayResolve  */
    FinalizationGroupObject::finalize,
    nullptr, /* call        */
    nullptr, /* hasInstance */
    nullptr, /* construct   */
    FinalizationGroupObject::trace};

const ClassSpec FinalizationGroupObject::classSpec_ = {
    GenericCreateConstructor<construct, 1, gc::AllocKind::FUNCTION>,
    GenericCreatePrototype<FinalizationGroupObject>,
    nullptr,
    nullptr,
    methods_,
    properties_};

196
197
198
199
const JSFunctionSpec FinalizationGroupObject::methods_[] = {
    JS_FN(js_register_str, register_, 2, 0),
    JS_FN(js_unregister_str, unregister, 1, 0),
    JS_FN(js_cleanupSome_str, cleanupSome, 0, 0), JS_FS_END};
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

const JSPropertySpec FinalizationGroupObject::properties_[] = {
    JS_STRING_SYM_PS(toStringTag, "FinalizationGroup", JSPROP_READONLY),
    JS_PS_END};

/* static */
bool FinalizationGroupObject::construct(JSContext* cx, unsigned argc,
                                        Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  if (!ThrowIfNotConstructing(cx, args, "FinalizationGroup")) {
    return false;
  }

  RootedObject cleanupCallback(
      cx, ValueToCallable(cx, args.get(0), 1, NO_CONSTRUCT));
  if (!cleanupCallback) {
    return false;
  }

  RootedObject proto(cx);
  if (!GetPrototypeFromBuiltinConstructor(cx, args, JSProto_FinalizationGroup,
                                          &proto)) {
    return false;
  }

226
227
228
  Rooted<UniquePtr<ObjectWeakMap>> registrations(
      cx, cx->make_unique<ObjectWeakMap>(cx));
  if (!registrations) {
229
230
231
    return false;
  }

232
233
  Rooted<UniquePtr<FinalizationRecordVector>> holdings(
      cx, cx->make_unique<FinalizationRecordVector>(cx->zone()));
234
  if (!holdings) {
235
236
237
    return false;
  }

238
239
240
  FinalizationGroupObject* group =
      NewObjectWithClassProto<FinalizationGroupObject>(cx, proto);
  if (!group) {
241
242
243
244
245
246
    return false;
  }

  group->initReservedSlot(CleanupCallbackSlot, ObjectValue(*cleanupCallback));
  InitReservedSlot(group, RegistrationsSlot, registrations.release(),
                   MemoryUse::FinalizationGroupRegistrations);
247
248
  InitReservedSlot(group, RecordsToBeCleanedUpSlot, holdings.release(),
                   MemoryUse::FinalizationGroupRecordVector);
249
250
251
252
253
254
255
256
257
258
  group->initReservedSlot(IsQueuedForCleanupSlot, BooleanValue(false));
  group->initReservedSlot(IsCleanupJobActiveSlot, BooleanValue(false));

  args.rval().setObject(*group);
  return true;
}

/* static */
void FinalizationGroupObject::trace(JSTracer* trc, JSObject* obj) {
  auto group = &obj->as<FinalizationGroupObject>();
259
  if (FinalizationRecordVector* holdings = group->recordsToBeCleanedUp()) {
260
261
262
263
264
    holdings->trace(trc);
  }
  if (ObjectWeakMap* registrations = group->registrations()) {
    registrations->trace(trc);
  }
265
266
267
268
269
}

/* static */
void FinalizationGroupObject::finalize(JSFreeOp* fop, JSObject* obj) {
  auto group = &obj->as<FinalizationGroupObject>();
270
271
  fop->delete_(obj, group->recordsToBeCleanedUp(),
               MemoryUse::FinalizationGroupRecordVector);
272
273
274
275
276
277
278
279
280
281
282
283
284
  fop->delete_(obj, group->registrations(),
               MemoryUse::FinalizationGroupRegistrations);
}

inline JSObject* FinalizationGroupObject::cleanupCallback() const {
  Value value = getReservedSlot(CleanupCallbackSlot);
  if (value.isUndefined()) {
    return nullptr;
  }
  return &value.toObject();
}

ObjectWeakMap* FinalizationGroupObject::registrations() const {
285
286
287
288
289
  Value value = getReservedSlot(RegistrationsSlot);
  if (value.isUndefined()) {
    return nullptr;
  }
  return static_cast<ObjectWeakMap*>(value.toPrivate());
290
291
}

292
293
294
FinalizationRecordVector* FinalizationGroupObject::recordsToBeCleanedUp()
    const {
  Value value = getReservedSlot(RecordsToBeCleanedUpSlot);
295
296
297
  if (value.isUndefined()) {
    return nullptr;
  }
298
  return static_cast<FinalizationRecordVector*>(value.toPrivate());
299
300
301
302
303
304
305
306
307
308
}

bool FinalizationGroupObject::isQueuedForCleanup() const {
  return getReservedSlot(IsQueuedForCleanupSlot).toBoolean();
}

bool FinalizationGroupObject::isCleanupJobActive() const {
  return getReservedSlot(IsCleanupJobActiveSlot).toBoolean();
}

309
310
void FinalizationGroupObject::queueRecordToBeCleanedUp(
    FinalizationRecordObject* record) {
311
  AutoEnterOOMUnsafeRegion oomUnsafe;
312
313
  if (!recordsToBeCleanedUp()->append(record)) {
    oomUnsafe.crash("FinalizationGroupObject::queueRecordsToBeCleanedUp");
314
315
316
317
318
319
320
321
322
323
324
325
326
  }
}

void FinalizationGroupObject::setQueuedForCleanup(bool value) {
  MOZ_ASSERT(value != isQueuedForCleanup());
  setReservedSlot(IsQueuedForCleanupSlot, BooleanValue(value));
}

void FinalizationGroupObject::setCleanupJobActive(bool value) {
  MOZ_ASSERT(value != isCleanupJobActive());
  setReservedSlot(IsCleanupJobActiveSlot, BooleanValue(value));
}

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
// FinalizationGroup.prototype.register(target , holdings [, unregisterToken ])
// https://tc39.es/proposal-weakrefs/#sec-finalization-group.prototype.register
/* static */
bool FinalizationGroupObject::register_(JSContext* cx, unsigned argc,
                                        Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // 1. Let finalizationGroup be the this value.
  // 2. If Type(finalizationGroup) is not Object, throw a TypeError exception.
  // 3. If finalizationGroup does not have a [[Cells]] internal slot, throw a
  // TypeError exception.
  if (!args.thisv().isObject() ||
      !args.thisv().toObject().is<FinalizationGroupObject>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_A_FINALIZATION_GROUP,
                              "Receiver of FinalizationGroup.register call");
    return false;
  }

  RootedFinalizationGroupObject group(
      cx, &args.thisv().toObject().as<FinalizationGroupObject>());

  // 4. If Type(target) is not Object, throw a TypeError exception.
  if (!args.get(0).isObject()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_OBJECT_REQUIRED,
                              "target argument to FinalizationGroup.register");
    return false;
  }

  RootedObject target(cx, &args[0].toObject());

  // 5. If SameValue(target, holdings), throw a TypeError exception.
  if (args.get(1).isObject() && &args.get(1).toObject() == target) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_BAD_HOLDINGS);
    return false;
  }

365
  HandleValue holdings = args.get(1);
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

  // 6. If Type(unregisterToken) is not Object,
  //    a. If unregisterToken is not undefined, throw a TypeError exception.
  if (!args.get(2).isUndefined() && !args.get(2).isObject()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_UNREGISTER_TOKEN,
                              "FinalizationGroup.register");
    return false;
  }

  RootedObject unregisterToken(cx);
  if (!args.get(2).isUndefined()) {
    unregisterToken = &args[2].toObject();
  }

  // Create the finalization record representing this target and holdings.
  Rooted<FinalizationRecordObject*> record(
      cx, FinalizationRecordObject::create(cx, group, holdings));
  if (!record) {
    return false;
  }

  if (unregisterToken && !addRegistration(cx, group, unregisterToken, record)) {
    return false;
  }

  auto guard = mozilla::MakeScopeExit([&] {
    if (unregisterToken) {
      removeRegistrationOnError(group, unregisterToken, record);
    }
  });

  // Fully unwrap the target to pass it to the GC.
  RootedObject unwrappedTarget(cx);
  unwrappedTarget = CheckedUnwrapDynamic(target, cx);
  if (!unwrappedTarget) {
    ReportAccessDenied(cx);
    return false;
  }

  // Wrap the record into the compartment of the target.
  RootedObject wrappedRecord(cx, record);
  AutoRealm ar(cx, unwrappedTarget);
  if (!JS_WrapObject(cx, &wrappedRecord)) {
    return false;
  }

  // Register the record with the target.
  gc::GCRuntime* gc = &cx->runtime()->gc;
  if (!gc->registerWithFinalizationGroup(cx, unwrappedTarget, wrappedRecord)) {
    return false;
  }

  guard.release();
  args.rval().setUndefined();
  return true;
}

/* static */
bool FinalizationGroupObject::addRegistration(
    JSContext* cx, HandleFinalizationGroupObject group,
    HandleObject unregisterToken, HandleFinalizationRecordObject record) {
  // Add the record to the list of records associated with this unregister
  // token.

  MOZ_ASSERT(unregisterToken);
  MOZ_ASSERT(group->registrations());

  auto& map = *group->registrations();
  Rooted<FinalizationRecordVectorObject*> recordsObject(cx);
  JSObject* obj = map.lookup(unregisterToken);
  if (obj) {
    recordsObject = &obj->as<FinalizationRecordVectorObject>();
  } else {
    recordsObject = FinalizationRecordVectorObject::create(cx);
    if (!recordsObject || !map.add(cx, unregisterToken, recordsObject)) {
      return false;
    }
  }

446
447
448
449
450
451
  if (!recordsObject->append(record)) {
    ReportOutOfMemory(cx);
    return false;
  }

  return true;
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
}

/* static */ void FinalizationGroupObject::removeRegistrationOnError(
    HandleFinalizationGroupObject group, HandleObject unregisterToken,
    HandleFinalizationRecordObject record) {
  // Remove a registration if something went wrong before we added it to the
  // target zone's map. Note that this can't remove a registration after that
  // point.

  MOZ_ASSERT(unregisterToken);
  MOZ_ASSERT(group->registrations());
  JS::AutoAssertNoGC nogc;

  auto& map = *group->registrations();
  JSObject* obj = map.lookup(unregisterToken);
  MOZ_ASSERT(obj);
  auto records = &obj->as<FinalizationRecordVectorObject>();
  records->remove(record);

  if (records->empty()) {
    map.remove(unregisterToken);
  }
}

// FinalizationGroup.prototype.unregister ( unregisterToken )
// https://tc39.es/proposal-weakrefs/#sec-finalization-group.prototype.unregister
/* static */
bool FinalizationGroupObject::unregister(JSContext* cx, unsigned argc,
                                         Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // 1. Let finalizationGroup be the this value.
  // 2. If Type(finalizationGroup) is not Object, throw a TypeError exception.
  // 3. If finalizationGroup does not have a [[Cells]] internal slot, throw a
  //    TypeError exception.
  if (!args.thisv().isObject() ||
      !args.thisv().toObject().is<FinalizationGroupObject>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_A_FINALIZATION_GROUP,
                              "Receiver of FinalizationGroup.unregister call");
    return false;
  }

  RootedFinalizationGroupObject group(
      cx, &args.thisv().toObject().as<FinalizationGroupObject>());

  // 4. If Type(unregisterToken) is not Object, throw a TypeError exception.
  if (!args.get(0).isObject()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_UNREGISTER_TOKEN,
                              "FinalizationGroup.unregister");
    return false;
  }

  RootedObject unregisterToken(cx, &args[0].toObject());

508
509
510
511
512
513
514
515
516
  // 5. Let removed be false.
  bool removed = false;

  // 6. For each Record { [[Target]], [[Holdings]], [[UnregisterToken]] } cell
  //    that is an element of finalizationGroup.[[Cells]], do
  //    a. If SameValue(cell.[[UnregisterToken]], unregisterToken) is true, then
  //       i. Remove cell from finalizationGroup.[[Cells]].
  //       ii. Set removed to true.

517
518
  RootedObject obj(cx, group->registrations()->lookup(unregisterToken));
  if (obj) {
519
520
521
522
    auto* records = obj->as<FinalizationRecordVectorObject>().records();
    MOZ_ASSERT(records);
    MOZ_ASSERT(!records->empty());
    for (FinalizationRecordObject* record : *records) {
523
524
525
526
527
528
      if (!record->wasCleared()) {
        // Clear the fields of this record; it will be removed from the target's
        // list when it is next swept.
        record->clear();
        removed = true;
      }
529
530
531
532
    }
    group->registrations()->remove(unregisterToken);
  }

533
534
  // 7. Return removed.
  args.rval().setBoolean(removed);
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
  return true;
}

// FinalizationGroup.prototype.cleanupSome ( [ callback ] )
// https://tc39.es/proposal-weakrefs/#sec-finalization-group.prototype.cleanupSome
bool FinalizationGroupObject::cleanupSome(JSContext* cx, unsigned argc,
                                          Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // 1. Let finalizationGroup be the this value.
  // 2. If Type(finalizationGroup) is not Object, throw a TypeError exception.
  // 3. If finalizationGroup does not have [[Cells]] and
  //    [[IsFinalizationGroupCleanupJobActive]] internal slots, throw a
  //    TypeError exception.
  if (!args.thisv().isObject() ||
      !args.thisv().toObject().is<FinalizationGroupObject>()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_NOT_A_FINALIZATION_GROUP,
                              "Receiver of FinalizationGroup.cleanupSome call");
    return false;
  }

  // 4. If finalizationGroup.[[IsFinalizationGroupCleanupJobActive]] is true,
  //    throw a TypeError exception.
  RootedFinalizationGroupObject group(
      cx, &args.thisv().toObject().as<FinalizationGroupObject>());
  if (group->isCleanupJobActive()) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_BAD_CLEANUP_STATE);
    return false;
  }

  // 5. If callback is not undefined and IsCallable(callback) is false, throw a
  //    TypeError exception.
  RootedObject cleanupCallback(cx);
  if (!args.get(0).isUndefined()) {
    cleanupCallback = ValueToCallable(cx, args.get(0), -1, NO_CONSTRUCT);
    if (!cleanupCallback) {
      return false;
    }
  }

577
  if (!cleanupQueuedRecords(cx, group, cleanupCallback)) {
578
579
580
581
582
583
584
585
586
587
    return false;
  }

  args.rval().setUndefined();
  return true;
}

// CleanupFinalizationGroup ( finalizationGroup [ , callback ] )
// https://tc39.es/proposal-weakrefs/#sec-cleanup-finalization-group
/* static */
588
bool FinalizationGroupObject::cleanupQueuedRecords(
589
590
    JSContext* cx, HandleFinalizationGroupObject group,
    HandleObject callbackArg) {
591
  MOZ_ASSERT(cx->compartment() == group->compartment());
592
593

  // 2. If CheckForEmptyCells(finalizationGroup) is false, return.
594
595
  FinalizationRecordVector* records = group->recordsToBeCleanedUp();
  size_t initialLength = records->length();
596
597
598
599
600
601
602
603
604
605
606
607
608
609
  if (initialLength == 0) {
    return true;
  }

  // 3. Let iterator be
  //    !CreateFinalizationGroupCleanupIterator(finalizationGroup).
  Rooted<FinalizationIteratorObject*> iterator(
      cx, FinalizationIteratorObject::create(cx, group));
  if (!iterator) {
    return false;
  }

  // 4. If callback is undefined, set callback to
  //    finalizationGroup.[[CleanupCallback]].
610
611
612
613
614
615
616
  RootedValue callback(cx);
  if (callbackArg) {
    callback.setObject(*callbackArg);
  } else {
    JSObject* cleanupCallback = group->cleanupCallback();
    MOZ_ASSERT(cleanupCallback);
    callback.setObject(*cleanupCallback);
617
618
619
620
621
622
  }

  // 5. Set finalizationGroup.[[IsFinalizationGroupCleanupJobActive]] to true.
  group->setCleanupJobActive(true);

  // 6. Let result be Call(callback, undefined, iterator).
623
  RootedValue iteratorVal(cx, ObjectValue(*iterator));
624
  RootedValue rval(cx);
625
  bool ok = Call(cx, callback, UndefinedHandleValue, iteratorVal, &rval);
626

627
  // Remove records that were iterated over.
628
  size_t index = iterator->index();
629
630
  MOZ_ASSERT(index <= records->length());
  MOZ_ASSERT(initialLength <= records->length());
631
  if (index > 0) {
632
    records->erase(records->begin(), records->begin() + index);
633
634
635
636
637
638
639
640
641
642
643
  }

  // 7. Set finalizationGroup.[[IsFinalizationGroupCleanupJobActive]] to false.
  group->setCleanupJobActive(false);

  // 8. Set iterator.[[FinalizationGroup]] to empty.
  iterator->clearFinalizationGroup();

  return ok;
}

644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
///////////////////////////////////////////////////////////////////////////
// FinalizationIteratorObject

const JSClass FinalizationIteratorObject::class_ = {
    "FinalizationGroupCleanupIterator", JSCLASS_HAS_RESERVED_SLOTS(SlotCount),
    JS_NULL_CLASS_OPS, JS_NULL_CLASS_SPEC};

const JSFunctionSpec FinalizationIteratorObject::methods_[] = {
    JS_FN(js_next_str, next, 0, 0), JS_FS_END};

const JSPropertySpec FinalizationIteratorObject::properties_[] = {
    JS_STRING_SYM_PS(toStringTag, "FinalizationGroup Cleanup Iterator",
                     JSPROP_READONLY),
    JS_PS_END};

/* static */
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
bool GlobalObject::initFinalizationIteratorProto(JSContext* cx,
                                                 Handle<GlobalObject*> global) {
  Rooted<JSObject*> base(
      cx, GlobalObject::getOrCreateIteratorPrototype(cx, global));
  if (!base) {
    return false;
  }
  RootedPlainObject proto(cx, NewObjectWithGivenProto<PlainObject>(cx, base));
  if (!proto) {
    return false;
  }
  if (!JS_DefineFunctions(cx, proto, FinalizationIteratorObject::methods_) ||
      !JS_DefineProperties(cx, proto,
                           FinalizationIteratorObject::properties_)) {
    return false;
  }
  global->setReservedSlot(FINALIZATION_ITERATOR_PROTO, ObjectValue(*proto));
677
678
679
  return true;
}

680
681
682
683
684
685
686
687
688
689
690
/* static */ FinalizationIteratorObject* FinalizationIteratorObject::create(
    JSContext* cx, HandleFinalizationGroupObject group) {
  MOZ_ASSERT(group);

  RootedObject proto(cx, GlobalObject::getOrCreateFinalizationIteratorPrototype(
                             cx, cx->global()));
  if (!proto) {
    return nullptr;
  }

  FinalizationIteratorObject* iterator =
691
      NewObjectWithGivenProto<FinalizationIteratorObject>(cx, proto);
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
  if (!iterator) {
    return nullptr;
  }

  iterator->initReservedSlot(FinalizationGroupSlot, ObjectValue(*group));
  iterator->initReservedSlot(IndexSlot, Int32Value(0));

  return iterator;
}

FinalizationGroupObject* FinalizationIteratorObject::finalizationGroup() const {
  Value value = getReservedSlot(FinalizationGroupSlot);
  if (value.isUndefined()) {
    return nullptr;
  }
  return &value.toObject().as<FinalizationGroupObject>();
}

710
711
712
713
714
size_t FinalizationIteratorObject::index() const {
  int32_t i = getReservedSlot(IndexSlot).toInt32();
  MOZ_ASSERT(i >= 0);
  return size_t(i);
}
715

716
717
718
void FinalizationIteratorObject::setIndex(size_t i) {
  MOZ_ASSERT(i <= INT32_MAX);
  setReservedSlot(IndexSlot, Int32Value(int32_t(i)));
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
}

void FinalizationIteratorObject::clearFinalizationGroup() {
  MOZ_ASSERT(finalizationGroup());
  setReservedSlot(FinalizationGroupSlot, UndefinedValue());
}

// %FinalizationGroupCleanupIteratorPrototype%.next()
// https://tc39.es/proposal-weakrefs/#sec-%finalizationgroupcleanupiterator%.next
/* static */
bool FinalizationIteratorObject::next(JSContext* cx, unsigned argc, Value* vp) {
  CallArgs args = CallArgsFromVp(argc, vp);

  // 1. Let iterator be the this value.
  // 2. If Type(iterator) is not Object, throw a TypeError exception.
  // 3. If iterator does not have a [[FinalizationGroup]] internal slot, throw a
  //    TypeError exception.
  if (!args.thisv().isObject() ||
      !args.thisv().toObject().is<FinalizationIteratorObject>()) {
    JS_ReportErrorNumberASCII(
        cx, GetErrorMessage, nullptr, JSMSG_NOT_A_FINALIZATION_ITERATOR,
        "Receiver of FinalizationGroupCleanupIterator.next call");
    return false;
  }

  RootedFinalizationIteratorObject iterator(
      cx, &args.thisv().toObject().as<FinalizationIteratorObject>());

  // 4. If iterator.[[FinalizationGroup]] is empty, throw a TypeError exception.
  // 5. Let finalizationGroup be iterator.[[FinalizationGroup]].
  RootedFinalizationGroupObject group(cx, iterator->finalizationGroup());
  if (!group) {
    JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr,
                              JSMSG_STALE_FINALIZATION_GROUP_ITERATOR);
    return false;
  }

  // 8. If finalizationGroup.[[Cells]] contains a Record cell such that
  //    cell.[[Target]] is empty,
  //    a. Choose any such cell.
  //    b. Remove cell from finalizationGroup.[[Cells]].
  //    c. Return CreateIterResultObject(cell.[[Holdings]], false).
761
  FinalizationRecordVector* records = group->recordsToBeCleanedUp();
762
  size_t index = iterator->index();
763
764
765
766
767
768
769
770
771
772
773
774
775
  MOZ_ASSERT(index <= records->length());

  // Advance until we find a record that hasn't been unregistered.
  while (index < records->length() && index < INT32_MAX &&
         (*records)[index]->wasCleared()) {
    index++;
    iterator->setIndex(index);
  }

  if (index < records->length() && index < INT32_MAX) {
    RootedFinalizationRecordObject record(cx, (*records)[index]);
    RootedValue holdings(cx, record->holdings());
    JSObject* result = CreateIterResultObject(cx, holdings, false);
776
777
778
779
    if (!result) {
      return false;
    }

780
781
    record->clear();
    iterator->setIndex(index + 1);
782
783
784
785
786
787
788
789
790
791
792
793
794
795

    args.rval().setObject(*result);
    return true;
  }

  // 9. Otherwise, return CreateIterResultObject(undefined, true).
  JSObject* result = CreateIterResultObject(cx, UndefinedHandleValue, true);
  if (!result) {
    return false;
  }

  args.rval().setObject(*result);
  return true;
}