-
Notifications
You must be signed in to change notification settings - Fork 212
/
kernel.js
2006 lines (1836 loc) · 72.2 KB
/
kernel.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
import { assert, Fail } from '@agoric/assert';
import { isNat } from '@endo/nat';
import { importBundle } from '@endo/import-bundle';
import { makeUpgradeDisconnection } from '@agoric/internal/src/upgrade-api.js';
import { assertKnownOptions } from '../lib/assertOptions.js';
import { foreverPolicy } from '../lib/runPolicies.js';
import { kser, kslot, makeError } from '../lib/kmarshal.js';
import { makeVatManagerFactory } from './vat-loader/manager-factory.js';
import { makeVatWarehouse } from './vat-warehouse.js';
import makeDeviceManager from './deviceManager.js';
import makeKernelKeeper from './state/kernelKeeper.js';
import {
kdebug,
kdebugEnable,
legibilizeMessageArgs,
extractMethod,
} from '../lib/kdebug.js';
import { insistKernelType, parseKernelSlot } from './parseKernelSlots.js';
import { parseVatSlot } from '../lib/parseVatSlots.js';
import { extractSingleSlot, insistCapData } from '../lib/capdata.js';
import { insistMessage, insistVatDeliveryResult } from '../lib/message.js';
import { insistDeviceID, insistVatID } from '../lib/id.js';
import { updateWorkerOptions } from '../lib/workerOptions.js';
import { makeVatOptionRecorder } from '../lib/recordVatOptions.js';
import { makeKernelQueueHandler } from './kernelQueue.js';
import { makeKernelSyscallHandler } from './kernelSyscall.js';
import { makeSlogger, makeDummySlogger } from './slogger.js';
import { makeDummyMeterControl } from './dummyMeterControl.js';
import { getKpidsToRetire } from './cleanup.js';
import { processGCActionSet } from './gc-actions.js';
import { makeVatLoader } from './vat-loader/vat-loader.js';
import { makeDeviceTranslators } from './deviceTranslator.js';
import { notifyTermination } from './notifyTermination.js';
import { makeVatAdminHooks } from './vat-admin-hooks.js';
/**
* @typedef {import('@agoric/swingset-liveslots').VatDeliveryObject} VatDeliveryObject
* @typedef {import('@agoric/swingset-liveslots').VatDeliveryResult} VatDeliveryResult
* @typedef {import('@agoric/swingset-liveslots').VatSyscallObject} VatSyscallObject
* @typedef {import('@agoric/swingset-liveslots').VatSyscallResult} VatSyscallResult
*/
function abbreviateReplacer(_, arg) {
if (typeof arg === 'bigint') {
return Number(arg);
}
if (typeof arg === 'string' && arg.length >= 40) {
// truncate long strings
return `${arg.slice(0, 15)}...${arg.slice(arg.length - 15)}`;
}
return arg;
}
/**
* Provide the kref of a vat's root object, as if it had been exported.
*
* @param {*} kernelKeeper Kernel keeper managing persistent kernel state.
* @param {string} vatID Vat ID of the vat whose root kref is sought.
*
* @returns {string} the kref of the root object of the given vat.
*/
export function exportRootObject(kernelKeeper, vatID) {
insistVatID(vatID);
const vatKeeper = kernelKeeper.provideVatKeeper(vatID);
return vatKeeper.mapVatSlotToKernelSlot('o+0');
}
/*
* Pretend that a vat just exported an object, and increment the refcount on
* the resulting kref so nothing tries to delete it for being unreferenced.
*/
export function doAddExport(kernelKeeper, fromVatID, vref) {
insistVatID(fromVatID);
assert(parseVatSlot(vref).allocatedByVat);
const vatKeeper = kernelKeeper.provideVatKeeper(fromVatID);
const kref = vatKeeper.mapVatSlotToKernelSlot(vref);
// we lie to incrementRefCount (this is really an export, but we pretend
// it's an import) so it will actually increment the count
kernelKeeper.incrementRefCount(kref, 'doAddExport', { isExport: false });
return kref;
}
export default function buildKernel(
kernelEndowments,
deviceEndowments,
kernelRuntimeOptions = {},
) {
const {
waitUntilQuiescent,
kernelStorage,
debugPrefix,
vatEndowments,
slogCallbacks = {},
makeConsole,
startSubprocessWorkerNode,
startXSnap,
writeSlogObject,
WeakRef,
FinalizationRegistry,
gcAndFinalize,
bundleHandler,
} = kernelEndowments;
deviceEndowments = { ...deviceEndowments }; // copy so we can modify
const {
verbose,
warehousePolicy,
overrideVatManagerOptions = {},
} = kernelRuntimeOptions;
const logStartup = verbose ? console.debug : () => 0;
const vatAdminRootKref = kernelStorage.kvStore.get('vatAdminRootKref');
/** @type { KernelSlog } */
const kernelSlog = writeSlogObject
? makeSlogger(slogCallbacks, writeSlogObject)
: makeDummySlogger(slogCallbacks, makeConsole('disabled slogger'));
const kernelKeeper = makeKernelKeeper(kernelStorage, kernelSlog);
/** @type {ReturnType<makeVatWarehouse>} */
let vatWarehouse;
let started = false;
/**
* @typedef {{
* manager: unknown,
* translators: ReturnType<makeDeviceTranslators>,
* }} DeviceInfo
*/
const ephemeral = {
/** @type { Map<string, DeviceInfo> } key is deviceID */
devices: new Map(),
/** @type {string[]} */
log: [],
};
/**
* @typedef { (args: SwingSetCapData) => SwingSetCapData } DeviceHook
* @typedef { string } HookName
* @typedef { Record<HookName, DeviceHook> } HooksForOneDevice
* @typedef { string } DeviceID
* @typedef { Map<DeviceID, HooksForOneDevice> } HooksForAllDevices
* @type HooksForAllDevices
*/
const deviceHooks = new Map();
const optionRecorder = makeVatOptionRecorder(kernelKeeper, bundleHandler);
// This is a low-level output-only string logger used by old unit tests to
// see whether vats made progress or not. The array it appends to is
// available as c.dump().log . New unit tests should instead use the
// 'result' value returned by c.queueToKref()
function testLog(...args) {
const rendered = args.map(arg =>
typeof arg === 'string' ? arg : JSON.stringify(arg, abbreviateReplacer),
);
ephemeral.log.push(rendered.join(''));
}
harden(testLog);
function makeSourcedConsole(vatID) {
const origConsole = makeConsole(args => {
const source = args.shift();
return `${debugPrefix}SwingSet:${source}:${vatID}`;
});
return kernelSlog.vatConsole(vatID, origConsole);
}
// message flow: vat -> syscall -> acceptanceQueue -> runQueue -> delivery -> vat
// runQueue and acceptanceQueue entries are {type, more..}. 'more' depends on type:
// * send: target, msg
// * notify: vatID, kpid
// * create-vat: vatID, source, dynamicOptions
// in the kernel table, promises and resolvers are both indexed by the same
// value. kernelPromises[promiseID] = { decider, subscribers }
// The "Vat Powers" are given to vats as arguments of setup(). Liveslots
// provides them, and more, as the only argument to buildRootObject(). They
// represent controlled authorities that come from the kernel but that do
// not go through the syscall mechanism (so they aren't included in the
// replay transcript), so they must not be particularly stateful. If any of
// them behave differently from one invocation to the next, the vat code
// which uses it will not be a deterministic function of the transcript,
// breaking our orthogonal-persistence model. They can have access to
// state, but they must not let it influence the data they return to the
// vat.
// These will eventually be provided by the in-worker supervisor instead.
// TODO: ideally the powerless ones are imported by the vat, not passed in
// an argument.
const allVatPowers = harden({
testLog,
});
function vatNameToID(name) {
const vatID = kernelKeeper.getVatIDForName(name);
insistVatID(vatID);
return vatID;
}
function deviceNameToID(name) {
const deviceID = kernelKeeper.getDeviceIDForName(name);
insistDeviceID(deviceID);
return deviceID;
}
function addImport(forVatID, what) {
if (!started) {
throw Error('must do kernel.start() before addImport()');
// because otherwise we can't get the vatManager
}
insistVatID(forVatID);
const kernelSlot = `${what}`;
parseKernelSlot(what);
const vatKeeper = kernelKeeper.provideVatKeeper(forVatID);
return vatKeeper.mapKernelSlotToVatSlot(kernelSlot);
}
function pinObject(kref) {
kernelKeeper.pinObject(kref);
}
function addExport(fromVatID, vatSlot) {
if (!started) {
throw Error('must do kernel.start() before addExport()');
// because otherwise we can't get the vatKeeper
}
return doAddExport(kernelKeeper, fromVatID, vatSlot);
}
// If `kernelPanic` is set to non-null, vat execution code will throw it as an
// error at the first opportunity
let kernelPanic = null;
/** @type {import('../types-internal.js').KernelPanic} */
function panic(problem, err = undefined) {
console.error(`##### KERNEL PANIC: ${problem} #####`);
kernelPanic = err || Error(`kernel panic ${problem}`);
}
const { doSend, doSubscribe, doResolve, resolveToError, queueToKref } =
makeKernelQueueHandler({ kernelKeeper, panic });
/**
* Terminate a vat; that is: delete vat DB state,
* resolve orphaned promises, notify parent, and
* shutdown worker.
*
* @param {string} vatID
* @param {boolean} shouldReject
* @param {SwingSetCapData} info
*/
async function terminateVat(vatID, shouldReject, info) {
const vatKeeper = kernelKeeper.provideVatKeeper(vatID);
const critical = vatKeeper.getOptions().critical;
insistCapData(info);
// ISSUE: terminate stuff in its own crank like creation?
// TODO: if a static vat terminates, panic the kernel?
// TODO: guard against somebody telling vatAdmin to kill a vat twice
// If a vat is terminated during the initial processCreateVat, the
// `abortCrank` will have erased all record of the vat, so this
// check will report 'false'. That's fine, there's no state to
// clean up.
if (kernelKeeper.vatIsAlive(vatID)) {
// Reject all promises decided by the vat, making sure to capture the list
// of kpids before that data is deleted.
const deadPromises = [...kernelKeeper.enumeratePromisesByDecider(vatID)];
kernelKeeper.cleanupAfterTerminatedVat(vatID);
for (const kpid of deadPromises) {
resolveToError(kpid, makeError('vat terminated'), vatID);
}
}
if (critical) {
// The following error construction is a bit awkward, but (1) it saves us
// from doing unmarshaling while in the kernel, while (2) it protects
// against the info not actually encoding an error, but (3) it still
// provides some diagnostic information back to the host, and (4) this
// should happen rarely enough that if you have to do a little bit of
// extra interpretive work on the receiving end to diagnose the problem,
// it's going to be a small cost compared to the trouble you're probably
// already in anyway if this happens.
panic(`critical vat ${vatID} failed`, Error(info.body));
return;
}
if (vatAdminRootKref) {
// static vat termination can happen before vat admin vat exists
notifyTermination(
vatID,
vatAdminRootKref,
shouldReject,
info,
queueToKref,
);
} else {
console.log(
`warning: vat ${vatID} terminated without a vatAdmin to report to`,
);
}
// worker needs to be stopped, if any
await vatWarehouse.stopWorker(vatID);
}
function notifyMeterThreshold(meterID) {
// tell vatAdmin that a meter has dropped below its notifyThreshold
const { remaining } = kernelKeeper.getMeter(meterID);
assert.typeof(vatAdminRootKref, 'string', 'vatAdminRootKref missing');
queueToKref(
vatAdminRootKref,
'meterCrossedThreshold',
[meterID, remaining],
'logFailure',
);
}
// TODO: instead of using a kernel-wide flag here, consider making each
// VatManager responsible for remembering if/when a KernelSyscallResult
// reports a non-'ok' status and therefore the vat is toast. Then the
// delivery handler could ask the manager (or vat-warehouse) afterwards for
// the sticky-fatal state. If we did that, we wouldn't need
// `vatFatalSyscall`. We'd still need a way for `requestTermination` to
// work, though.
// These two flags are reset at the beginning of each
// deliverAndLogToVat, set by syscall implementations, and
// incorporated into the DeliveryStatus result of deliverAndLogToVat
let vatRequestedTermination;
let illegalSyscall;
// this is called for syscall.exit, which allows the crank to complete
// before terminating the vat
function requestTermination(vatID, reject, info) {
insistCapData(info);
vatRequestedTermination = { reject, info };
}
// this is called for vat-fatal syscall errors, which aborts the crank and
// then terminates the vat
function vatFatalSyscall(vatID, problem) {
illegalSyscall = { vatID, info: makeError(problem) };
}
const kernelSyscallHandler = makeKernelSyscallHandler({
kernelKeeper,
ephemeral,
doSend,
doSubscribe,
doResolve,
requestTermination,
deviceHooks,
});
/**
*
* @typedef { import('@agoric/swingset-liveslots').MeterConsumption } MeterConsumption
* @typedef { import('../types-internal.js').MeterID } MeterID
*
* Any delivery crank (send, notify, start-vat.. anything which is allowed
* to make vat delivery) emits one of these status events if a delivery
* actually happened.
*
* @typedef { [string, any[]] } RawMethargs
* @typedef { {
* metering?: MeterConsumption | null, // delivery metering results
* deliveryError?: string, // delivery failed
* illegalSyscall: { vatID: VatID, info: SwingSetCapData } | undefined,
* vatRequestedTermination: { reject: boolean, info: SwingSetCapData } | undefined,
* } } DeliveryStatus
* @typedef { {
* abort?: boolean, // changes should be discarded, not committed
* consumeMessage?: boolean, // discard the aborted delivery
* didDelivery?: VatID, // we made a delivery to a vat, for run policy and save-snapshot
* computrons?: BigInt, // computron count for run policy
* meterID?: string, // deduct those computrons from a meter
* decrementReapCount?: { vatID: VatID }, // the reap counter should decrement
* terminate?: { vatID: VatID, reject: boolean, info: SwingSetCapData }, // terminate vat, notify vat-admin
* vatAdminMethargs?: RawMethargs, // methargs to notify vat-admin about create/upgrade results
* } } CrankResults
*/
const NO_DELIVERY_CRANK_RESULTS = harden({});
/**
* Perform one delivery to a vat.
*
* @param {VatID} vatID
* @param {KernelDeliveryObject} kd
* @param {VatDeliveryObject} vd
*/
async function deliverAndLogToVat(vatID, kd, vd) {
vatRequestedTermination = undefined;
illegalSyscall = undefined;
assert(vatWarehouse.lookup(vatID));
// Ensure that the vatSlogger is available before clist translation.
const vs = kernelSlog.provideVatSlogger(vatID).vatSlog;
await null;
try {
/** @type { VatDeliveryResult } */
const deliveryResult = await vatWarehouse.deliverToVat(vatID, kd, vd, vs);
insistVatDeliveryResult(deliveryResult);
// const [ ok, problem, usage ] = deliveryResult;
/** @type {DeliveryStatus} */
const status = { illegalSyscall, vatRequestedTermination };
// we get metering for all non-throwing deliveries (both 'ok'
// and 'error') except for hard metering faults
status.metering = deliveryResult[2];
if (deliveryResult[0] !== 'ok') {
// kernel-panic -worthy delivery problems (unexpected worker
// exit, pipe problems) are signalled with an exception, so
// non-'ok' status means:
//
// * hard metering fault (E_TOO_MUCH_COMPUTATION or
// E_STACK_OVERFLOW or E_NOT_ENOUGH_MEMORY), and the worker is
// dead
// * a bug in the vat's dispatch() or liveslots, and we
// shouldn't trust the surviving worker
// * Liveslots observed a vat-fatal error, like startVat()
// noticed buildRootObject() did not restore all virtual
// Kinds, and we're not going to use the worker
//
// So in all cases, our caller should abandon the worker.
await vatWarehouse.stopWorker(vatID);
// TODO: does stopWorker work if the worker process just died?
status.deliveryError = deliveryResult[1];
}
return harden(status);
} catch (e) {
// log so we get a stack trace before we panic the kernel
console.error(`error in kernel.deliver:`, e);
throw e;
}
}
/**
* Given the results of a delivery, build a set of instructions for
* finishing up the crank. This is a helper function whose return
* value should be further customized as needed by each run-queue
* event handler.
*
* Two flags influence this:
* `decrementReapCount` is used for deliveries that run userspace code
* `meterID` means we should check a meter
*
* @param {VatID} vatID
* @param {DeliveryStatus} status
* @param {boolean} decrementReapCount
* @param {MeterID} [meterID]
* @returns {CrankResults}
*/
function deliveryCrankResults(vatID, status, decrementReapCount, meterID) {
let meterUnderrun = false;
let computrons;
if (status.metering?.compute) {
computrons = BigInt(status.metering.compute);
}
// TODO metering.allocate, some day
/** @type {CrankResults} */
const results = { didDelivery: vatID, computrons };
if (meterID && computrons) {
results.meterID = meterID; // decrement meter when we're done
if (!kernelKeeper.checkMeter(meterID, computrons)) {
meterUnderrun = true; // vat used too much, oops
}
}
// note: these conditionals express a priority order: the
// consequences of an illegal syscall take precedence over a vat
// requesting termination, etc
if (status.illegalSyscall) {
// For now, vat errors both rewind changes and terminate the
// vat. Some day, they might rewind changes but then suspend the
// vat.
results.abort = true;
const { info } = status.illegalSyscall;
results.terminate = { vatID, reject: true, info };
} else if (status.deliveryError) {
results.abort = true;
const info = makeError(status.deliveryError);
results.terminate = { vatID, reject: true, info };
} else if (meterUnderrun) {
results.abort = true;
const info = makeError('meter underflow, vat terminated');
results.terminate = { vatID, reject: true, info };
} else if (status.vatRequestedTermination) {
if (status.vatRequestedTermination.reject) {
results.abort = true; // vatPowers.exitWithFailure wants rewind
}
results.terminate = { vatID, ...status.vatRequestedTermination };
}
if (decrementReapCount && !(results.abort || results.terminate)) {
results.decrementReapCount = { vatID };
}
// We leave results.consumeMessage up to the caller. Send failures
// never set results.consumeMessage (we allow the delivery to be
// re-attempted and it splats against the now-dead vat, or doesn't
// get delivered until the vat is unsuspended). But failures in
// e.g. startVat will want to set consumeMessage.
return harden(results);
}
/**
* Deliver one message to a vat.
*
* @param {VatID} vatID
* @param {string} target
* @param {Message} msg
* @returns {Promise<CrankResults>}
*/
async function processSend(vatID, target, msg) {
insistMessage(msg);
kernelKeeper.incStat('dispatches');
kernelKeeper.incStat('dispatchDeliver');
const vatInfo = vatWarehouse.lookup(vatID);
assert(vatInfo, 'routeSendEvent() should have noticed dead vat');
const { enablePipelining, meterID } = vatInfo;
/** @type { KernelDeliveryMessage } */
const kd = harden(['message', target, msg]);
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
if (enablePipelining && msg.result) {
// TODO maybe move after deliverAndLogToVat??
kernelKeeper.requeueKernelPromise(msg.result);
}
const status = await deliverAndLogToVat(vatID, kd, vd);
return deliveryCrankResults(vatID, status, true, meterID);
}
/**
*
* @param {RunQueueEventNotify} message
* @returns {Promise<CrankResults>}
*/
async function processNotify(message) {
const { vatID, kpid } = message;
insistVatID(vatID);
insistKernelType('promise', kpid);
kernelKeeper.incStat('dispatches');
const vatInfo = vatWarehouse.lookup(vatID);
if (!vatInfo) {
kdebug(`dropping notify of ${kpid} to ${vatID} because vat is dead`);
return NO_DELIVERY_CRANK_RESULTS;
}
const { meterID } = vatInfo;
const p = kernelKeeper.getKernelPromise(kpid);
kernelKeeper.incStat('dispatchNotify');
const vatKeeper = kernelKeeper.provideVatKeeper(vatID);
p.state !== 'unresolved' || Fail`spurious notification ${kpid}`;
/** @type { KernelDeliveryOneNotify[] } */
const resolutions = [];
if (!vatKeeper.hasCListEntry(kpid)) {
kdebug(`vat ${vatID} has no c-list entry for ${kpid}`);
kdebug(`skipping notify of ${kpid} because it's already been done`);
return NO_DELIVERY_CRANK_RESULTS;
}
const targets = getKpidsToRetire(kernelKeeper, kpid, p.data);
if (targets.length === 0) {
kdebug(`no kpids to retire`);
kdebug(`skipping notify of ${kpid} because it's already been done`);
return NO_DELIVERY_CRANK_RESULTS;
}
for (const toResolve of targets) {
const { state, data } = kernelKeeper.getKernelPromise(toResolve);
resolutions.push([toResolve, { state, data }]);
}
/** @type { KernelDeliveryNotify } */
const kd = harden(['notify', resolutions]);
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
vatKeeper.deleteCListEntriesForKernelSlots(targets);
const status = await deliverAndLogToVat(vatID, kd, vd);
return deliveryCrankResults(vatID, status, true, meterID);
}
/**
*
* @param {RunQueueEventDropExports | RunQueueEventRetireImports | RunQueueEventRetireExports} message
* @returns {Promise<CrankResults>}
*/
async function processGCMessage(message) {
// used for dropExports, retireExports, and retireImports
const { type, vatID, krefs } = message;
// console.log(`-- processGCMessage(${vatID} ${type} ${krefs.join(',')})`);
insistVatID(vatID);
if (!vatWarehouse.lookup(vatID)) {
return NO_DELIVERY_CRANK_RESULTS; // can't collect from the dead
}
/** @type { KernelDeliveryDropExports | KernelDeliveryRetireExports | KernelDeliveryRetireImports } */
const kd = harden([type, krefs]);
if (type === 'retireExports') {
for (const kref of krefs) {
// const rc = kernelKeeper.getObjectRefCount(kref);
// console.log(` ${kref}: ${rc.reachable},${rc.recognizable}`);
kernelKeeper.deleteKernelObject(kref);
// console.log(` deleted ${kref}`);
}
}
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
const status = await deliverAndLogToVat(vatID, kd, vd);
return deliveryCrankResults(vatID, status, false); // no meterID
}
/**
*
* @param {RunQueueEventBringOutYourDead} message
* @returns {Promise<CrankResults>}
*/
async function processBringOutYourDead(message) {
const { type, vatID } = message;
// console.log(`-- processBringOutYourDead(${vatID})`);
insistVatID(vatID);
if (!vatWarehouse.lookup(vatID)) {
return NO_DELIVERY_CRANK_RESULTS; // can't collect from the dead
}
/** @type { KernelDeliveryBringOutYourDead } */
const kd = harden([type]);
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
const status = await deliverAndLogToVat(vatID, kd, vd);
return deliveryCrankResults(vatID, status, false); // no meter
}
/**
* The 'startVat' event is queued by `initializeKernel` for all static vats,
* so that we execute their bundle imports and call their `buildRootObject`
* functions in a transcript context. The consequence of this is that if
* there are N static vats, N 'startVat' events will be the first N events on
* the initial run queue. For dynamic vats, the handler of the 'create-vat'
* event, `processCreateVat`, calls `processStartVat` directly, rather than
* enqueing 'startVat', so that vat startup happens promptly after creation
* and so that there are no intervening events in the run queue between vat
* creation and vat startup (it would probably not be a problem if there were,
* but doing it this way simply guarantees there won't be such a problem
* without requiring any further analysis to be sure).
*
* @param {RunQueueEventStartVat} message
* @returns {Promise<CrankResults>}
*/
async function processStartVat(message) {
const { vatID, vatParameters } = message;
// console.log(`-- processStartVat(${vatID})`);
insistVatID(vatID);
insistCapData(vatParameters);
const vatInfo = vatWarehouse.lookup(vatID);
if (!vatInfo) {
kdebug(`vat ${vatID} terminated before startVat delivered`);
return NO_DELIVERY_CRANK_RESULTS;
}
const { meterID } = vatInfo;
/** @type { KernelDeliveryStartVat } */
const kd = harden(['startVat', vatParameters]);
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
// decref slots now that create-vat is off run-queue
for (const kref of vatParameters.slots) {
kernelKeeper.decrementRefCount(kref, 'create-vat-event');
}
const status = await deliverAndLogToVat(vatID, kd, vd);
// note: if deliveryCrankResults() learns to suspend vats,
// startVat errors should still terminate them
const results = harden({
...deliveryCrankResults(vatID, status, true, meterID),
consumeMessage: true,
});
return results;
}
/**
*
* @param {RunQueueEventCreateVat} message
* @returns {Promise<CrankResults>}
*/
async function processCreateVat(message) {
assert(vatAdminRootKref, `initializeKernel did not set vatAdminRootKref`);
const { vatID, source, vatParameters, dynamicOptions } = message;
insistCapData(vatParameters);
kernelKeeper.addDynamicVatID(vatID);
await optionRecorder.recordDynamic(vatID, source, dynamicOptions);
// createDynamicVat makes the worker, installs lockdown and
// supervisor, but does not load the vat bundle yet. It can fail
// if the options are bad, worker cannot be launched, lockdown or
// supervisor bundles are bad.
try {
await vatWarehouse.createDynamicVat(vatID);
} catch (err) {
console.log('error during createDynamicVat', err);
const info = makeError(`${err}`);
const results = {
didDelivery: vatID, // ok, it failed, but we did spend the time
abort: true, // delete partial vat state
consumeMessage: true, // don't repeat createVat
terminate: { vatID, reject: true, info },
};
return harden(results);
}
// If we managed to make a worker, use processStartVat() to invoke
// dispatch.startVat . The CrankResults it returns may signal an
// error like meter underflow during startVat, or failure to
// redefine all Kinds.
/** @type { RunQueueEventStartVat } */
const startVat = { type: 'startVat', vatID, vatParameters };
const startResults = await processStartVat(startVat);
if (startResults.terminate) {
const consumeMessage = true;
return harden({ ...startResults, consumeMessage });
}
// if the startVat CrankResults were happy, we should report them
// (for meter deductions and runPolicy computrons), but add a
// success message for vat-admin, which also gives it access to
// the new vat's root object
const kernelRootObjSlot = exportRootObject(kernelKeeper, vatID);
const arg = { rootObject: kslot(kernelRootObjSlot) };
/** @type { RawMethargs } */
const vatAdminMethargs = ['newVatCallback', [vatID, arg]];
return harden({ ...startResults, vatAdminMethargs });
}
function setKernelVatOption(vatID, option, value) {
switch (option) {
case 'reapInterval': {
if (value === 'never' || isNat(value)) {
const vatKeeper = kernelKeeper.provideVatKeeper(vatID);
vatKeeper.updateReapInterval(value);
} else {
console.log(`WARNING: invalid reapInterval value`, value);
}
return true;
}
default:
return false;
}
}
/**
*
* @param {RunQueueEventChangeVatOptions} message
* @returns {Promise<CrankResults>}
*/
async function processChangeVatOptions(message) {
const { vatID, options } = message;
insistVatID(vatID);
if (!vatWarehouse.lookup(vatID)) {
return NO_DELIVERY_CRANK_RESULTS; // vat is dead, ignore
}
/** @type { Record<string, unknown> } */
const optionsForVat = {};
let haveOptionsForVat = false;
for (const option of Object.getOwnPropertyNames(options)) {
if (!setKernelVatOption(vatID, option, options[option])) {
optionsForVat[option] = options[option];
haveOptionsForVat = true;
}
}
if (!haveOptionsForVat) {
return NO_DELIVERY_CRANK_RESULTS;
}
/** @type { KernelDeliveryChangeVatOptions } */
const kd = harden(['changeVatOptions', optionsForVat]);
const vd = vatWarehouse.kernelDeliveryToVatDelivery(vatID, kd);
const status = await deliverAndLogToVat(vatID, kd, vd);
const results = deliveryCrankResults(vatID, status, false); // no meter
return harden({ ...results, consumeMessage: true });
}
function addComputrons(computrons1, computrons2) {
if (computrons1 !== undefined) {
assert.typeof(computrons1, 'bigint');
}
if (computrons2 !== undefined) {
assert.typeof(computrons2, 'bigint');
}
// leave undefined if both deliveries lacked numbers
if (computrons1 !== undefined || computrons2 !== undefined) {
return (computrons1 || 0n) + (computrons2 || 0n);
}
return undefined;
}
/**
* @param {RunQueueEventUpgradeVat} message
* @returns {Promise<CrankResults>}
*/
async function processUpgradeVat(message) {
assert(vatAdminRootKref, 'initializeKernel did not set vatAdminRootKref');
const { vatID, upgradeID, bundleID, vatParameters, upgradeMessage } =
message;
insistCapData(vatParameters);
assert.typeof(upgradeMessage, 'string');
const vatInfo = vatWarehouse.lookup(vatID);
if (!vatInfo) {
return NO_DELIVERY_CRANK_RESULTS; // vat terminated already
}
const { meterID } = vatInfo;
let computrons;
const vatKeeper = kernelKeeper.provideVatKeeper(vatID);
const oldIncarnation = vatKeeper.getIncarnationNumber();
const disconnectionObject = makeUpgradeDisconnection(
upgradeMessage,
oldIncarnation,
);
const disconnectionCapData = kser(disconnectionObject);
/**
* Terminate the vat and translate internal-delivery results into
* abort-without-termination results for the upgrade delivery.
*
* @param {CrankResults} badDeliveryResults
* @param {SwingSetCapData} errorCapData
* @returns {Promise<CrankResults>}
*/
const abortUpgrade = async (badDeliveryResults, errorCapData) => {
// get rid of the worker, so the next delivery to this vat will
// re-create one from the previous state
await vatWarehouse.stopWorker(vatID);
// notify vat-admin of the failed upgrade without revealing error details
insistCapData(errorCapData);
// const error = kunser(errorCapData);
const error = Error('vat-upgrade failure');
/** @type {RawMethargs} */
const vatAdminMethargs = [
'vatUpgradeCallback',
[upgradeID, false, error],
];
const results = harden({
...badDeliveryResults,
computrons, // still report computrons
abort: true, // always unwind
consumeMessage: true, // don't repeat the upgrade
terminate: undefined, // do *not* terminate the vat
vatAdminMethargs,
});
return results;
};
// cleanup on behalf of the worker
// This used to be handled by a stopVat delivery to the vat itself,
// but the implementation of that was cut to the bone
// in commits like 91480dee8e48ae26c39c420febf73b93deba6ea5
// basically reverting 1cfbeaa3c925d0f8502edfb313ecb12a1cab5eac
// and then ultimately moved to the kernel in a MUCH diminished form
// (see #5342 and #6650, and testUpgrade in
// {@link ../../test/upgrade/test-upgrade.js}).
// We hope to eventually add back correct sophisticated logic
// by e.g. having liveslots sweep the database when restoring a vat.
// send BOYD so the terminating vat has one last chance to clean
// up, drop imports, and delete durable data.
// If a vat is so broken it can't do BOYD, we can make this optional.
/** @type { import('../types-external.js').KernelDeliveryBringOutYourDead } */
const boydKD = harden(['bringOutYourDead']);
const boydVD = vatWarehouse.kernelDeliveryToVatDelivery(vatID, boydKD);
const boydStatus = await deliverAndLogToVat(vatID, boydKD, boydVD);
const boydResults = deliveryCrankResults(vatID, boydStatus, false);
// we don't meter bringOutYourDead since no user code is running, but we
// still report computrons to the runPolicy
computrons = addComputrons(computrons, boydResults.computrons);
// In the unexpected event that there is a problem during this
// upgrade-internal BOYD, the appropriate response isn't fully
// clear. We currently opt to translate a `terminate` result into a
// non-terminating `abort` that unwinds the upgrade delivery, and to
// ignore a non-terminate `abort` result. This is expected to change
// in the future, especially if we ever need some kind of emergency/
// manual upgrade (which might involve something like throwing an
// error to prompt a kernel panic if the bad vat is marked critical).
// There's a good analysis at
// https://github.com/Agoric/agoric-sdk/pull/7244#discussion_r1153633902
if (boydResults.terminate) {
console.log(
`WARNING: vat ${vatID} failed to upgrade from incarnation ${oldIncarnation} (BOYD)`,
);
const { info: errorCapData } = boydResults.terminate;
const results = await abortUpgrade(boydResults, errorCapData);
return results;
}
// reject all promises for which the vat was decider
for (const kpid of kernelKeeper.enumeratePromisesByDecider(vatID)) {
resolveToError(kpid, disconnectionCapData, vatID);
}
// simulate an abandonExports syscall from the vat,
// without making an *actual* syscall that could pollute logs
const abandonedObjects = [
...kernelKeeper.enumerateNonDurableObjectExports(vatID),
];
for (const { kref, vref } of abandonedObjects) {
/** @see translateAbandonExports in {@link ./vatTranslator.js} */
vatKeeper.deleteCListEntry(kref, vref);
/** @see abandonExports in {@link ./kernelSyscall.js} */
kernelKeeper.orphanKernelObject(kref, vatID);
}
// cleanup done, now we reset the worker to a clean state with no
// transcript or snapshot and prime everything for the next incarnation.
const newIncarnation = await vatWarehouse.beginNewWorkerIncarnation(vatID);
// update source and bundleIDs, store back to vat metadata
const source = { bundleID };
const origOptions = vatKeeper.getOptions();
const workerOptions = await updateWorkerOptions(origOptions.workerOptions, {
bundleHandler,
});
const vatOptions = harden({ ...origOptions, workerOptions });
vatKeeper.setSourceAndOptions(source, vatOptions);
// TODO: decref the bundleID once setSourceAndOptions increfs it
// pause, take a deep breath, appreciate this moment of silence
// between the old and the new. this moment will never come again.
// deliver a startVat with the new vatParameters
/** @type { import('../types-external.js').KernelDeliveryStartVat } */
const startVatKD = harden(['startVat', vatParameters]);
const startVatVD = vatWarehouse.kernelDeliveryToVatDelivery(
vatID,
startVatKD,
);
// decref vatParameters now that translation did incref
for (const kref of vatParameters.slots) {
kernelKeeper.decrementRefCount(kref, 'upgrade-vat-event');
}
const startVatStatus = await deliverAndLogToVat(
vatID,
startVatKD,
startVatVD,
);
const startVatResults = deliveryCrankResults(vatID, startVatStatus, false);
computrons = addComputrons(computrons, startVatResults.computrons);
if (startVatResults.terminate) {
// abort and unwind just like above
console.log(
`WARNING: vat ${vatID} failed to upgrade from incarnation ${oldIncarnation} (startVat)`,
);
const { info: errorCapData } = startVatResults.terminate;
const results = await abortUpgrade(startVatResults, errorCapData);
return results;
}
console.log(
`vat ${vatID} upgraded from incarnation ${oldIncarnation} to ${newIncarnation} with source ${bundleID}`,
);
const args = [upgradeID, true, undefined, newIncarnation];
/** @type {RawMethargs} */
const vatAdminMethargs = ['vatUpgradeCallback', args];
const results = harden({
computrons,
meterID, // for the startVat
vatAdminMethargs,
});
return results;
}
function legibilizeMessage(message) {
if (message.type === 'send') {
const msg = message.msg;
const [method, argList] = legibilizeMessageArgs(msg.methargs);
const result = msg.result ? msg.result : 'null';
return `@${message.target} <- ${method}(${argList}) : @${result}`;
} else if (message.type === 'notify') {
return `notify(vatID: ${message.vatID}, kpid: @${message.kpid})`;
} else if (message.type === 'create-vat') {
// prettier-ignore
return `create-vat ${message.vatID} opts: ${JSON.stringify(message.dynamicOptions)} vatParameters: ${JSON.stringify(message.vatParameters)}`;
} else if (message.type === 'upgrade-vat') {
// prettier-ignore
return `upgrade-vat ${message.vatID} upgradeID: ${message.upgradeID} vatParameters: ${JSON.stringify(message.vatParameters)}`;
} else if (message.type === 'changeVatOptions') {
// prettier-ignore
return `changeVatOptions ${message.vatID} options: ${JSON.stringify(message.options)}`;
// eslint-disable-next-line no-use-before-define
} else if (gcMessages.includes(message.type)) {
// prettier-ignore
return `${message.type} ${message.vatID} ${message.krefs.map(e=>`@${e}`).join(' ')}`;