@swf2es/codegen 0.1.34 → 0.1.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/index.ts CHANGED
@@ -8,6 +8,10 @@
8
8
  */
9
9
  import { AIR_API_VERSION, API_VERSION, checkApiVersion, isAirApiVersion } from "@swf2es/format";
10
10
  import { instantiate } from "./codegen.js";
11
+ import { KeyChains, type KeyContext } from "./keys.js";
12
+
13
+ export { KeyChains, type KeyContext, type KeyLog } from "./keys.js";
14
+ export { hex, sha256Here } from "./sha256.js";
11
15
 
12
16
  /** Bumped whenever generated code or the runtime ABI it calls changes. */
13
17
  export const COMPILER_VERSION = "0.0.0";
@@ -47,9 +51,11 @@ export function libraryLog(codegen: Codegen, index: number, count: number): stri
47
51
  * SWFs of several versions share the libraries' modules), every ABC its
48
52
  * domain sees, by hash and whether it is a library, those added after it
49
53
  * included, its own place among them, and the compiler's log about them
50
- * (see Codegen.context), the libraries' part by its digest once taken. The
51
- * player's module cache and the swf2es command both key by it, so that the
52
- * command's modules are the cache's. Null where there is no context.
54
+ * (see Codegen.context), the libraries' part by its digest once taken and
55
+ * the rest by the chained digests of its blocks of entries but the last
56
+ * few (see Codegen.keyContext). The player's module cache and the swf2es
57
+ * command both key by it, so that the command's modules are the cache's.
58
+ * Null where there is no context.
53
59
  */
54
60
  export function moduleKey(
55
61
  codegen: Codegen,
@@ -57,7 +63,7 @@ export function moduleKey(
57
63
  abcs: AddedAbcs,
58
64
  libraries: LibraryDigest | null,
59
65
  ): string | null {
60
- const context = codegen.context(index, libraries?.count ?? 0);
66
+ const context = codegen.keyContext(index, libraries?.count ?? 0);
61
67
  if (!context) {
62
68
  return null;
63
69
  }
@@ -70,7 +76,8 @@ export function moduleKey(
70
76
  abcs: context.abcs.map((i) => `${abcs.builtins[i] ? "builtin " : ""}${abcs.hashes[i]}`),
71
77
  own: context.own,
72
78
  libraries,
73
- log: context.log,
79
+ blocks: context.blocks,
80
+ log: context.rest,
74
81
  });
75
82
  }
76
83
 
@@ -160,7 +167,7 @@ export interface Compiled {
160
167
  module: string;
161
168
  /** JSON: the module's lines mapped to the AS3 lines debugline names. */
162
169
  sourceMap: string;
163
- /** By method body index: the body's entry in the module's F, as the JIT compiles it alone. */
170
+ /** By method body index: the body's entry in the module's F. */
164
171
  entries: Map<number, string>;
165
172
  }
166
173
 
