-
Notifications
You must be signed in to change notification settings - Fork 212
/
liveslots.js
1700 lines (1550 loc) · 63 KB
/
liveslots.js
1
2
3
4
5
6
7
8
9
10
11
12
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
56
57
58
59
60
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
196
197
198
199
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
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
365
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
446
447
448
449
450
451
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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint @typescript-eslint/no-floating-promises: "warn" */
import {
Remotable,
passStyleOf,
getInterfaceOf,
makeMarshal,
} from '@endo/marshal';
import { assert, Fail } from '@agoric/assert';
import { isPromise } from '@endo/promise-kit';
import { E, HandledPromise } from '@endo/eventual-send';
import { insistVatType, makeVatSlot, parseVatSlot } from './parseVatSlots.js';
import { insistCapData } from './capdata.js';
import { extractMethod, legibilizeMethod } from './kdebug.js';
import { insistMessage } from './message.js';
import { makeVirtualReferenceManager } from './virtualReferences.js';
import { makeVirtualObjectManager } from './virtualObjectManager.js';
import { makeCollectionManager } from './collectionManager.js';
import { makeWatchedPromiseManager } from './watchedPromises.js';
const SYSCALL_CAPDATA_BODY_SIZE_LIMIT = 10_000_000;
const SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT = 10_000;
const { details: X } = assert;
// 'makeLiveSlots' is a dispatcher which uses javascript Maps to keep track
// of local objects which have been exported. These cannot be persisted
// beyond the runtime of the javascript environment, so this mechanism is not
// going to work for our in-chain hosts.
/**
* Instantiate the liveslots layer for a new vat and then populate the vat with
* a new root object and its initial associated object graph, if any.
*
* @param {*} syscall Kernel syscall interface that the vat will have access to
* @param {*} forVatID Vat ID label, for use in debug diagnostics
* @param {*} vatPowers
* @param {import('./types').LiveSlotsOptions} liveSlotsOptions
* @param {*} gcTools { WeakRef, FinalizationRegistry, waitUntilQuiescent, gcAndFinalize,
* meterControl }
* @param {Pick<Console, 'debug' | 'log' | 'info' | 'warn' | 'error'>} console
* @param {*} buildVatNamespace
*
* @returns {*} { dispatch }
*/
function build(
syscall,
forVatID,
vatPowers,
liveSlotsOptions = {},
gcTools,
console,
buildVatNamespace,
) {
const { enableDisavow = false, relaxDurabilityRules = false } =
liveSlotsOptions;
const { WeakRef, FinalizationRegistry, meterControl } = gcTools;
const enableLSDebug = false;
function lsdebug(...args) {
if (enableLSDebug) {
console.log(...args);
}
}
let didStartVat = false;
const didStopVat = false;
const outstandingProxies = new WeakSet();
let syscallCapdataBodySizeLimit = SYSCALL_CAPDATA_BODY_SIZE_LIMIT;
let syscallCapdataSlotsLengthLimit = SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT;
function setSyscallCapdataLimits(
bodySizeLimit = SYSCALL_CAPDATA_BODY_SIZE_LIMIT,
slotsLengthLimit = SYSCALL_CAPDATA_SLOTS_LENGTH_LIMIT,
) {
syscallCapdataBodySizeLimit = bodySizeLimit;
syscallCapdataSlotsLengthLimit = slotsLengthLimit;
}
function isAcceptableSyscallCapdataSize(capdatas) {
let bodySizeTotal = 0;
let slotsLengthTotal = 0;
for (const capdata of capdatas) {
bodySizeTotal += capdata.body.length;
slotsLengthTotal += capdata.slots.length;
}
return (
bodySizeTotal <= syscallCapdataBodySizeLimit &&
slotsLengthTotal <= syscallCapdataSlotsLengthLimit
);
}
function assertAcceptableSyscallCapdataSize(capdatas) {
assert(
isAcceptableSyscallCapdataSize(capdatas),
'syscall capdata too large',
);
}
/**
* Translation and tracking tables to map in-vat object/promise references
* to/from vat-format slot strings.
*
* Exports: pass-by-presence objects (Remotables) in the vat are exported as
* o+NN slots, as are "virtual object" exports. Promises are exported as p+NN
* slots. We retain a strong reference to all exports via the
* `exportedRemotables` Set until the kernel tells us all external references
* have been dropped via dispatch.dropExports, or by some unilateral
* revoke-object operation executed by our user-level code.
*
* Imports: o-NN slots are represented as a Presence. p-NN slots are
* represented as an imported Promise, with the resolver held in an
* additional table (importedPromisesByPromiseID) to handle a future
* incoming resolution message. We retain a weak reference to the Presence,
* and use a FinalizationRegistry to learn when the vat has dropped it, so
* we can notify the kernel. We retain strong references to unresolved
* Promises. When an import is added, the finalizer is added to
* `vreffedObjectRegistry`.
*
* slotToVal is a Map whose keys are slots (strings) and the values are
* WeakRefs. If the entry is present but wr.deref()===undefined (the
* weakref is dead), treat that as if the entry was not present. The same
* slotToVal table is used for both imports and returning exports. The
* subset of those which need to be held strongly (exported objects and
* promises, imported promises) are kept alive by `exportedRemotables`.
*
* valToSlot is a WeakMap whose keys are Remotable/Presence/Promise
* objects, and the keys are (string) slot identifiers. This is used
* for both exports and returned imports.
*
* We use two weak maps plus the strong `exportedRemotables` set, because
* it seems simpler than using four separate maps (import-vs-export times
* strong-vs-weak).
*/
/** @type {WeakMap<object, string>} */
const valToSlot = new WeakMap(); // object -> vref
const slotToVal = new Map(); // baseRef -> WeakRef(object)
const exportedRemotables = new Set(); // objects
const kernelRecognizableRemotables = new Set(); // vrefs
const importedDevices = new Set(); // device nodes
const possiblyDeadSet = new Set(); // baseRefs that need to be checked for being dead
const possiblyRetiredSet = new Set(); // vrefs that might need to be rechecked for being retired
// importedVPIDs and exportedVPIDs track all promises which the
// kernel knows about: the kernel is the decider for importedVPIDs,
// and we are the decider for exportedVPIDs
// We do not need to include the ancillary promises that
// resolutionCollector() creates: those are resolved immediately
// after export. However we remove those during resolution just in
// case they overlap with non-ancillary ones.
const exportedVPIDs = new Map(); // VPID -> Promise, kernel-known, vat-decided
const importedVPIDs = new Map(); // VPID -> { promise, resolve, reject }, kernel-known+decided
function retainExportedVref(vref) {
// if the vref corresponds to a Remotable, keep a strong reference to it
// until the kernel tells us to release it
const { type, allocatedByVat, virtual, durable } = parseVatSlot(vref);
if (type === 'object' && allocatedByVat) {
if (virtual || durable) {
// eslint-disable-next-line no-use-before-define
vrm.setExportStatus(vref, 'reachable');
} else {
// eslint-disable-next-line no-use-before-define
const remotable = requiredValForSlot(vref);
exportedRemotables.add(remotable);
kernelRecognizableRemotables.add(vref);
}
}
}
/*
Imports are in one of 5 states: UNKNOWN, REACHABLE, UNREACHABLE,
COLLECTED, FINALIZED. Note that there's no actual state machine with those
values, and we can't observe all of the transitions from JavaScript, but
we can describe what operations could cause a transition, and what our
observations allow us to deduce about the state:
* UNKNOWN moves to REACHABLE when a crank introduces a new import
* userspace holds a reference only in REACHABLE
* REACHABLE moves to UNREACHABLE only during a userspace crank
* UNREACHABLE moves to COLLECTED when GC runs, which queues the finalizer
* COLLECTED moves to FINALIZED when a new turn runs the finalizer
* liveslots moves from FINALIZED to UNKNOWN by syscalling dropImports
convertSlotToVal either imports a vref for the first time, or
re-introduces a previously-seen vref. It transitions from:
* UNKNOWN to REACHABLE by creating a new Presence
* UNREACHABLE to REACHABLE by re-using the old Presence that userspace
forgot about
* COLLECTED/FINALIZED to REACHABLE by creating a new Presence
Our tracking tables hold data that depends on the current state:
* slotToVal holds a WeakRef in [REACHABLE, UNREACHABLE, COLLECTED]
* that WeakRef .deref()s into something in [REACHABLE, UNREACHABLE]
* deadSet holds the vref only in FINALIZED
* re-introduction must ensure the vref is not in the deadSet
Each state thus has a set of perhaps-measurable properties:
* UNKNOWN: slotToVal[baseRef] is missing, baseRef not in deadSet
* REACHABLE: slotToVal has live weakref, userspace can reach
* UNREACHABLE: slotToVal has live weakref, userspace cannot reach
* COLLECTED: slotToVal[baseRef] has dead weakref
* FINALIZED: slotToVal[baseRef] is missing, baseRef is in deadSet
Our finalizer callback is queued by the engine's transition from
UNREACHABLE to COLLECTED, but the baseRef might be re-introduced before the
callback has a chance to run. There might even be multiple copies of the
finalizer callback queued. So the callback must deduce the current state
and only perform cleanup (i.e. delete the slotToVal entry and add the
baseRef to the deadSet) in the COLLECTED state.
*/
function finalizeDroppedObject(baseRef) {
// TODO: Ideally this function should assert that it is not metered. This
// appears to be fine in practice, but it breaks a number of unit tests in
// ways that are not obvious how to fix.
// meterControl.assertNotMetered();
const wr = slotToVal.get(baseRef);
// The finalizer for a given Presence might run in any state:
// * COLLECTED: most common. Action: move to FINALIZED
// * REACHABLE/UNREACHABLE: after re-introduction. Action: ignore
// * FINALIZED: after re-introduction and subsequent finalizer invocation
// (second finalizer executed for the same baseRef). Action: be idempotent
// * UNKNOWN: after re-introduction, multiple finalizer invocation,
// and post-crank cleanup does dropImports and deletes baseRef from
// deadSet. Action: ignore
if (wr && !wr.deref()) {
// we're in the COLLECTED state, or FINALIZED after a re-introduction
// eslint-disable-next-line no-use-before-define
addToPossiblyDeadSet(baseRef);
slotToVal.delete(baseRef);
}
}
const vreffedObjectRegistry = new FinalizationRegistry(finalizeDroppedObject);
async function scanForDeadObjects() {
// `possiblyDeadSet` accumulates vrefs which have lost a supporting
// pillar (in-memory, export, or virtualized data refcount) since the
// last call to scanForDeadObjects. The vref might still be supported
// by a remaining pillar, or the pillar which was dropped might be back
// (e.g., given a new in-memory manifestation).
const importsToDrop = new Set();
const importsToRetire = new Set();
const exportsToRetire = new Set();
let doMore;
await null;
do {
doMore = false;
await gcTools.gcAndFinalize();
// possiblyDeadSet contains a baseref for everything (Presences,
// Remotables, Representatives) that might have lost a
// pillar. The object might still be supported by other pillars,
// and the lost pillar might have been reinstantiated by the
// time we get here. The first step is to filter this down to a
// list of definitely dead baserefs.
const deadSet = new Set();
for (const baseRef of possiblyDeadSet) {
// eslint-disable-next-line no-use-before-define
if (slotToVal.has(baseRef)) {
continue; // RAM pillar remains
}
const { virtual, durable, type } = parseVatSlot(baseRef);
assert(type === 'object', `unprepared to track ${type}`);
if (virtual || durable) {
// eslint-disable-next-line no-use-before-define
if (vrm.isVirtualObjectReachable(baseRef)) {
continue; // vdata or export pillar remains
}
}
deadSet.add(baseRef);
}
possiblyDeadSet.clear();
// deadSet now contains objects which are certainly dead
// possiblyRetiredSet holds (a subset of??) baserefs which have
// lost a recognizer recently. TODO recheck this
for (const vref of possiblyRetiredSet) {
// eslint-disable-next-line no-use-before-define
if (!getValForSlot(vref) && !deadSet.has(vref)) {
// Don't retire things that haven't yet made the transition to dead,
// i.e., always drop before retiring
// eslint-disable-next-line no-use-before-define
if (!vrm.isVrefRecognizable(vref)) {
importsToRetire.add(vref);
}
}
}
possiblyRetiredSet.clear();
const deadBaseRefs = Array.from(deadSet);
deadBaseRefs.sort();
for (const baseRef of deadBaseRefs) {
const { virtual, durable, allocatedByVat, type } =
parseVatSlot(baseRef);
type === 'object' || Fail`unprepared to track ${type}`;
if (virtual || durable) {
// Representative: send nothing, but perform refcount checking
// eslint-disable-next-line no-use-before-define
const [gcAgain, retirees] = vrm.deleteVirtualObject(baseRef);
if (retirees) {
retirees.map(retiree => exportsToRetire.add(retiree));
}
doMore = doMore || gcAgain;
} else if (allocatedByVat) {
// Remotable: send retireExport
// for remotables, vref === baseRef
if (kernelRecognizableRemotables.has(baseRef)) {
kernelRecognizableRemotables.delete(baseRef);
exportsToRetire.add(baseRef);
}
} else {
// Presence: send dropImport unless reachable by VOM
// eslint-disable-next-line no-lonely-if, no-use-before-define
if (!vrm.isPresenceReachable(baseRef)) {
importsToDrop.add(baseRef);
// eslint-disable-next-line no-use-before-define
if (!vrm.isVrefRecognizable(baseRef)) {
// for presences, baseRef === vref
importsToRetire.add(baseRef);
}
}
}
}
} while (possiblyDeadSet.size > 0 || possiblyRetiredSet.size > 0 || doMore);
if (importsToDrop.size) {
syscall.dropImports(Array.from(importsToDrop).sort());
}
if (importsToRetire.size) {
syscall.retireImports(Array.from(importsToRetire).sort());
}
if (exportsToRetire.size) {
syscall.retireExports(Array.from(exportsToRetire).sort());
}
}
/**
* Remember disavowed Presences which will kill the vat if you try to talk
* to them
*/
const disavowedPresences = new WeakSet();
const disavowalError = harden(Error(`this Presence has been disavowed`));
function makeImportedPresence(slot, iface = `Alleged: presence ${slot}`) {
// Called by convertSlotToVal for type=object (an `o-NN` reference). We
// build a Presence for application-level code to receive. This Presence
// is associated with 'slot' so that all handled messages get sent to
// that slot: pres~.foo() causes a syscall.send(target=slot, msg=foo).
lsdebug(`makeImportedPresence(${slot})`);
const fulfilledHandler = {
applyMethod(o, prop, args, returnedP) {
// Support: o~.[prop](...args) remote method invocation
lsdebug(`makeImportedPresence handler.applyMethod (${slot})`);
if (disavowedPresences.has(o)) {
// eslint-disable-next-line no-use-before-define
exitVatWithFailure(disavowalError);
throw disavowalError;
}
// eslint-disable-next-line no-use-before-define
return queueMessage(slot, prop, args, returnedP);
},
applyFunction(o, args, returnedP) {
return fulfilledHandler.applyMethod(o, undefined, args, returnedP);
},
get(o, prop) {
lsdebug(`makeImportedPresence handler.get (${slot})`);
if (disavowedPresences.has(o)) {
// eslint-disable-next-line no-use-before-define
exitVatWithFailure(disavowalError);
throw disavowalError;
}
// FIXME: Actually use remote property lookup
return o[prop];
},
};
let remotePresence;
const p = new HandledPromise((_res, _rej, resolveWithPresence) => {
// Use Remotable rather than Far to make a remote from a presence
remotePresence = Remotable(
iface,
undefined,
resolveWithPresence(fulfilledHandler),
);
// remote === presence, actually
// todo: mfig says resolveWithPresence
// gives us a Presence, Remotable gives us a Remote. I think that
// implies we have a lot of renaming to do, 'makeRemote' instead of
// 'makeImportedPresence', etc. I'd like to defer that for a later
// cleanup/renaming pass.
}); // no unfulfilledHandler
// The call to resolveWithPresence performs the forwarding logic
// immediately, so by the time we reach here, E(presence).foo() will use
// our fulfilledHandler, and nobody can observe the fact that we failed
// to provide an unfulfilledHandler.
// We throw 'p' away, but it is retained by the internal tables of
// HandledPromise, and will be returned to anyone who calls
// `HandledPromise.resolve(presence)`. So we must harden it now, for
// safety, to prevent it from being used as a communication channel
// between isolated objects that share a reference to the Presence.
void harden(p);
// Up at the application level, presence~.foo(args) starts by doing
// HandledPromise.resolve(presence), which retrieves it, and then does
// p.eventualSend('foo', [args]), which uses the fulfilledHandler.
// We harden the presence for the same safety reasons.
return harden(remotePresence);
}
function makePipelinablePromise(vpid) {
// Called by convertSlotToVal(type=promise) for incoming promises (a
// `p-NN` reference), and by queueMessage() for the result of an outbound
// message (a `p+NN` reference). We build a Promise for application-level
// code, to which messages can be pipelined, and we prepare for the
// kernel to tell us that it has been resolved in various ways.
insistVatType('promise', vpid);
lsdebug(`makePipelinablePromise(${vpid})`);
// The Promise will we associated with a handler that converts p~.foo() into
// a syscall.send() that targets the vpid. When the Promise is resolved
// (during receipt of a dispatch.notify), this Promise's handler will be
// replaced by the handler of the resolution, which might be a Presence or a
// local object.
// for safety as we shake out bugs in HandledPromise, we guard against
// this handler being used after it was supposed to be resolved
let handlerActive = true;
const unfulfilledHandler = {
applyMethod(_p, prop, args, returnedP) {
// Support: p~.[prop](...args) remote method invocation
lsdebug(`makePipelinablePromise handler.applyMethod (${vpid})`);
if (!handlerActive) {
console.error(`mIPromise handler called after resolution`);
Fail`mIPromise handler called after resolution`;
}
// eslint-disable-next-line no-use-before-define
return queueMessage(vpid, prop, args, returnedP);
},
get(p, prop) {
// Support: p~.[prop]
lsdebug(`makePipelinablePromise handler.get (${vpid})`);
if (!handlerActive) {
console.error(`mIPromise handler called after resolution`);
Fail`mIPromise handler called after resolution`;
}
// FIXME: Actually pipeline.
return E.when(p, o => o[prop]);
},
};
let resolve;
let reject;
const p = new HandledPromise((res, rej, _resPres) => {
resolve = res;
reject = rej;
}, unfulfilledHandler);
// Prepare for the kernel to tell us about resolution. Both ensure the
// old handler should never be called again. TODO: once we're confident
// about how we interact with HandledPromise, just use harden({ resolve,
// reject }).
const pRec = harden({
promise: p,
resolve(resolution) {
handlerActive = false;
resolve(resolution);
},
reject(rejection) {
handlerActive = false;
reject(rejection);
},
});
return pRec;
}
function makeDeviceNode(id, iface = `Alleged: device ${id}`) {
return Remotable(iface);
}
// TODO: fix awkward non-orthogonality: allocateExportID() returns a number,
// allocatePromiseID() returns a slot, registerPromise() uses the slot from
// allocatePromiseID(), exportPassByPresence() generates a slot itself using
// the number from allocateExportID(). Both allocateX fns should return a
// number or return a slot; both exportY fns should either create a slot or
// use a slot from the corresponding allocateX
function allocateExportID() {
// eslint-disable-next-line no-use-before-define
return vrm.allocateNextID('exportID');
}
function allocateCollectionID() {
// eslint-disable-next-line no-use-before-define
return vrm.allocateNextID('collectionID');
}
function allocatePromiseID() {
// eslint-disable-next-line no-use-before-define
const promiseID = vrm.allocateNextID('promiseID');
return makeVatSlot('promise', true, promiseID);
}
const knownResolutions = new WeakMap();
/**
* Determines if a vref from a watched promise or outbound argument
* identifies a promise that should be exported, and if so then
* adds it to exportedVPIDs and sets up handlers.
*
* @param {any} vref
* @returns {boolean} whether the vref was added to exportedVPIDs
*/
function maybeExportPromise(vref) {
// we only care about new vpids
if (
parseVatSlot(vref).type === 'promise' &&
!exportedVPIDs.has(vref) &&
!importedVPIDs.has(vref)
) {
const vpid = vref;
// The kernel is about to learn about this promise (syscall.send
// arguments or syscall.resolve resolution data), so prepare to
// do a syscall.resolve when it fires. The caller must finish
// doing their syscall before this turn finishes, to ensure the
// kernel isn't surprised by a spurious resolution.
// eslint-disable-next-line no-use-before-define
const p = requiredValForSlot(vpid);
// if (!knownResolutions.has(p)) { // TODO really?
// eslint-disable-next-line no-use-before-define
followForKernel(vpid, p);
return true;
}
return false;
}
function exportPassByPresence() {
const exportID = allocateExportID();
return makeVatSlot('object', true, exportID);
}
// eslint-disable-next-line no-use-before-define
const m = makeMarshal(convertValToSlot, convertSlotToVal, {
marshalName: `liveSlots:${forVatID}`,
serializeBodyFormat: 'smallcaps',
// TODO Temporary hack.
// See https://github.com/Agoric/agoric-sdk/issues/2780
errorIdNum: 70000,
marshalSaveError: err =>
// By sending this to `console.warn`, under cosmic-swingset this is
// controlled by the `console` option given to makeLiveSlots.
console.warn('Logging sent error stack', err),
});
const unmeteredUnserialize = meterControl.unmetered(m.unserialize);
// eslint-disable-next-line no-use-before-define
const unmeteredConvertSlotToVal = meterControl.unmetered(convertSlotToVal);
function getSlotForVal(val) {
return valToSlot.get(val);
}
function getValForSlot(baseRef) {
meterControl.assertNotMetered();
const wr = slotToVal.get(baseRef);
return wr && wr.deref();
}
function requiredValForSlot(baseRef) {
const wr = slotToVal.get(baseRef);
const result = wr && wr.deref();
result || Fail`no value for ${baseRef}`;
return result;
}
function addToPossiblyDeadSet(baseRef) {
possiblyDeadSet.add(baseRef);
}
function addToPossiblyRetiredSet(vref) {
possiblyRetiredSet.add(vref);
}
const vrm = makeVirtualReferenceManager(
syscall,
getSlotForVal,
requiredValForSlot,
FinalizationRegistry,
WeakRef,
addToPossiblyDeadSet,
addToPossiblyRetiredSet,
relaxDurabilityRules,
);
const vom = makeVirtualObjectManager(
syscall,
vrm,
allocateExportID,
getSlotForVal,
requiredValForSlot,
// eslint-disable-next-line no-use-before-define
registerValue,
m.serialize,
unmeteredUnserialize,
assertAcceptableSyscallCapdataSize,
liveSlotsOptions,
);
const collectionManager = makeCollectionManager(
syscall,
vrm,
allocateExportID,
allocateCollectionID,
// eslint-disable-next-line no-use-before-define
convertValToSlot,
unmeteredConvertSlotToVal,
// eslint-disable-next-line no-use-before-define
registerValue,
m.serialize,
unmeteredUnserialize,
assertAcceptableSyscallCapdataSize,
);
const watchedPromiseManager = makeWatchedPromiseManager({
syscall,
vrm,
vom,
collectionManager,
// eslint-disable-next-line no-use-before-define
convertValToSlot,
convertSlotToVal: unmeteredConvertSlotToVal,
maybeExportPromise,
});
function convertValToSlot(val) {
// lsdebug(`serializeToSlot`, val, Object.isFrozen(val));
// This is either a Presence (in presenceToImportID), a
// previously-serialized local pass-by-presence object or
// previously-serialized local Promise (in valToSlot), a new local
// pass-by-presence object, or a new local Promise.
// If we've already assigned it an importID or exportID, it might be in
// slots/slotMap for this particular act of serialization. If it's new,
// it certainly will not be in slotMap. If we've already serialized it in
// this particular act, it will definitely be in slotMap.
if (!valToSlot.has(val)) {
let slot;
// must be a new export/store
// lsdebug('must be a new export', JSON.stringify(val));
if (isPromise(val)) {
// the promise either appeared in outbound arguments, or in a
// virtual-object store operation, so immediately after
// serialization we'll either add it to exportedVPIDs or
// increment a vdata refcount
slot = allocatePromiseID();
} else {
if (disavowedPresences.has(val)) {
// eslint-disable-next-line no-use-before-define
exitVatWithFailure(disavowalError);
throw disavowalError; // cannot reference a disavowed object
}
assert.equal(passStyleOf(val), 'remotable');
slot = exportPassByPresence();
}
const { type, baseRef } = parseVatSlot(slot); // also used as assertion
valToSlot.set(val, slot);
slotToVal.set(baseRef, new WeakRef(val));
if (type === 'object') {
// Set.delete() metering seems unaffected by presence/absence, but it
// doesn't matter anyway because deadSet.add only happens when
// finializers run, and we wrote xsnap.c to ensure they only run
// deterministically (during gcAndFinalize)
vreffedObjectRegistry.register(val, baseRef, val);
}
}
return valToSlot.get(val);
}
let importedPromises = null;
function beginCollectingPromiseImports() {
importedPromises = new Set();
}
function finishCollectingPromiseImports() {
const result = importedPromises;
importedPromises = null;
return result;
}
function registerValue(baseRef, val, valIsCohort) {
const { type, id, facet } = parseVatSlot(baseRef);
!facet ||
Fail`registerValue(${baseRef} should not receive individual facets`;
slotToVal.set(baseRef, new WeakRef(val));
if (valIsCohort) {
for (const [index, name] of vrm.getFacetNames(id).entries()) {
valToSlot.set(val[name], `${baseRef}:${index}`);
}
} else {
valToSlot.set(val, baseRef);
}
// we don't dropImports on promises, to avoid interaction with retire
if (type === 'object') {
vreffedObjectRegistry.register(val, baseRef, val);
}
}
// The meter usage of convertSlotToVal is strongly affected by GC, because
// it only creates a new Presence if one does not already exist. Userspace
// moves from REACHABLE to UNREACHABLE, but the JS engine then moves to
// COLLECTED (and maybe FINALIZED) on its own, and we must not allow the
// latter changes to affect metering. So every call to convertSlotToVal (or
// m.unserialize) must be wrapped by unmetered().
function convertSlotToVal(slot, iface = undefined) {
meterControl.assertNotMetered();
const { type, allocatedByVat, id, virtual, durable, facet, baseRef } =
parseVatSlot(slot);
let val = getValForSlot(baseRef);
if (val) {
if (virtual || durable) {
if (facet !== undefined) {
return vrm.getFacet(id, val, facet);
}
}
return val;
}
let result;
if (virtual || durable) {
assert.equal(type, 'object');
try {
val = vrm.reanimate(baseRef);
} catch (err) {
const wrappedError = assert.error(X`failed to reanimate ${iface}`);
assert.note(wrappedError, X`Original error: ${err}`);
throw wrappedError;
}
if (facet !== undefined) {
result = vrm.getFacet(id, val, facet);
}
} else {
!allocatedByVat || Fail`I don't remember allocating ${slot}`;
if (type === 'object') {
// this is a new import value
val = makeImportedPresence(slot, iface);
} else if (type === 'promise') {
const pRec = makePipelinablePromise(slot);
importedVPIDs.set(slot, pRec);
val = pRec.promise;
// ideally we'd wait until .then is called on p before subscribing,
// but the current Promise API doesn't give us a way to discover
// this, so we must subscribe right away. If we were using Vows or
// some other then-able, we could just hook then() to notify us.
if (importedPromises) {
// leave the subscribe() up to dispatch.notify()
importedPromises.add(slot);
} else {
// probably in dispatch.deliver(), so subscribe now
syscall.subscribe(slot);
}
} else if (type === 'device') {
val = makeDeviceNode(slot, iface);
importedDevices.add(val);
} else {
Fail`unrecognized slot type '${type}'`;
}
}
registerValue(baseRef, val, facet !== undefined);
if (!result) {
result = val;
}
return result;
}
function revivePromise(slot) {
meterControl.assertNotMetered();
const { type } = parseVatSlot(slot);
type === 'promise' || Fail`revivePromise called on non-promise ${slot}`;
!getValForSlot(slot) || Fail`revivePromise called on pre-existing ${slot}`;
const pRec = makePipelinablePromise(slot);
importedVPIDs.set(slot, pRec);
const p = pRec.promise;
registerValue(slot, p);
return p;
}
const unmeteredRevivePromise = meterControl.unmetered(revivePromise);
function resolutionCollector() {
const resolutions = [];
const doneResolutions = new Set();
function scanSlots(slots) {
for (const slot of slots) {
const { type } = parseVatSlot(slot);
if (type === 'promise') {
// this can run metered because it's supposed to always be present
const p = requiredValForSlot(slot);
const priorResolution = knownResolutions.get(p);
if (priorResolution && !doneResolutions.has(slot)) {
const [priorRejected, priorRes] = priorResolution;
// eslint-disable-next-line no-use-before-define
collect(slot, priorRejected, priorRes);
}
}
}
}
function collect(promiseID, rejected, value) {
doneResolutions.add(promiseID);
meterControl.assertIsMetered(); // else userspace getters could escape
let valueSer;
try {
valueSer = m.serialize(value);
} catch (e) {
// Serialization failure.
valueSer = m.serialize(e);
rejected = true;
}
valueSer.slots.map(retainExportedVref);
// do maybeExportPromise() next to the syscall, not here
resolutions.push([promiseID, rejected, valueSer]);
scanSlots(valueSer.slots);
}
function forPromise(promiseID, rejected, value) {
collect(promiseID, rejected, value);
return resolutions;
}
function forSlots(slots) {
scanSlots(slots);
return resolutions;
}
return {
forPromise,
forSlots,
};
}
function queueMessage(targetSlot, prop, args, returnedP) {
const methargs = [prop, args];
meterControl.assertIsMetered(); // else userspace getters could escape
const serMethargs = m.serialize(harden(methargs));
assertAcceptableSyscallCapdataSize([serMethargs]);
serMethargs.slots.map(retainExportedVref);
const resultVPID = allocatePromiseID();
lsdebug(`Promise allocation ${forVatID}:${resultVPID} in queueMessage`);
// create a Promise which callers follow for the result, give it a
// handler so we can pipeline messages to it, and prepare for the kernel
// to notify us of its resolution
const pRec = makePipelinablePromise(resultVPID);
// userspace sees `returnedP` (so that's what we need to register
// in slotToVal, and what's what we need to retain with a strong
// reference via importedVPIDs), but when dispatch.notify arrives,
// we need to fire `pRec.promise` because that's what we've got
// the firing controls for
importedVPIDs.set(resultVPID, harden({ ...pRec, promise: returnedP }));
valToSlot.set(returnedP, resultVPID);
slotToVal.set(resultVPID, new WeakRef(returnedP));
// prettier-ignore
lsdebug(
`ls.qm send(${JSON.stringify(targetSlot)}, ${legibilizeMethod(prop)}) -> ${resultVPID}`,
);
syscall.send(targetSlot, serMethargs, resultVPID);
// The vpids in the syscall.send might be in A:exportedVPIDs,
// B:importedVPIDs, or C:neither. Just after the send(), we are
// newly on the hook for following the ones in C:neither. One
// option would be to feed all the syscall.send slots to
// maybeExportPromise(), which will sort them into A/B/C, then
// take everything in C:neither and do a .then on it and add it to
// exportedVPIDs. Then we call it a day, and allow all the
// resolutions to be delivered in a later turn.
//
// But instead, we choose the option that says "but many of those
// promises might already be resolved", and if there's more than
// one, we could amortize some syscall overhead by emitting all
// the known resolutions in a 2-or-larger batch, and in this
// moment (in this turn) we have a whole list of them that we can
// check synchronously.
//
// To implement this option, the sequence is:
// * use W to name the vpids in syscall.send
// * feed W into resolutionCollector(), to get 'resolutions'
// * that provides the resolution of any promise in W that is
// known to be resolved, plus any known-resolved promises
// transitively referenced through their resolution data
// * all these resolutions will use the original vpid, which the
// kernel does not currently know about, because the vpid was
// retired earlier, the previous time that promise was
// resolved
// * name X the set of vpids resolved in 'resolutions'
// * assert that X vpids are not in exportedVPIDs or importedVPIDs
// * they can only be in X if we remembered the Promise's
// resolution, which means we observed the vpid resolve
// * at that moment of observation, we would have removed it
// from exportedVPIDs, as we did a syscall.resolve on it
// * name Y the set of vpids *referenced* by 'resolutions'
// * emit syscall.resolve(resolutions)
// * Z = (W+Y)-X: the set of vpids we told the kernel but didn't resolve
// * feed Z into maybeExportPromise()
const maybeNewVPIDs = new Set(serMethargs.slots);
const resolutions = resolutionCollector().forSlots(serMethargs.slots);
if (resolutions.length > 0) {
try {
const resolutionCDs = resolutions.map(
([_xvpid, _isReject, resolutionCD]) => resolutionCD,
);
assertAcceptableSyscallCapdataSize(resolutionCDs);
} catch (e) {
syscall.exit(true, m.serialize(e));
return null;
}
syscall.resolve(resolutions);
for (const resolution of resolutions) {
const [_xvpid, _isReject, resolutionCD] = resolution;
for (const vref of resolutionCD.slots) {
maybeNewVPIDs.add(vref);
}
}
for (const resolution of resolutions) {
const [xvpid] = resolution;
maybeNewVPIDs.delete(xvpid);
}
}
for (const newVPID of Array.from(maybeNewVPIDs).sort()) {
maybeExportPromise(newVPID);
}
// ideally we'd wait until .then is called on p before subscribing, but
// the current Promise API doesn't give us a way to discover this, so we
// must subscribe right away. If we were using Vows or some other
// then-able, we could just hook then() to notify us.
syscall.subscribe(resultVPID);
// We return our new 'pRec.promise' to the handler, and when we
// resolve it (during dispatch.notify) its resolution will be used
// to resolve the caller's 'returnedP' Promise, but the caller
// never sees pRec.promise itself. The caller got back their
// 'returnedP' Promise before the handler even got invoked, and
// thus before this queueMessage() was called.. If that caller
// passes the 'returnedP' Promise they received as argument or
// return value, we want it to serialize as resultVPID. And if
// someone passes resultVPID to them, we want the user-level code
// to get back that Promise, not 'pRec.promise'. As a result, we
// do not retain or track 'pRec.promise'. Only 'returnedP' is
// registered and retained by importedVPIDs.
return pRec.promise;
}
function forbidPromises(serArgs) {
for (const slot of serArgs.slots) {
parseVatSlot(slot).type !== 'promise' ||
Fail`D() arguments cannot include a Promise`;
}
}
function DeviceHandler(slot) {
return {
get(target, prop) {
if (typeof prop !== 'string' && typeof prop !== 'symbol') {
return undefined;
}
return (...args) => {
meterControl.assertIsMetered(); // userspace getters shouldn't escape
const serArgs = m.serialize(harden(args));
assertAcceptableSyscallCapdataSize([serArgs]);
serArgs.slots.map(retainExportedVref);
// if we didn't forbid promises, we'd need to
// maybeExportPromise() here
forbidPromises(serArgs);
const ret = syscall.callNow(slot, prop, serArgs);
insistCapData(ret);
forbidPromises(ret);
// but the unserialize must be unmetered, to prevent divergence