@@ -188,8 +195,8 @@ export interface LoggedModule {
188
195
 
189
196
  /**
190
197
  * The compiler. ABCs are added to a domain in the order the SWF loads them
191
- * (the builtins first), and the last one added compiles, whole or a method
192
- * at a time, to code that is byte for byte the same either way.
198
+ * (the builtins first), and the last one added compiles to its module,
199
+ * byte for byte the same however the compiler got there.
193
200
  */
194
201
  export interface Codegen {
195
202
  /**
@@ -234,18 +241,24 @@ export interface Codegen {
234
241
  /**
235
242
  * Rebuild the domain without the ABCs of dropped and evicted domains, if
236
243
  * memory would otherwise grow and they hold enough to keep it from
237
- * growing: whether it did. A rebuild links every live ABC again, tens of
238
- * milliseconds for a large application, so a host calls this when it has
239
- * time, as when idle; nothing else does.
244
+ * growing, or memory is far above what the live ones need: whether it
245
+ * did. Done in a new instance of the compiler, made ahead, which takes
246
+ * the old one's place, so that its memory goes with it, where that takes
247
+ * less memory or a rebuild in place would not fit; else in place, only
248
+ * where the new tables fit beside the old. A rebuild links every live
249
+ * ABC again and verifies them again, seconds for a large application, so
250
+ * a host calls this when it has time, as when idle; nothing else does.
240
251
  */
241
252
  compact(): boolean;
242
253
  /**
243
254
  * What the ABCs hold of codegen's memory, roughly, in bytes: the live
244
255
  * ones', and the dropped and evicted domains' that compact would free;
245
- * and the size of codegen's memory, which never shrinks.
256
+ * the size of codegen's memory, which grows and never shrinks but when
257
+ * compact moves the domain to a new instance; and how many such moves
258
+ * failed, each leaving the domain as it was, rebuilt in place if at all.
246
259
  */
247
- usage(): { live: number; dead: number; memory: number };
248
- /** The size of codegen's memory in bytes, which never shrinks: cheap, for a host that shows it often. */
260
+ usage(): { live: number; dead: number; memory: number; failedMoves: number };
261
+ /** The size of codegen's memory in bytes, as usage gives it: cheap, for a host that shows it often. */
249
262
  memoryBytes(): number;
250
263
  /**
251
264
  * Evict application domain `appDomain` and its descendants while the host
@@ -281,20 +294,6 @@ export interface Codegen {
281
294
  * never shrinks.
282
295
  */
283
296
  compileModule(hashes?: string[], index?: number): string;
284
- /**
285
- * An opt-in JIT module's tables and lazy factories. Its default export
286
- * takes (rt, jit); jit(body, bindings) returns that body's factory.
287
- * Verification still runs now to fix scopes against the current domain.
288
- * This module is not an AOT module and must not enter the module cache.
289
- */
290
- compileLazyModule(hashes?: string[], index?: number): string;
291
- /**
292
- * Method bodies of ABC `index` (the last added by default) compiled
293
- * alone, as the optional lazy JIT compiles each on first factory use;
294
- * a native, unverified or unknown one is left out. Each is byte for byte
295
- * its entry in the whole module.
296
- */
297
- compileMethods(bodies: number[], index?: number): Map<number, string>;
298
297
  /**
299
298
  * What ABC `index`'s module depends on beyond the ABCs' bytes, for a
300
299
  * cache key: besides the ABCs its domain sees, what the domain has
@@ -304,6 +303,17 @@ export interface Codegen {
304
303
  * for an ABC never added.
305
304
  */
306
305
  context(index?: number, after?: number, upTo?: number): ModuleContext | null;
306
+ /**
307
+ * ABC `index`'s context as a module key names it, the log's entries
308
+ * made with `after` ABCs added or fewer left out: the log by the chained
309
+ * digests of its blocks of entries, those made before the last ABC was
310
+ * added, and the text of the entries after them. Each application
311
+ * domain keeps its last digest, so a key reads and digests only the
312
+ * entries made since the last, or since its parent's. The same domain
313
+ * gives the same however its keys were taken. Null for an ABC never
314
+ * added, or of a domain not live.
315
+ */
316
+ keyContext(index?: number, after?: number): KeyContext | null;
307
317
  /**
308
318
  * A string that changes whenever a context might: a host that took one
309
319
  * and finds this the same since need not take it again.
@@ -359,7 +369,7 @@ export interface Codegen {
359
369
  * this package free of I/O. The file ships as `@swf2es/codegen/codegen.wasm`.
360
370
  */
361
371
  export async function createCodegen(module: WebAssembly.Module): Promise<Codegen> {
362
- const wasm = await instantiate(module, { env: {} });
372
+ let wasm = await instantiate(module, { env: {} });
363
373
  const version = wasm.compilerVersion();
364
374
  if (version !== COMPILER_VERSION) {
365
375
  throw new Error(
@@ -376,6 +386,16 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
376
386
  );
377
387
  }
378
388
 
389
+ // Or before it wrote a module a part at a time, or rebuilt its domain a
390
+ // part at a time and in another instance.
391
+ for (const name of ["domainModuleMoreBytes", "domainRebuildStep", "domainSaveBytes"]) {
392
+ if (!WebAssembly.Module.exports(module).some((e) => e.name === name)) {
393
+ throw new Error(
394
+ `codegen.wasm has no ${name} export, which the wrapper expects: it is older than the wrapper`,
395
+ );
396
+ }
397
+ }
398
+
379
399
  // codegen.wasm uses AssemblyScript's minimal runtime, which collects
380
400
  // garbage only when asked. Nothing runs in wasm between calls, so that is
381
401
  // when: every COLLECT_EVERY calls, and after a call that grew memory.
@@ -383,7 +403,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
383
403
  // cycle's garbage grow it a little further.
384
404
  let size = wasm.memory.buffer.byteLength;
385
405
  let calls = 0;
386
- let methodBytes = 0;
387
406
  // Whether the domain has an ABC to compile: asking before is a mistake worth a message, not a trap.
388
407
  let added = 0;
389
408
  const last = (what: string) => {
@@ -401,7 +420,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
401
420
  };
402
421
  // ABC `index`'s module, its source map and entries kept for `keep`. A
403
422
  // module is never empty: the ABC was of a dropped application domain.
404
- const moduleOf = (hashes: string[], index: number, keep: boolean, lazy = false) => {
423
+ const moduleOf = (hashes: string[], index: number, keep: boolean) => {
405
424
  // Only the hashes the module names: joining every ABC's for each
406
425
  // compile took megabytes of codegen's memory a few thousand loads on.
407
426
  const at = indexOf(index);
@@ -413,12 +432,19 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
413
432
  }
414
433
 
415
434
  // Its bytes decoded here: lifted as a string, a module of megabytes took
416
- // longer than compiling it. The emitter writes only well-formed UTF-8,
417
- // which decodes alike either way.
418
- const address = lazy
419
- ? wasm.domainLazyModuleBytes(named.join("\n"), at)
420
- : wasm.domainModuleBytes(named.join("\n"), at, keep, true);
421
- const module = collected(handed(address, wasm.outputLength()), lazy);
435
+ // longer than compiling it. The emitter writes only ASCII, which decodes
436
+ // alike either way, and to a string the engine keeps a byte a character.
437
+ // A large ABC's module comes a part at a time, each part's garbage
438
+ // collected before the next is written (see domainModuleBytes).
439
+ const parts = [
440
+ handed(wasm.domainModuleBytes(named.join("\n"), at, keep, true), wasm.outputLength()),
441
+ ];
442
+ while (!wasm.domainModuleDone()) {
443
+ wasm.__collect();
444
+ parts.push(handed(wasm.domainModuleMoreBytes(), wasm.outputLength()));
445
+ }
446
+
447
+ const module = collected(parts.length === 1 ? parts[0] : parts.join(""), parts.length > 1);
422
448
  if (module === "") {
423
449
  throw new Error(`ABC ${index}: its application domain was dropped`);
424
450
  }
@@ -487,13 +513,125 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
487
513
  const identity = stamps.length ? String.fromCharCode(...new Uint8Array(stamps[0])) : null;
488
514
  let epoch = 0;
489
515
  let apiVersion = API_VERSION;
516
+ // Read where they are in codegen's memory, digested before the next call in.
517
+ const chains = new KeyChains({
518
+ header(index) {
519
+ const address = wasm.domainKeyHeaderBytes(index);
520
+ return address === 0 ? "" : handed(address, wasm.outputLength());
521
+ },
522
+ parent: (appDomain) => wasm.domainParent(appDomain),
523
+ fork: (appDomain) => wasm.domainKeyFork(appDomain),
524
+ log(appDomain, after, from, to, block, filled) {
525
+ const address = wasm.domainKeyLogBytes(appDomain, after, from, to, block, filled);
526
+ return address === 0
527
+ ? null
528
+ : new Uint8Array(wasm.memory.buffer, address, wasm.outputLength());
529
+ },
530
+ });
531
+ // The rebuild domainCompact, domainRevive or domainLoadRebuild started in
532
+ // `into`, a part a call, each part's garbage collected before the next
533
+ // (see domainRebuildStep), and the old tables once it is done, before the
534
+ // next call's allocations would grow memory past them: whether it was done.
535
+ const rebuild = (into = wasm) => {
536
+ let step = into.domainRebuildStep();
537
+ while (step === 0) {
538
+ into.__collect();
539
+ step = into.domainRebuildStep();
540
+ }
541
+
542
+ into.__collect();
543
+ size = wasm.memory.buffer.byteLength;
544
+ calls = 0;
545
+ return step > 0;
546
+ };
547
+ // A second instance of the compiler, made ahead as instantiating is
548
+ // asynchronous, that the next rebuild is done in (see moved): wasm memory
549
+ // never shrinks, so one done in place keeps, for good, as much as the
550
+ // dead tables and the old and the new took together. Made only once a
551
+ // move will be due before long (WANT_Spare), not for every compiler, and
552
+ // taken by the move; and how many moves failed, which usage tells.
553
+ let spare: typeof wasm | null = null;
554
+ let making = false;
555
+ let failedMoves = 0;
556
+ const prepare = () => {
557
+ if (spare === null && !making) {
558
+ making = true;
559
+ instantiate(module, { env: {} }).then(
560
+ (made) => {
561
+ spare = made;
562
+ making = false;
563
+ },
564
+ () => {
565
+ making = false;
566
+ },
567
+ );
568
+ }
569
+ };
570
+ // The domain rebuilt in `into`, a new instance, from what this one saves
571
+ // of it and its live ABCs' bytes, read where they are: whether it was. The
572
+ // ABCs' copies in it are its garbage once parsed, collected every few
573
+ // megabytes.
574
+ const rebuiltIn = (into: typeof wasm) => {
575
+ const saved = wasm.domainSaveBytes();
576
+ if (!into.domainLoad(new Uint8Array(wasm.memory.buffer, saved, wasm.outputLength()))) {
577
+ return false;
578
+ }
579
+
580
+ into.__collect();
581
+ let copied = 0;
582
+ for (let i = 0; i < added; i++) {
583
+ const at = wasm.domainSavedAbcBytes(i);
584
+ const length = wasm.outputLength();
585
+ if (at !== 0 && into.domainLoadAbc(i, new Uint8Array(wasm.memory.buffer, at, length)) !== 0) {
586
+ return false;
587
+ }
588
+
589
+ copied += length;
590
+ if (copied >= COPIED_BETWEEN_COLLECTIONS) {
591
+ into.__collect();
592
+ copied = 0;
593
+ }
594
+ }
595
+
596
+ return into.domainLoadRebuild() && rebuild(into);
597
+ };
598
+ // The domain rebuilt in the spare instance, which then takes this one's
599
+ // place, whose memory goes with it: whether it was. One that failed, or
600
+ // trapped as its memory could not grow, is let go of, the domain left
601
+ // here as it was, and another made.
602
+ const moved = () => {
603
+ const into = spare;
604
+ if (into === null) {
605
+ return false;
606
+ }
607
+
608
+ spare = null;
609
+ let done = false;
610
+ try {
611
+ done = rebuiltIn(into);
612
+ } catch {
613
+ done = false;
614
+ }
615
+
616
+ if (!done) {
617
+ failedMoves++;
618
+ size = wasm.memory.buffer.byteLength;
619
+ return false;
620
+ }
621
+
622
+ // The held SWFs' copies were the old instance's (see hold).
623
+ holds.length = 0;
624
+ wasm = into;
625
+ size = wasm.memory.buffer.byteLength;
626
+ calls = 0;
627
+ return true;
628
+ };
490
629
  const collected = <T>(result: T, reclaim = false): T => {
491
630
  const grown = wasm.memory.buffer.byteLength;
492
631
  if (reclaim || grown > size || ++calls >= COLLECT_EVERY) {
493
632
  wasm.__collect();
494
633
  size = grown;
495
634
  calls = 0;
496
- methodBytes = 0;
497
635
  }
498
636
 
499
637
  return result;
@@ -512,6 +650,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
512
650
  checkApiVersion(version);
513
651
  added = 0;
514
652
  epoch++;
653
+ chains.clear();
515
654
  apiVersion = version;
516
655
  collected(wasm.domainReset(version));
517
656
  },
@@ -541,6 +680,7 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
541
680
  dropDomain(appDomain, of = epoch) {
542
681
  if (of === epoch) {
543
682
  collected(wasm.domainDrop(appDomain));
683
+ chains.forget((d) => wasm.domainState(d) === 2);
544
684
  }
545
685
  },
546
686
  evictDomain(appDomain) {
@@ -548,36 +688,45 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
548
688
  },
549
689
  usage() {
550
690
  const [live, dead, memory] = collected(wasm.domainUsage()).split(" ").map(Number);
551
- return { live, dead, memory };
691
+ return { live, dead, memory, failedMoves };
552
692
  },
553
693
  memoryBytes() {
554
694
  return wasm.memory.buffer.byteLength;
555
695
  },
556
696
  compact() {
557
- // A rebuild makes new tables while the old are live: what earlier
558
- // calls left is collected first, and the old tables once it is done,
559
- // before the next call's allocations would grow memory past them.
560
- if (!collected(wasm.domainWantsCompact())) {
561
- return false;
697
+ // Done in the spare instance, once there is one and that would take
698
+ // less memory, or in place would not fit; else in place, where the
699
+ // new tables are made while the old are live, only where they fit
700
+ // and, beside a spare made or being made, a move would not do better:
701
+ // what earlier calls left is collected first, and the old tables once
702
+ // it is done, before the next call's allocations would grow memory
703
+ // past them.
704
+ if (spare === null && !making && collected(wasm.domainWantsCompact(WANT_Spare))) {
705
+ prepare();
562
706
  }
563
707
 
564
- wasm.__collect();
565
- calls = 0;
566
- if (!wasm.domainCompact()) {
708
+ if (spare !== null && collected(wasm.domainWantsCompact(WANT_Move))) {
709
+ wasm.__collect();
710
+ if (moved()) {
711
+ return true;
712
+ }
713
+ }
714
+
715
+ const beside = spare !== null || making;
716
+ if (!collected(wasm.domainWantsCompact(beside ? WANT_InPlaceBesideSpare : WANT_InPlace))) {
567
717
  return false;
568
718
  }
569
719
 
570
720
  wasm.__collect();
571
- size = wasm.memory.buffer.byteLength;
572
721
  calls = 0;
573
- return true;
722
+ return wasm.domainCompact(true) && rebuild();
574
723
  },
575
724
  isLive(appDomain) {
576
725
  return collected(wasm.domainState(appDomain)) === 0;
577
726
  },
578
727
  reviveDomain(appDomain, abcs) {
579
728
  // Its ABCs' bytes are copied into the compiler only if a rebuild let go of them.
580
- let revived = collected(wasm.domainRevive(appDomain));
729
+ let revived = collected(wasm.domainRevive(appDomain, true));
581
730
  if (revived < 0) {
582
731
  for (const [index, bytes] of abcs) {
583
732
  const error = collected(wasm.domainRestore(index, bytes));
@@ -586,20 +735,15 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
586
735
  }
587
736
  }
588
737
 
589
- revived = collected(wasm.domainRevive(appDomain));
738
+ revived = collected(wasm.domainRevive(appDomain, true));
590
739
  }
591
740
 
592
- if (revived < 0) {
741
+ // Revived by a rebuild in place, mid-load: a compaction moves it later.
742
+ if (revived < 0 || (revived > 0 && !rebuild())) {
593
743
  throw new Error(
594
744
  `application domain ${appDomain}: not evicted, its parent not live, or an ABC of it not given`,
595
745
  );
596
746
  }
597
-
598
- if (revived > 0) {
599
- wasm.__collect();
600
- size = wasm.memory.buffer.byteLength;
601
- calls = 0;
602
- }
603
747
  },
604
748
  found(d) {
605
749
  collected(wasm.domainFound(d.domain, d.nsKind, d.uri, d.name, d.abc, d.asType));
@@ -617,10 +761,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
617
761
  last("compileModule");
618
762
  return moduleOf(hashes, index, false);
619
763
  },
620
- compileLazyModule(hashes = [], index = -1) {
621
- last("compileLazyModule");
622
- return moduleOf(hashes, index, false, true);
623
- },
624
764
  context(index = -1, after = 0, upTo = -1) {
625
765
  if (added === 0) {
626
766
  return null;
@@ -640,6 +780,13 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
640
780
  log: second < 0 ? "" : text.slice(second + 1),
641
781
  };
642
782
  },
783
+ keyContext(index = -1, after = 0) {
784
+ if (added === 0) {
785
+ return null;
786
+ }
787
+
788
+ return collected(chains.context(indexOf(index), after));
789
+ },
643
790
  revision() {
644
791
  return `${epoch} ${wasm.domainRevision()}`;
645
792
  },
@@ -654,19 +801,6 @@ export async function createCodegen(module: WebAssembly.Module): Promise<Codegen
654
801
  last("replay");
655
802
  return collected(wasm.domainReplay(log, indexOf(index)));
656
803
  },
657
- compileMethods(bodies, index = -1) {
658
- last("compileMethods");
659
- const indices = bodies.filter((b) => Number.isInteger(b) && b >= 0);
660
- if (indices.length === 0) {
661
- return new Map();
662
- }
663
-
664
- const address = wasm.domainEmitEachBytes(indices.join(","), true, indexOf(index));
665
- const length = wasm.outputLength();
666
- methodBytes += length;
667
- const text = handed(address, length);
668
- return parseEntries(collected(text, methodBytes >= COLLECT_METHOD_BYTES));
669
- },
670
804
  compileActions(bytes, actions) {
671
805
  const module = actionsModule(bytes, actions, true);
672
806
  const entries = parseEntries(collected(wasm.actionsModuleEntries()));
@@ -735,10 +869,15 @@ function parseEntries(text: string): Map<number, string> {
735
869
  }
736
870
 
737
871
  const COLLECT_EVERY = 64;
872
+ /** What domainWantsCompact is asked (see wantsRebuild in assembly/avm2/link/lifetime.ts). */
873
+ const WANT_InPlace = 0;
874
+ const WANT_InPlaceBesideSpare = 1;
875
+ const WANT_Move = 2;
876
+ const WANT_Spare = 3;
877
+ /** How many bytes of ABCs a rebuild in the spare instance copies in between its collections. */
878
+ const COPIED_BETWEEN_COLLECTIONS = 4 << 20;
738
879
  /** How many SWFs whose blocks or units are compiled codegen holds a copy of at most. */
739
880
  const HELD_SWFS = 4;
740
- // Large method entries should not accumulate sixty-four calls of garbage.
741
- const COLLECT_METHOD_BYTES = 256 * 1024;
742
881
 
743
882
  // TextDecoder is the web's and node's alike, though not ECMAScript's,
744
883
  // whose library alone the compiler's wrapper is typed against.