@amritk/nish-x86_64-linux 0.44.0 → 0.46.0

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.
Files changed (119) hide show
  1. package/INSTALL.md +3 -1
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +18 -16
  4. package/package.json +1 -1
  5. package/runtime/core/numbers.mjs +3 -1
  6. package/runtime/core/strings.mjs +90 -38
  7. package/runtime/core.d.ts +8 -0
  8. package/runtime/core.mjs +16 -0
  9. package/runtime/nish.d.ts +88 -5
  10. package/runtime/nish.h +10 -0
  11. package/runtime/nish.mjs +5 -0
  12. package/runtime/runtime-host.c +15 -0
  13. package/runtime/runtime-net.c +223 -4
  14. package/runtime/runtime-os.c +15 -1
  15. package/runtime/runtime-uring.c +291 -31
  16. package/runtime/sqlite/nish-sqlite.c +301 -128
  17. package/std/README.md +15 -15
  18. package/std/array.ts +10 -2
  19. package/std/bytes.ts +239 -26
  20. package/std/cli-args.ts +1072 -606
  21. package/std/cli-flags.ts +180 -98
  22. package/std/cli.ts +21 -13
  23. package/std/collections.ts +245 -127
  24. package/std/compress/checksum.ts +32 -37
  25. package/std/compress/deflate.ts +1102 -542
  26. package/std/compress/gzip.ts +290 -145
  27. package/std/compress/zlib.ts +57 -21
  28. package/std/crypto/aes.ts +153 -75
  29. package/std/crypto/base64url.ts +84 -61
  30. package/std/crypto/bcrypt-batch.ts +164 -90
  31. package/std/crypto/bcrypt.ts +185 -107
  32. package/std/crypto/chacha20poly1305.ts +84 -68
  33. package/std/crypto/ct.ts +9 -7
  34. package/std/crypto/ed25519.ts +64 -27
  35. package/std/crypto/hkdf.ts +105 -63
  36. package/std/crypto/hmac.ts +95 -89
  37. package/std/crypto/jwt.ts +248 -126
  38. package/std/crypto/p256.ts +758 -444
  39. package/std/crypto/p384.ts +20 -13
  40. package/std/crypto/pki-roots.ts +95 -38
  41. package/std/crypto/pki.ts +164 -60
  42. package/std/crypto/rsa.ts +266 -223
  43. package/std/crypto/scram.ts +3 -4
  44. package/std/crypto/sha1.ts +107 -65
  45. package/std/crypto/sha256.ts +502 -422
  46. package/std/crypto/sha512.ts +204 -135
  47. package/std/crypto/x509-random.ts +9 -3
  48. package/std/crypto/x509.ts +331 -171
  49. package/std/json-equal.ts +35 -19
  50. package/std/json-format.ts +215 -108
  51. package/std/json-number.ts +126 -72
  52. package/std/json-pointer.ts +42 -13
  53. package/std/json-tokenizer.ts +498 -307
  54. package/std/json-typed.ts +115 -36
  55. package/std/json-value.ts +341 -152
  56. package/std/json.ts +300 -158
  57. package/std/net/buffer-pool.ts +17 -7
  58. package/std/net/dns-config.ts +427 -236
  59. package/std/net/dns-message.ts +114 -47
  60. package/std/net/dns-resolver.ts +736 -237
  61. package/std/net/dns.ts +205 -52
  62. package/std/net/fetch.ts +320 -184
  63. package/std/net/grpc.ts +948 -0
  64. package/std/net/handler.ts +1315 -222
  65. package/std/net/hpack.ts +395 -180
  66. package/std/net/http-compress.ts +502 -65
  67. package/std/net/http-fields.ts +85 -49
  68. package/std/net/http-server.ts +1764 -602
  69. package/std/net/http1-client-codec.ts +372 -161
  70. package/std/net/http1-codec.ts +665 -331
  71. package/std/net/http1-server.ts +660 -278
  72. package/std/net/http2-cleartext.ts +165 -95
  73. package/std/net/http2-frame.ts +232 -89
  74. package/std/net/http2-tls.ts +42 -12
  75. package/std/net/http2.ts +327 -101
  76. package/std/net/http3-frame.ts +68 -33
  77. package/std/net/http3-server.ts +647 -192
  78. package/std/net/http3.ts +667 -189
  79. package/std/net/oidc.ts +63 -24
  80. package/std/net/outbound.ts +207 -142
  81. package/std/net/postgres-async.ts +1165 -443
  82. package/std/net/postgres-carrier.ts +575 -372
  83. package/std/net/postgres.ts +1459 -559
  84. package/std/net/prefork.ts +254 -98
  85. package/std/net/protobuf.ts +1017 -0
  86. package/std/net/qpack.ts +143 -92
  87. package/std/net/quic-conn-ack.ts +50 -18
  88. package/std/net/quic-conn-cid.ts +66 -26
  89. package/std/net/quic-conn-params.ts +13 -7
  90. package/std/net/quic-datagram.ts +90 -27
  91. package/std/net/quic-frame.ts +225 -124
  92. package/std/net/quic-listener.ts +197 -89
  93. package/std/net/quic-packet.ts +289 -163
  94. package/std/net/quic-recovery.ts +279 -128
  95. package/std/net/quic-stream.ts +466 -167
  96. package/std/net/quic.ts +568 -257
  97. package/std/net/router.ts +450 -99
  98. package/std/net/serve.ts +651 -232
  99. package/std/net/static.ts +1458 -0
  100. package/std/net/tls/client.ts +140 -45
  101. package/std/net/tls/codec.ts +510 -260
  102. package/std/net/tls/record-client.ts +268 -76
  103. package/std/net/tls/record-server.ts +236 -79
  104. package/std/net/tls/record.ts +173 -47
  105. package/std/net/tls/schedule.ts +58 -39
  106. package/std/net/tls/ticket.ts +295 -103
  107. package/std/net/tls/verify.ts +1 -1
  108. package/std/net/tls-tcp.ts +218 -75
  109. package/std/net/tls.ts +260 -152
  110. package/std/net/upstream.ts +283 -86
  111. package/std/net/url.ts +277 -102
  112. package/std/net/websocket.ts +370 -186
  113. package/std/net/webtransport.ts +755 -436
  114. package/std/regex.ts +1659 -829
  115. package/std/sqlite.ts +171 -0
  116. package/std/sync/ring.ts +320 -156
  117. package/std/sync/shm.ts +53 -6
  118. package/std/text.ts +205 -124
  119. package/std/threads.ts +22 -2
@@ -172,7 +172,7 @@ import {
172
172
  } from "nish:net"
173
173
  import { monotonicNanos } from "nish:process"
174
174
  import { Secret } from "nish:secret"
175
- import { copyBytes, getI32BE, getU16BE, setI32BE, setU16BE } from "nish/bytes"
175
+ import { getI32BE, getU16BE, tryCopyBytes } from "nish/bytes"
176
176
  import {
177
177
  PG_ERR_CLOSED,
178
178
  PG_ERR_ENCODING,
@@ -214,8 +214,8 @@ export const PG_ASYNC_MAX_STATEMENTS: i32 = 64
214
214
  export const PG_ASYNC_MAX_DEPTH: i32 = 16
215
215
  /**
216
216
  * `pgAsyncSend`'s answer for a statement it did not send because a parameter
217
- * holds a NUL; `pgAsyncAnswer` fails it with `PG_ERR_ENCODING`, and the
218
- * connection is reused.
217
+ * holds a NUL, its Bind would pass 2^30 bytes, or its `values` and `nulls`
218
+ * differ in length; `pgAsyncAnswer` fails it with `PG_ERR_ENCODING`, and the connection is reused.
219
219
  */
220
220
  export const PG_ASYNC_UNSENT: i32 = -1
221
221
  /**
@@ -256,6 +256,41 @@ const PG_ASYNC_MAX_CAP: i32 = 1073741823
256
256
  const PG_ASYNC_MAX_ROWS: i32 = 16777216
257
257
  // What a kept cell costs `maxResultBytes` beyond its bytes: its string and its NULL flag.
258
258
  const PG_ASYNC_CELL_COST: i32 = 16
259
+ // Every wrap above is a power of two, so a count steps with a mask one below it.
260
+ const PG_ASYNC_CLAIM_MASK: i32 = PG_ASYNC_CLAIM_WRAP - 1
261
+ const PG_ASYNC_SEAT_MASK: i32 = PG_ASYNC_SEAT_WRAP - 1
262
+ const PG_ASYNC_SEQ_MASK: i32 = PG_ASYNC_SEQ_WRAP - 1
263
+ const PG_ASYNC_QUEUE_MASK: i32 = PG_ASYNC_QUEUE_WRAP - 1
264
+
265
+ /**
266
+ * `n` plus one, wrapped below `mask` plus one, a power of two: for `n` below
267
+ * that wrap it is `(n + 1) % wrap`. The sum is `u32`, which wraps by
268
+ * definition, so it needs no overflow check.
269
+ */
270
+ const pgAsyncStep = (n: i32, mask: i32): i32 => toI32((toU32(n) + toU32(1)) & toU32(mask))
271
+
272
+ /**
273
+ * How far `from` is behind `to`, two counts that wrap below `mask` plus one,
274
+ * a power of two: `(to - from + wrap) % wrap` for counts below the wrap,
275
+ * taken in `u32`, which wraps by definition.
276
+ */
277
+ const pgAsyncGap = (to: i32, from: i32, mask: i32): i32 => toI32((toU32(to) - toU32(from)) & toU32(mask))
278
+
279
+ /**
280
+ * Where wake `w`'s socket pair starts in `wakes`, `2w`: in `u32` the double
281
+ * wraps rather than checks, and a wake past 2^30 comes out negative, which
282
+ * every caller checks against `wakes` before it reads.
283
+ */
284
+ const pgAsyncPair = (w: i32): i32 => toI32(toU32(w) * toU32(2))
285
+
286
+ /** `n` plus one, held at the `i32` ceiling: a statistic that counts on, never back. */
287
+ const pgAsyncCount = (n: i32): i32 => (n < 2147483647 ? n + 1 : n)
288
+
289
+ /**
290
+ * `n` less 1, but not below 0: a waiter count is above 0 when a task takes
291
+ * itself off it, and a ring's unseen count only ever compares with 0.
292
+ */
293
+ const pgAsyncUncount = (n: i32): i32 => (n > 0 ? n - 1 : 0)
259
294
 
260
295
  /**
261
296
  * Authenticated PostgreSQL connections that spawned tasks share. Build one
@@ -306,13 +341,20 @@ export class PgAsyncPool {
306
341
  * 1 to `PG_ASYNC_MAX_DEPTH`.
307
342
  */
308
343
  depth: i32 = 8
309
- /** How many times `pgAsyncClaim` or `pgAsyncSeat` waited because no live connection had room. */
344
+ /**
345
+ * How many times `pgAsyncClaim` or `pgAsyncSeat` waited because no live
346
+ * connection had room, held at 2^31 - 1 rather than wrapping.
347
+ */
310
348
  waits: i32 = 0
311
- /** How many times `pgAsyncTurn` waited for the answers seated ahead of its own. */
349
+ /**
350
+ * How many times `pgAsyncTurn` waited for the answers seated ahead of its
351
+ * own, held at 2^31 - 1 rather than wrapping.
352
+ */
312
353
  turnWaits: i32 = 0
313
354
  /**
314
355
  * How many connections were closed rather than given back: by
315
- * `pgAsyncRelease`, or once a lost pipeline emptied.
356
+ * `pgAsyncRelease`, or once a lost pipeline emptied. It is held at
357
+ * 2^31 - 1 rather than wrapping.
316
358
  */
317
359
  dropped: i32 = 0
318
360
  /**
@@ -321,7 +363,7 @@ export class PgAsyncPool {
321
363
  * for as long as the server takes.
322
364
  */
323
365
  connectWaitMs: i32 = 10000
324
- /** How many connections `pgAsyncConnect` made, in all. */
366
+ /** How many connections `pgAsyncConnect` made, in all, held at 2^31 - 1 rather than wrapping. */
325
367
  connects: i32 = 0
326
368
  /**
327
369
  * The queue number of the first task still waiting for a seat. Of the
@@ -416,31 +458,36 @@ export class PgAsyncPool {
416
458
  panic("nish/net/postgres-async: a PgAsyncPool size out of range")
417
459
  }
418
460
  this.size = size
419
- this.fds = new Array<i32>(size)
420
- this.claimed = new Array<u8>(size)
421
- this.claims = new Array<i32>(size)
461
+ // As `u16`s the lengths need no check: the size is 1 to 64 here, so the
462
+ // most any of them holds is 64 seats of 64 statements.
463
+ const slots: u16 = toU16(size)
464
+ const statements: u16 = slots * toU16(PG_ASYNC_MAX_STATEMENTS)
465
+ const seats: u16 = slots * toU16(PG_ASYNC_MAX_DEPTH)
466
+ const wakes: u16 = toU16(PG_ASYNC_WAKES)
467
+ this.fds = new Array<i32>(slots)
468
+ this.claimed = new Array<u8>(slots)
469
+ this.claims = new Array<i32>(slots)
422
470
  this.statements = []
423
- this.prepared = new Array<u8>(size * PG_ASYNC_MAX_STATEMENTS)
471
+ this.prepared = new Array<u8>(statements)
424
472
  this.inputs = []
425
- this.inStart = new Array<i32>(size)
426
- this.inEnd = new Array<i32>(size)
427
- this.inAnswer = new Array<i32>(size)
428
- this.inParsed = new Array<u8>(size)
429
- this.nextSeq = new Array<i32>(size)
430
- this.served = new Array<i32>(size)
431
- this.doomAt = new Array<i32>(size)
432
- this.seated = new Array<i32>(size)
433
- this.writing = new Array<u8>(size)
434
- this.seatUsed = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
435
- this.seatSeq = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
436
- this.seatStatement = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
437
- this.seatParse = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
438
- this.seatWaiting = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
439
- this.seatClaims = new Array<i32>(size * PG_ASYNC_MAX_DEPTH)
440
- this.seatAbandoned = new Array<u8>(size * PG_ASYNC_MAX_DEPTH)
441
- this.skipping = new Array<u8>(size)
442
- const wakes: i32 = PG_ASYNC_WAKES
443
- this.wakes = new Array<i32>(wakes * 2)
473
+ this.inStart = new Array<i32>(slots)
474
+ this.inEnd = new Array<i32>(slots)
475
+ this.inAnswer = new Array<i32>(slots)
476
+ this.inParsed = new Array<u8>(slots)
477
+ this.nextSeq = new Array<i32>(slots)
478
+ this.served = new Array<i32>(slots)
479
+ this.doomAt = new Array<i32>(slots)
480
+ this.seated = new Array<i32>(slots)
481
+ this.writing = new Array<u8>(slots)
482
+ this.seatUsed = new Array<u8>(seats)
483
+ this.seatSeq = new Array<i32>(seats)
484
+ this.seatStatement = new Array<i32>(seats)
485
+ this.seatParse = new Array<u8>(seats)
486
+ this.seatWaiting = new Array<u8>(seats)
487
+ this.seatClaims = new Array<i32>(seats)
488
+ this.seatAbandoned = new Array<u8>(seats)
489
+ this.skipping = new Array<u8>(slots)
490
+ this.wakes = new Array<i32>(wakes * toU16(2))
444
491
  this.wakePending = new Array<u8>(wakes)
445
492
  this.wakeBytes = new Array<u8>(8)
446
493
  this.wakePair = new Array<i32>(2)
@@ -448,12 +495,12 @@ export class PgAsyncPool {
448
495
  this.wakeRings = new Array<i32>(wakes)
449
496
  this.wakeUnseen = new Array<i32>(wakes)
450
497
  this.seatGone = new Array<u8>(PG_ASYNC_QUEUE)
451
- for (let s: i32 = 0; s < size; s++) {
498
+ for (let s: i32 = 0; s < toI32(this.fds.length) && s < toI32(this.doomAt.length); s++) {
452
499
  this.fds[s] = -1
453
500
  this.doomAt[s] = -1
454
501
  this.inputs.push(new Array<u8>(PG_ASYNC_INPUT_SIZE))
455
502
  }
456
- for (let w: i32 = 0; w < wakes * 2; w++) {
503
+ for (let w: i32 = 0; w < toI32(this.wakes.length); w++) {
457
504
  this.wakes[w] = -1
458
505
  }
459
506
  }
@@ -463,13 +510,14 @@ export class PgAsyncPool {
463
510
  * @returns The count, 0 to `size`.
464
511
  */
465
512
  live(): i32 {
466
- let n: i32 = 0
467
- for (let s: i32 = 0; s < this.size; s++) {
513
+ // A `u32` count wraps rather than checks: it never passes `size`.
514
+ let n: u32 = 0
515
+ for (let s: i32 = 0; s < toI32(this.fds.length); s++) {
468
516
  if (this.fds[s] >= 0) {
469
517
  n += 1
470
518
  }
471
519
  }
472
- return n
520
+ return toI32(n)
473
521
  }
474
522
 
475
523
  /**
@@ -479,28 +527,41 @@ export class PgAsyncPool {
479
527
  */
480
528
  close(): void {
481
529
  const terminate: u8[] = [88, 0, 0, 0, 4]
482
- for (let s: i32 = 0; s < this.size; s++) {
530
+ for (
531
+ let s: i32 = 0;
532
+ s < toI32(this.fds.length) && s < toI32(this.claimed.length) && s < toI32(this.claims.length);
533
+ s++
534
+ ) {
535
+ // The slot is marked closed before the calls, which the bounds above do not outlive.
483
536
  const fd: i32 = this.fds[s]
537
+ this.fds[s] = -1
538
+ this.claimed[s] = 0
539
+ this.claims[s] = pgAsyncStep(this.claims[s], PG_ASYNC_CLAIM_MASK)
484
540
  if (fd >= 0) {
485
- netWrite(fd, terminate, 0, 5)
541
+ netWrite(fd, terminate, 0, toI32(terminate.length))
486
542
  netClose(fd)
487
- this.fds[s] = -1
488
- }
489
- this.claimed[s] = 0
490
- this.claims[s] = (this.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
491
- for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
492
- const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
493
- this.seatUsed[seat] = 0
494
- this.seatWaiting[seat] = 0
495
- this.seatAbandoned[seat] = 0
496
- this.seatClaims[seat] = (this.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
497
543
  }
498
544
  pgAsyncForget(this, s)
499
545
  }
546
+ // Every slot's seats, which lie one after another.
547
+ for (
548
+ let seat: i32 = 0;
549
+ seat < toI32(this.seatUsed.length) &&
550
+ seat < toI32(this.seatWaiting.length) &&
551
+ seat < toI32(this.seatAbandoned.length) &&
552
+ seat < toI32(this.seatClaims.length);
553
+ seat++
554
+ ) {
555
+ this.seatUsed[seat] = 0
556
+ this.seatWaiting[seat] = 0
557
+ this.seatAbandoned[seat] = 0
558
+ this.seatClaims[seat] = pgAsyncStep(this.seatClaims[seat], PG_ASYNC_SEAT_MASK)
559
+ }
500
560
  for (let w: i32 = 0; w < toI32(this.wakes.length); w++) {
501
- if (this.wakes[w] >= 0) {
502
- netClose(this.wakes[w])
503
- this.wakes[w] = -1
561
+ const fd: i32 = this.wakes[w]
562
+ this.wakes[w] = -1
563
+ if (fd >= 0) {
564
+ netClose(fd)
504
565
  }
505
566
  }
506
567
  }
@@ -508,6 +569,35 @@ export class PgAsyncPool {
508
569
 
509
570
  /** Resets slot `s`'s pipeline: nothing in flight, nothing prepared, nothing buffered. */
510
571
  const pgAsyncForget = (pool: PgAsyncPool, s: i32): void => {
572
+ // 64 is PG_ASYNC_MAX_SIZE, written as a literal: the prover takes a bound
573
+ // from a literal but not from a module constant, and the bound proves the
574
+ // `prepared` offsets below cannot overflow.
575
+ if (s < 0 || s >= 64) {
576
+ return
577
+ }
578
+ if (
579
+ s >= toI32(pool.nextSeq.length) ||
580
+ s >= toI32(pool.served.length) ||
581
+ s >= toI32(pool.doomAt.length) ||
582
+ s >= toI32(pool.seated.length) ||
583
+ s >= toI32(pool.writing.length) ||
584
+ s >= toI32(pool.inStart.length) ||
585
+ s >= toI32(pool.inEnd.length) ||
586
+ s >= toI32(pool.inAnswer.length) ||
587
+ s >= toI32(pool.inParsed.length) ||
588
+ s >= toI32(pool.skipping.length)
589
+ ) {
590
+ // No such slot: nothing to reset.
591
+ return
592
+ }
593
+ const first: i32 = s * PG_ASYNC_MAX_STATEMENTS
594
+ // 64 is PG_ASYNC_MAX_STATEMENTS, a literal for the same reason.
595
+ for (let q: i32 = 0; q < 64; q++) {
596
+ const at: i32 = first + q
597
+ if (at < toI32(pool.prepared.length)) {
598
+ pool.prepared[at] = 0
599
+ }
600
+ }
511
601
  pool.nextSeq[s] = 0
512
602
  pool.served[s] = 0
513
603
  pool.doomAt[s] = -1
@@ -518,9 +608,6 @@ const pgAsyncForget = (pool: PgAsyncPool, s: i32): void => {
518
608
  pool.inAnswer[s] = -1
519
609
  pool.inParsed[s] = 0
520
610
  pool.skipping[s] = 0
521
- for (let q: i32 = 0; q < PG_ASYNC_MAX_STATEMENTS; q++) {
522
- pool.prepared[s * PG_ASYNC_MAX_STATEMENTS + q] = 0
523
- }
524
611
  }
525
612
 
526
613
  /**
@@ -618,7 +705,11 @@ export class PgAsyncResult {
618
705
  * @returns The text the server sent.
619
706
  */
620
707
  text(row: i32, column: i32): string {
621
- return this.values[this.cell(row, column)]
708
+ const at: i32 = this.cell(row, column)
709
+ if (at < 0 || at >= toI32(this.values.length)) {
710
+ panic("nish/net/postgres-async: a cell out of range")
711
+ }
712
+ return this.values[at]
622
713
  }
623
714
 
624
715
  /**
@@ -628,63 +719,73 @@ export class PgAsyncResult {
628
719
  * @returns True for a NULL.
629
720
  */
630
721
  isNull(row: i32, column: i32): boolean {
631
- return this.nulls[this.cell(row, column)]
722
+ const at: i32 = this.cell(row, column)
723
+ if (at < 0 || at >= toI32(this.nulls.length)) {
724
+ panic("nish/net/postgres-async: a cell out of range")
725
+ }
726
+ return this.nulls[at]
632
727
  }
633
728
 
634
729
  /**
635
- * A cell read as a decimal `i32`, or `fallback` when it is NULL or not one.
730
+ * A cell read as a decimal `i32`, or `fallback` when it is NULL or not one;
731
+ * panics on a row or column out of range.
636
732
  * @param row The row, from 0.
637
733
  * @param column The column, from 0.
638
734
  * @param fallback The answer for a NULL or a cell that is not a decimal `i32`.
639
735
  * @returns The number.
640
736
  */
641
737
  int(row: i32, column: i32, fallback: i32): i32 {
642
- const at: i32 = this.cell(row, column)
643
- if (this.nulls[at]) {
738
+ if (this.isNull(row, column)) {
644
739
  return fallback
645
740
  }
646
- return pgAsyncDecimal(this.values[at], fallback)
741
+ return pgAsyncDecimal(this.text(row, column), fallback)
647
742
  }
648
743
 
649
- /** The index into `values` of a cell, after the bounds check. */
744
+ /**
745
+ * The index into `values` of a cell, or -1 for a row or column out of
746
+ * range; the caller panics on -1, as its contract says.
747
+ */
650
748
  private cell(row: i32, column: i32): i32 {
651
749
  if (row < 0 || row >= this.rows || column < 0 || column >= this.columns) {
652
- panic("nish/net/postgres-async: a cell out of range")
750
+ return -1
653
751
  }
654
- return row * this.columns + column
752
+ // In `i64` the sum cannot overflow; past the cells kept it is out of range too.
753
+ const at: i64 = toI64(row) * toI64(this.columns) + toI64(column)
754
+ return at < toI64(this.values.length) ? toI32(at) : -1
655
755
  }
656
756
  }
657
757
 
658
758
  /** `s` as a decimal `i32`, or `fallback` when it is not one. */
659
759
  const pgAsyncDecimal = (s: string, fallback: i32): i32 => {
660
760
  const n: i32 = toI32(s.length)
661
- if (n === 0 || n > 11) {
761
+ if (n < 1 || n > 11) {
662
762
  return fallback
663
763
  }
664
- let at: i32 = 0
665
- const negative: boolean = s.charCodeAt(0) === 45
666
- if (negative) {
667
- at = 1
668
- if (n === 1) {
669
- return fallback
670
- }
671
- }
672
- let v: i64 = 0
673
- while (at < n) {
764
+ let negative: boolean = false
765
+ // At most 11 digits fit a `u64` with room to spare, and `u64` arithmetic
766
+ // wraps rather than checks, so the sum needs no overflow test.
767
+ let v: u64 = 0
768
+ for (let at: i32 = 0; at < n; at++) {
674
769
  const c: i32 = toI32(s.charCodeAt(at))
675
- if (c < 48 || c > 57) {
770
+ if (at === 0 && c === 45) {
771
+ negative = true
772
+ } else if (c < 48 || c > 57) {
676
773
  return fallback
774
+ } else {
775
+ v = v * toU64(10) + toU64(c - 48)
677
776
  }
678
- v = v * toI64(10) + toI64(c - 48)
679
- at += 1
680
777
  }
681
- if (negative) {
682
- v = -v
778
+ const w: i64 = toI64(v)
779
+ if (w < 0 || w > 2147483648) {
780
+ return fallback
683
781
  }
684
- if (v < toI64(-2147483648) || v > toI64(2147483647)) {
782
+ if (negative && n === 1) {
685
783
  return fallback
686
784
  }
687
- return toI32(v)
785
+ if (negative) {
786
+ return toI32(-w)
787
+ }
788
+ return w > toI64(2147483647) ? fallback : toI32(w)
688
789
  }
689
790
 
690
791
  /**
@@ -705,7 +806,8 @@ const pgAsyncSlot = (pool: PgAsyncPool, ticket: i32): i32 => {
705
806
  const slot: i32 = ticket >= 0 ? ticket % PG_ASYNC_MAX_SIZE : -1
706
807
  if (
707
808
  slot < 0 ||
708
- slot >= pool.size ||
809
+ slot >= toI32(pool.claimed.length) ||
810
+ slot >= toI32(pool.claims.length) ||
709
811
  toI32(pool.claimed[slot]) !== 1 ||
710
812
  toI32(ticket / PG_ASYNC_MAX_SIZE) !== pool.claims[slot]
711
813
  ) {
@@ -743,7 +845,7 @@ export const pgAsyncConnect = async (
743
845
  panic("nish/net/postgres-async: a TCP host must be a numeric address")
744
846
  }
745
847
  const nonce: u8[] = new Array<u8>(PG_ASYNC_NONCE_BYTES)
746
- for (let s: i32 = 0; s < pool.size; s++) {
848
+ for (let s: i32 = 0; s < toI32(pool.fds.length); s++) {
747
849
  if (pool.fds[s] >= 0) {
748
850
  continue
749
851
  }
@@ -756,10 +858,11 @@ export const pgAsyncConnect = async (
756
858
  }
757
859
  const made: boolean = await pgAsyncStartup(conn, fd, monotonicNanos(), pool.connectWaitMs)
758
860
  conn.dispose()
759
- if (made) {
861
+ // The handshake awaited, so the slot is checked against the arrays again.
862
+ if (made && s < toI32(pool.fds.length) && s < toI32(pool.claimed.length)) {
760
863
  pool.fds[s] = fd
761
864
  pool.claimed[s] = 0
762
- pool.connects += 1
865
+ pool.connects = pgAsyncCount(pool.connects)
763
866
  pgAsyncForget(pool, s)
764
867
  } else {
765
868
  netClose(fd)
@@ -779,13 +882,14 @@ const pgAsyncStartup = async (conn: PgConnection, fd: i32, began: i64, waitMs: i
779
882
  return false
780
883
  }
781
884
  while (true) {
782
- while (conn.outputEnd() > conn.outputStart()) {
783
- const n: i32 = netWrite(
784
- fd,
785
- conn.outputBuffer(),
786
- conn.outputStart(),
787
- conn.outputEnd() - conn.outputStart()
788
- )
885
+ while (true) {
886
+ const start: i32 = conn.outputStart()
887
+ const end: i32 = conn.outputEnd()
888
+ if (start < 0 || end <= start) {
889
+ break
890
+ }
891
+ // Both are at least 0 and `end` is past `start`, so the `u32` difference is exact.
892
+ const n: i32 = netWrite(fd, conn.outputBuffer(), start, toI32(toU32(end) - toU32(start)))
789
893
  if (n === PG_ASYNC_AGAIN) {
790
894
  const waited: boolean = await pgAsyncWaitUntil(fd, true, began, waitMs)
791
895
  if (!waited) {
@@ -837,10 +941,11 @@ const pgAsyncWaitUntil = async (fd: i32, write: boolean, began: i64, waitMs: i32
837
941
  } else if (waitMs <= 0) {
838
942
  waited = await readable(fd)
839
943
  } else {
840
- const left: i32 = waitMs - pgAsyncSince(began)
841
- if (left <= 0) {
944
+ const since: i32 = pgAsyncSince(began)
945
+ if (since < 0 || since >= waitMs) {
842
946
  return false
843
947
  }
948
+ const left: i32 = waitMs - since
844
949
  if (write) {
845
950
  waited = await writableWithin(fd, left)
846
951
  } else {
@@ -852,7 +957,9 @@ const pgAsyncWaitUntil = async (fd: i32, write: boolean, began: i64, waitMs: i32
852
957
 
853
958
  /** Milliseconds since `began`, a `monotonicNanos` reading. */
854
959
  const pgAsyncSince = (began: i64): i32 => {
855
- const ms: i64 = (monotonicNanos() - began) / toI64(1000000)
960
+ // `u64` arithmetic wraps rather than checks; a clock read after `began`
961
+ // is never behind it, so the difference is the real one.
962
+ const ms: i64 = toI64((toU64(monotonicNanos()) - toU64(began)) / toU64(1000000))
856
963
  return ms > toI64(1073741823) ? 1073741823 : toI32(ms)
857
964
  }
858
965
 
@@ -864,7 +971,20 @@ const pgAsyncSince = (began: i64): i32 => {
864
971
  * many would leave the rest waiting until their time ran out.
865
972
  */
866
973
  const pgAsyncSignal = (pool: PgAsyncPool, w: i32): void => {
867
- const fd: i32 = pool.wakes[w * 2 + 1]
974
+ if (w < 0 || w >= toI32(pool.waiters.length) || w >= toI32(pool.wakePending.length)) {
975
+ // No such wake: nobody waits on it.
976
+ return
977
+ }
978
+ // A wake's pair is `wakes[2w]` (read end) and `wakes[2w + 1]` (write end).
979
+ const start: i32 = pgAsyncPair(w)
980
+ if (start < 0 || start >= toI32(pool.wakes.length)) {
981
+ return
982
+ }
983
+ const end: i32 = start + 1
984
+ if (end >= toI32(pool.wakes.length) || toI32(pool.wakeBytes.length) < 1) {
985
+ return
986
+ }
987
+ const fd: i32 = pool.wakes[end]
868
988
  if (pool.waiters[w] <= 0 || fd < 0) {
869
989
  return
870
990
  }
@@ -873,13 +993,22 @@ const pgAsyncSignal = (pool: PgAsyncPool, w: i32): void => {
873
993
  if (netWrite(fd, pool.wakeBytes, 0, 1) !== 1) {
874
994
  return
875
995
  }
876
- pool.wakePending[w] = 1
877
996
  }
997
+ // The write was a call, so the wake is checked against the arrays again.
998
+ if (
999
+ w >= toI32(pool.waiters.length) ||
1000
+ w >= toI32(pool.wakePending.length) ||
1001
+ w >= toI32(pool.wakeUnseen.length) ||
1002
+ w >= toI32(pool.wakeRings.length)
1003
+ ) {
1004
+ return
1005
+ }
1006
+ pool.wakePending[w] = 1
878
1007
  // Rung again while its byte is there, the byte now stays for every task
879
1008
  // waiting at this ring too: one that waited again after the last ring would
880
1009
  // otherwise see the byte read back before it was polled, and wait for ever.
881
1010
  pool.wakeUnseen[w] = pool.waiters[w]
882
- pool.wakeRings[w] = (pool.wakeRings[w] + 1) % PG_ASYNC_QUEUE_WRAP
1011
+ pool.wakeRings[w] = pgAsyncStep(pool.wakeRings[w], PG_ASYNC_QUEUE_MASK)
883
1012
  }
884
1013
 
885
1014
  /**
@@ -890,7 +1019,15 @@ const pgAsyncSignal = (pool: PgAsyncPool, w: i32): void => {
890
1019
  */
891
1020
  const pgAsyncFreeSeats = (pool: PgAsyncPool): i32 => {
892
1021
  let free: i32 = 0
893
- for (let s: i32 = 0; s < pool.size; s++) {
1022
+ for (
1023
+ let s: i32 = 0;
1024
+ s < toI32(pool.fds.length) &&
1025
+ s < toI32(pool.claimed.length) &&
1026
+ s < toI32(pool.doomAt.length) &&
1027
+ s < toI32(pool.writing.length) &&
1028
+ s < toI32(pool.seated.length);
1029
+ s++
1030
+ ) {
894
1031
  if (
895
1032
  pool.fds[s] >= 0 &&
896
1033
  toI32(pool.claimed[s]) === 0 &&
@@ -898,7 +1035,9 @@ const pgAsyncFreeSeats = (pool: PgAsyncPool): i32 => {
898
1035
  toI32(pool.writing[s]) === 0 &&
899
1036
  pool.seated[s] < pool.depth
900
1037
  ) {
901
- free += pool.depth - pool.seated[s]
1038
+ // In `i64` the sum cannot overflow; it never passes 64 slots of 16 seats.
1039
+ const next: i64 = toI64(free) + toI64(pool.depth) - toI64(pool.seated[s])
1040
+ free = next > toI64(2147483647) ? 2147483647 : toI32(next)
902
1041
  }
903
1042
  }
904
1043
  return free
@@ -911,7 +1050,7 @@ const pgAsyncFreeSeats = (pool: PgAsyncPool): i32 => {
911
1050
  */
912
1051
  const pgAsyncWakePool = (pool: PgAsyncPool): void => {
913
1052
  pgAsyncSignal(pool, PG_ASYNC_POOL_WAKE)
914
- const queued: i32 = (pool.seatTail - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP
1053
+ const queued: i32 = pgAsyncGap(pool.seatTail, pool.seatHead, PG_ASYNC_QUEUE_MASK)
915
1054
  if (queued === 0) {
916
1055
  return
917
1056
  }
@@ -920,16 +1059,26 @@ const pgAsyncWakePool = (pool: PgAsyncPool): void => {
920
1059
  wake = wake > queued ? queued : wake
921
1060
  wake = wake > PG_ASYNC_LANES ? PG_ASYNC_LANES : wake
922
1061
  for (let k: i32 = 0; k < wake; k++) {
923
- pgAsyncSignal(pool, PG_ASYNC_POOL_WAKE + 1 + ((pool.seatHead + k) % PG_ASYNC_LANES))
1062
+ // The queue lane of the `k`th task waiting, after the pool's own wake.
1063
+ const lane: u32 = (toU32(pool.seatHead) + toU32(k)) & toU32(PG_ASYNC_LANES - 1)
1064
+ pgAsyncSignal(pool, toI32(toU32(PG_ASYNC_POOL_WAKE + 1) + lane))
924
1065
  }
925
1066
  }
926
1067
 
927
1068
  /** Reads wake `w`'s byte back once every task it was written for has woken, so its waiters wait again. */
928
1069
  const pgAsyncDrain = (pool: PgAsyncPool, w: i32): void => {
929
- const fd: i32 = pool.wakes[w * 2]
1070
+ if (w < 0 || w >= toI32(pool.wakeUnseen.length) || w >= toI32(pool.wakePending.length)) {
1071
+ // No such wake: no byte to read back.
1072
+ return
1073
+ }
1074
+ const start: i32 = pgAsyncPair(w)
1075
+ if (start < 0 || start >= toI32(pool.wakes.length)) {
1076
+ return
1077
+ }
1078
+ const fd: i32 = pool.wakes[start]
930
1079
  if (toI32(pool.wakePending[w]) === 1 && pool.wakeUnseen[w] <= 0 && fd >= 0) {
931
- netRead(fd, pool.wakeBytes, 0, 8)
932
1080
  pool.wakePending[w] = 0
1081
+ netRead(fd, pool.wakeBytes, 0, 8)
933
1082
  }
934
1083
  }
935
1084
 
@@ -939,24 +1088,60 @@ const pgAsyncDrain = (pool: PgAsyncPool, w: i32): void => {
939
1088
  * A cancelled task returns at once.
940
1089
  */
941
1090
  const pgAsyncPark = async (pool: PgAsyncPool, w: i32, ms: i32): Promise<void> => {
942
- if (pool.wakes[w * 2] < 0 && unixSocketPair(NET_UNIX_STREAM, pool.wakePair) >= 0) {
943
- // Opened before this task counts as waiting, so no byte is written to a
944
- // wake without a pair. Out of descriptors, it sleeps 1 ms and tries again.
945
- pool.wakes[w * 2] = pool.wakePair[0]
946
- pool.wakes[w * 2 + 1] = pool.wakePair[1]
1091
+ const start: i32 = pgAsyncPair(w)
1092
+ if (
1093
+ w < 0 ||
1094
+ start < 0 ||
1095
+ start >= toI32(pool.wakes.length) ||
1096
+ w >= toI32(pool.waiters.length) ||
1097
+ w >= toI32(pool.wakeRings.length)
1098
+ ) {
1099
+ // No such wake: wait as a task with no pair does, then look again.
1100
+ await sleep(1)
1101
+ return
947
1102
  }
948
- const fd: i32 = pool.wakes[w * 2]
1103
+ const end: i32 = start + 1
1104
+ if (pool.wakes[start] < 0 && end < toI32(pool.wakes.length) && toI32(pool.wakePair.length) >= 2) {
1105
+ if (unixSocketPair(NET_UNIX_STREAM, pool.wakePair) >= 0) {
1106
+ // Opened before this task counts as waiting, so no byte is written to a
1107
+ // wake without a pair. Out of descriptors, it sleeps 1 ms and tries again.
1108
+ if (
1109
+ start < toI32(pool.wakes.length) &&
1110
+ end < toI32(pool.wakes.length) &&
1111
+ toI32(pool.wakePair.length) >= 2
1112
+ ) {
1113
+ pool.wakes[start] = pool.wakePair[0]
1114
+ pool.wakes[end] = pool.wakePair[1]
1115
+ }
1116
+ }
1117
+ }
1118
+ if (
1119
+ start >= toI32(pool.wakes.length) ||
1120
+ w >= toI32(pool.waiters.length) ||
1121
+ w >= toI32(pool.wakeRings.length)
1122
+ ) {
1123
+ return
1124
+ }
1125
+ const fd: i32 = pool.wakes[start]
949
1126
  const rings: i32 = pool.wakeRings[w]
950
- pool.waiters[w] += 1
1127
+ pool.waiters[w] = pgAsyncCount(pool.waiters[w])
951
1128
  if (fd < 0) {
952
1129
  await sleep(1)
953
1130
  } else {
954
1131
  await readableWithin(fd, ms)
955
1132
  }
956
- pool.waiters[w] -= 1
1133
+ // The wait was a call, so the wake is checked against the arrays again.
1134
+ if (
1135
+ w >= toI32(pool.waiters.length) ||
1136
+ w >= toI32(pool.wakeRings.length) ||
1137
+ w >= toI32(pool.wakeUnseen.length)
1138
+ ) {
1139
+ return
1140
+ }
1141
+ pool.waiters[w] = pgAsyncUncount(pool.waiters[w])
957
1142
  if (pool.wakeRings[w] !== rings) {
958
1143
  // Waiting when the byte was written: one fewer it waits for.
959
- pool.wakeUnseen[w] -= 1
1144
+ pool.wakeUnseen[w] = pgAsyncUncount(pool.wakeUnseen[w])
960
1145
  }
961
1146
  }
962
1147
 
@@ -982,33 +1167,46 @@ export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
982
1167
  return PG_ASYNC_CANCELLED
983
1168
  }
984
1169
  let live: boolean = false
985
- for (let s: i32 = 0; s < pool.size; s++) {
1170
+ for (
1171
+ let s: i32 = 0;
1172
+ s < toI32(pool.fds.length) &&
1173
+ s < toI32(pool.claimed.length) &&
1174
+ s < toI32(pool.claims.length) &&
1175
+ s < toI32(pool.seated.length) &&
1176
+ s < toI32(pool.doomAt.length);
1177
+ s++
1178
+ ) {
986
1179
  if (pool.fds[s] < 0) {
987
1180
  continue
988
1181
  }
989
1182
  live = true
990
1183
  if (toI32(pool.claimed[s]) === 0 && pool.seated[s] === 0 && pool.doomAt[s] < 0) {
1184
+ // The claim count wraps below 2^24, so in `u32` the ticket, the count
1185
+ // times 64 slots plus the slot, is exact and below 2^30.
1186
+ const claim: u32 = (toU32(pool.claims[s]) + toU32(1)) & toU32(PG_ASYNC_CLAIM_MASK)
991
1187
  pool.claimed[s] = 1
992
- pool.claims[s] = (pool.claims[s] + 1) % PG_ASYNC_CLAIM_WRAP
1188
+ pool.claims[s] = toI32(claim)
993
1189
  if (waited) {
994
1190
  // Another waiter may find room this one did not take.
995
1191
  pgAsyncWakePool(pool)
996
1192
  }
997
- return pool.claims[s] * PG_ASYNC_MAX_SIZE + s
1193
+ return toI32(claim * toU32(PG_ASYNC_MAX_SIZE) + toU32(s))
998
1194
  }
999
1195
  }
1000
1196
  if (!live) {
1001
1197
  return PG_POOL_NONE
1002
1198
  }
1003
- const left: i32 = pool.claimWaitMs - pgAsyncSince(began)
1004
- if (left <= 0) {
1199
+ const limit: i32 = pool.claimWaitMs
1200
+ const since: i32 = pgAsyncSince(began)
1201
+ if (limit <= 0 || since < 0 || since >= limit) {
1005
1202
  return PG_CARRIER_FULL
1006
1203
  }
1204
+ const left: i32 = limit - since
1007
1205
  const skipped: boolean = await pgAsyncSkipAny(pool)
1008
1206
  if (skipped) {
1009
1207
  continue
1010
1208
  }
1011
- pool.waits += 1
1209
+ pool.waits = pgAsyncCount(pool.waits)
1012
1210
  waited = true
1013
1211
  await pgAsyncPark(pool, PG_ASYNC_POOL_WAKE, left)
1014
1212
  pgAsyncDrain(pool, PG_ASYNC_POOL_WAKE)
@@ -1027,14 +1225,24 @@ export const pgAsyncClaim = async (pool: PgAsyncPool): Promise<i32> => {
1027
1225
  */
1028
1226
  export const pgAsyncRelease = (pool: PgAsyncPool, ticket: i32, reusable: boolean): void => {
1029
1227
  const slot: i32 = pgAsyncSlot(pool, ticket)
1228
+ if (
1229
+ slot < 0 ||
1230
+ slot >= toI32(pool.fds.length) ||
1231
+ slot >= toI32(pool.claimed.length) ||
1232
+ slot >= toI32(pool.claims.length)
1233
+ ) {
1234
+ // `pgAsyncSlot` panicked already on a ticket with no slot.
1235
+ return
1236
+ }
1237
+ const fd: i32 = pool.fds[slot]
1238
+ pool.claimed[slot] = 0
1239
+ pool.claims[slot] = pgAsyncStep(pool.claims[slot], PG_ASYNC_CLAIM_MASK)
1030
1240
  if (!reusable) {
1031
- netClose(pool.fds[slot])
1032
1241
  pool.fds[slot] = -1
1033
- pool.dropped += 1
1242
+ pool.dropped = pgAsyncCount(pool.dropped)
1243
+ netClose(fd)
1034
1244
  pgAsyncForget(pool, slot)
1035
1245
  }
1036
- pool.claimed[slot] = 0
1037
- pool.claims[slot] = (pool.claims[slot] + 1) % PG_ASYNC_CLAIM_WRAP
1038
1246
  pgAsyncWakePool(pool)
1039
1247
  }
1040
1248
 
@@ -1068,13 +1276,20 @@ const pgAsyncUnqueue = (pool: PgAsyncPool, n: i32): void => {
1068
1276
  return
1069
1277
  }
1070
1278
  if (n !== pool.seatHead) {
1071
- pool.seatGone[n % PG_ASYNC_QUEUE] = 1
1279
+ const at: i32 = n % PG_ASYNC_QUEUE
1280
+ if (at >= 0 && at < toI32(pool.seatGone.length)) {
1281
+ pool.seatGone[at] = 1
1282
+ }
1072
1283
  return
1073
1284
  }
1074
- pool.seatHead = (pool.seatHead + 1) % PG_ASYNC_QUEUE_WRAP
1075
- while (pool.seatHead !== pool.seatTail && toI32(pool.seatGone[pool.seatHead % PG_ASYNC_QUEUE]) !== 0) {
1076
- pool.seatGone[pool.seatHead % PG_ASYNC_QUEUE] = 0
1077
- pool.seatHead = (pool.seatHead + 1) % PG_ASYNC_QUEUE_WRAP
1285
+ pool.seatHead = pgAsyncStep(pool.seatHead, PG_ASYNC_QUEUE_MASK)
1286
+ while (pool.seatHead !== pool.seatTail) {
1287
+ const at: i32 = pool.seatHead % PG_ASYNC_QUEUE
1288
+ if (at < 0 || at >= toI32(pool.seatGone.length) || toI32(pool.seatGone[at]) === 0) {
1289
+ break
1290
+ }
1291
+ pool.seatGone[at] = 0
1292
+ pool.seatHead = pgAsyncStep(pool.seatHead, PG_ASYNC_QUEUE_MASK)
1078
1293
  }
1079
1294
  pgAsyncWakePool(pool)
1080
1295
  }
@@ -1119,21 +1334,34 @@ export const pgAsyncSeat = async (pool: PgAsyncPool, statement: i32): Promise<i3
1119
1334
  }
1120
1335
  let live: boolean = false
1121
1336
  let best: i32 = -1
1337
+ let bestSeated: i32 = 0
1122
1338
  let free: i32 = 0
1123
- for (let s: i32 = 0; s < pool.size; s++) {
1339
+ for (
1340
+ let s: i32 = 0;
1341
+ s < toI32(pool.fds.length) &&
1342
+ s < toI32(pool.claimed.length) &&
1343
+ s < toI32(pool.doomAt.length) &&
1344
+ s < toI32(pool.seated.length) &&
1345
+ s < toI32(pool.writing.length);
1346
+ s++
1347
+ ) {
1124
1348
  if (pool.fds[s] < 0) {
1125
1349
  continue
1126
1350
  }
1127
1351
  live = true
1128
- if (toI32(pool.claimed[s]) !== 0 || pool.doomAt[s] >= 0 || pool.seated[s] >= pool.depth) {
1352
+ const seated: i32 = pool.seated[s]
1353
+ if (toI32(pool.claimed[s]) !== 0 || pool.doomAt[s] >= 0 || seated >= pool.depth) {
1129
1354
  continue
1130
1355
  }
1131
- free += pool.depth - pool.seated[s]
1356
+ // In `i64` the sum cannot overflow; it never passes 64 slots of 16 seats.
1357
+ const next: i64 = toI64(free) + toI64(pool.depth) - toI64(seated)
1358
+ free = next > toI64(2147483647) ? 2147483647 : toI32(next)
1132
1359
  if (toI32(pool.writing[s]) !== 0) {
1133
1360
  continue
1134
1361
  }
1135
- if (best < 0 || pool.seated[s] < pool.seated[best]) {
1362
+ if (best < 0 || seated < bestSeated) {
1136
1363
  best = s
1364
+ bestSeated = seated
1137
1365
  }
1138
1366
  }
1139
1367
  // First come, first seated: under load a task that lost the seat it was
@@ -1143,52 +1371,77 @@ export const pgAsyncSeat = async (pool: PgAsyncPool, statement: i32): Promise<i3
1143
1371
  // takes one only while none waits.
1144
1372
  const turn: boolean =
1145
1373
  queued >= 0
1146
- ? (queued - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP < free
1374
+ ? pgAsyncGap(queued, pool.seatHead, PG_ASYNC_QUEUE_MASK) < free
1147
1375
  : pool.seatHead === pool.seatTail
1148
1376
  if (best >= 0 && turn) {
1377
+ // `best` is below 64 and `statement` below 64, so in `u32` these
1378
+ // offsets are exact; each is then checked against its arrays.
1379
+ const known: i32 = toI32(toU32(best) * toU32(PG_ASYNC_MAX_STATEMENTS) + toU32(statement))
1149
1380
  for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1150
- const seat: i32 = best * PG_ASYNC_MAX_DEPTH + k
1381
+ const seat: i32 = pgAsyncSeatAt(best, k)
1382
+ if (
1383
+ seat < 0 ||
1384
+ seat >= toI32(pool.seatUsed.length) ||
1385
+ seat >= toI32(pool.seatWaiting.length) ||
1386
+ seat >= toI32(pool.seatSeq.length) ||
1387
+ seat >= toI32(pool.seatStatement.length) ||
1388
+ seat >= toI32(pool.seatParse.length) ||
1389
+ seat >= toI32(pool.seatClaims.length) ||
1390
+ known < 0 ||
1391
+ known >= toI32(pool.prepared.length) ||
1392
+ best >= toI32(pool.nextSeq.length) ||
1393
+ best >= toI32(pool.seated.length) ||
1394
+ best >= toI32(pool.writing.length)
1395
+ ) {
1396
+ // Past the slot's seats: none free on it.
1397
+ break
1398
+ }
1151
1399
  if (toI32(pool.seatUsed[seat]) !== 0) {
1152
1400
  continue
1153
1401
  }
1154
- const known: i32 = best * PG_ASYNC_MAX_STATEMENTS + statement
1402
+ // The seat claim count wraps below 2^20, so the ticket, the count
1403
+ // times 1024 seats plus the seat, is exact in `u32` and below 2^30.
1404
+ const claim: u32 = (toU32(pool.seatClaims[seat]) + toU32(1)) & toU32(PG_ASYNC_SEAT_MASK)
1155
1405
  pool.seatUsed[seat] = 1
1156
1406
  pool.seatWaiting[seat] = 0
1157
1407
  pool.seatSeq[seat] = pool.nextSeq[best]
1158
1408
  pool.seatStatement[seat] = statement
1159
1409
  pool.seatParse[seat] = toI32(pool.prepared[known]) === 0 ? 1 : 0
1160
1410
  pool.prepared[known] = 1
1161
- pool.nextSeq[best] = (pool.nextSeq[best] + 1) % PG_ASYNC_SEQ_WRAP
1162
- pool.seated[best] += 1
1411
+ pool.nextSeq[best] = pgAsyncStep(pool.nextSeq[best], PG_ASYNC_SEQ_MASK)
1412
+ pool.seated[best] = pgAsyncCount(pool.seated[best])
1163
1413
  pool.writing[best] = 1
1164
- pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
1414
+ pool.seatClaims[seat] = toI32(claim)
1165
1415
  // The next in the queue may find a seat this one did not take.
1166
1416
  pgAsyncUnqueue(pool, queued)
1167
- return pool.seatClaims[seat] * PG_ASYNC_SEATS + seat
1417
+ return toI32(claim * toU32(PG_ASYNC_SEATS) + toU32(seat))
1168
1418
  }
1169
1419
  }
1170
1420
  if (!live) {
1171
1421
  pgAsyncUnqueue(pool, queued)
1172
1422
  return PG_POOL_NONE
1173
1423
  }
1174
- const left: i32 = pool.claimWaitMs - pgAsyncSince(began)
1175
- if (left <= 0) {
1424
+ const limit: i32 = pool.claimWaitMs
1425
+ const since: i32 = pgAsyncSince(began)
1426
+ if (limit <= 0 || since < 0 || since >= limit) {
1176
1427
  pgAsyncUnqueue(pool, queued)
1177
1428
  return PG_CARRIER_FULL
1178
1429
  }
1179
- if (
1180
- queued < 0 &&
1181
- (pool.seatTail - pool.seatHead + PG_ASYNC_QUEUE_WRAP) % PG_ASYNC_QUEUE_WRAP < PG_ASYNC_QUEUE
1182
- ) {
1430
+ const left: i32 = limit - since
1431
+ if (queued < 0 && pgAsyncGap(pool.seatTail, pool.seatHead, PG_ASYNC_QUEUE_MASK) < PG_ASYNC_QUEUE) {
1183
1432
  queued = pool.seatTail
1184
- pool.seatTail = (pool.seatTail + 1) % PG_ASYNC_QUEUE_WRAP
1433
+ pool.seatTail = pgAsyncStep(pool.seatTail, PG_ASYNC_QUEUE_MASK)
1185
1434
  }
1186
1435
  const skipped: boolean = await pgAsyncSkipAny(pool)
1187
1436
  if (skipped) {
1188
1437
  continue
1189
1438
  }
1190
- const w: i32 = queued >= 0 ? PG_ASYNC_POOL_WAKE + 1 + (queued % PG_ASYNC_LANES) : PG_ASYNC_POOL_WAKE
1191
- pool.waits += 1
1439
+ // A queued task waits on its queue lane, after the pool's own wake.
1440
+ const w: i32 =
1441
+ queued >= 0
1442
+ ? toI32(toU32(PG_ASYNC_POOL_WAKE + 1) + (toU32(queued) & toU32(PG_ASYNC_LANES - 1)))
1443
+ : PG_ASYNC_POOL_WAKE
1444
+ pool.waits = pgAsyncCount(pool.waits)
1192
1445
  await pgAsyncPark(pool, w, left)
1193
1446
  pgAsyncDrain(pool, w)
1194
1447
  }
@@ -1199,7 +1452,8 @@ const pgAsyncSeatOf = (pool: PgAsyncPool, ticket: i32): i32 => {
1199
1452
  const seat: i32 = ticket >= 0 ? ticket % PG_ASYNC_SEATS : -1
1200
1453
  if (
1201
1454
  seat < 0 ||
1202
- seat >= pool.size * PG_ASYNC_MAX_DEPTH ||
1455
+ seat >= toI32(pool.seatUsed.length) ||
1456
+ seat >= toI32(pool.seatClaims.length) ||
1203
1457
  toI32(pool.seatUsed[seat]) !== 1 ||
1204
1458
  toI32(ticket / PG_ASYNC_SEATS) !== pool.seatClaims[seat]
1205
1459
  ) {
@@ -1227,7 +1481,23 @@ export const pgAsyncSend = async (pool: PgAsyncPool, ticket: i32, params: PgAsyn
1227
1481
  if (cancelled()) {
1228
1482
  return PG_ASYNC_UNSENT_CANCELLED
1229
1483
  }
1484
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1485
+ if (
1486
+ seat < 0 ||
1487
+ seat >= toI32(pool.seatStatement.length) ||
1488
+ seat >= toI32(pool.seatParse.length) ||
1489
+ s < 0 ||
1490
+ s >= toI32(pool.fds.length)
1491
+ ) {
1492
+ // `pgAsyncSeatOf` panicked already on a ticket with no seat.
1493
+ return PG_ASYNC_UNSENT
1494
+ }
1230
1495
  const statement: i32 = pool.seatStatement[seat]
1496
+ if (statement < 0 || statement >= toI32(pool.statements.length)) {
1497
+ // `pgAsyncSeat` seats only a registered statement.
1498
+ return PG_ASYNC_UNSENT
1499
+ }
1500
+ const fd: i32 = pool.fds[s]
1231
1501
  const out: u8[] | null = pgAsyncEncode(
1232
1502
  pool.statements[statement],
1233
1503
  statement,
@@ -1237,10 +1507,10 @@ export const pgAsyncSend = async (pool: PgAsyncPool, ticket: i32, params: PgAsyn
1237
1507
  if (out === null) {
1238
1508
  return PG_ASYNC_UNSENT
1239
1509
  }
1240
- const fd: i32 = pool.fds[toI32(seat / PG_ASYNC_MAX_DEPTH)]
1241
1510
  let sent: i32 = 0
1242
- while (sent < toI32(out.length)) {
1243
- const n: i32 = netWrite(fd, out, sent, toI32(out.length) - sent)
1511
+ while (sent >= 0 && sent < toI32(out.length)) {
1512
+ // Both are at least 0 and `sent` is short of the end, so the `u32` difference is exact.
1513
+ const n: i32 = netWrite(fd, out, sent, toI32(toU32(toI32(out.length)) - toU32(sent)))
1244
1514
  if (n === PG_ASYNC_AGAIN) {
1245
1515
  const waited: boolean = await writable(fd)
1246
1516
  const failed: i32 = pgAsyncWaitFailure(waited)
@@ -1248,44 +1518,106 @@ export const pgAsyncSend = async (pool: PgAsyncPool, ticket: i32, params: PgAsyn
1248
1518
  return PG_ASYNC_UNSENT_CANCELLED
1249
1519
  }
1250
1520
  if (failed !== 0) {
1251
- return PG_ASYNC_BROKEN + failed
1521
+ return pgAsyncBroken(failed)
1252
1522
  }
1253
1523
  } else if (n <= 0) {
1254
- return PG_ASYNC_BROKEN + (n < PG_ASYNC_BROKEN ? n : 0)
1524
+ return n < PG_ASYNC_BROKEN ? pgAsyncBroken(n) : PG_ASYNC_BROKEN
1255
1525
  } else {
1256
- sent += n
1526
+ // A write takes no more than it was given, so `sent` stays within `out`.
1527
+ const next: i64 = toI64(sent) + toI64(n)
1528
+ sent = next > toI64(out.length) ? toI32(out.length) : toI32(next)
1257
1529
  }
1258
1530
  }
1259
1531
  return sent
1260
1532
  }
1261
1533
 
1262
- /** How far `seq` is past slot `s`'s next answer, in the order of its pipeline. */
1263
- const pgAsyncAhead = (pool: PgAsyncPool, s: i32, seq: i32): i32 =>
1264
- (seq - pool.served[s] + PG_ASYNC_SEQ_WRAP) % PG_ASYNC_SEQ_WRAP
1534
+ /**
1535
+ * What `pgAsyncSend` answers for a broken write: `PG_ASYNC_BROKEN` beside
1536
+ * the failure `e` (0 or below), so it stays below -15, and no lower than
1537
+ * the least `i32`.
1538
+ */
1539
+ const pgAsyncBroken = (e: i32): i32 => {
1540
+ const sum: i64 = toI64(PG_ASYNC_BROKEN) + toI64(e)
1541
+ return sum < toI64(-2147483648) ? -2147483648 : toI32(sum)
1542
+ }
1543
+
1544
+ /**
1545
+ * How far `seq` is past `served`, a slot's next answer, in the order of its
1546
+ * pipeline: both wrap below `PG_ASYNC_SEQ_WRAP`.
1547
+ */
1548
+ const pgAsyncAhead = (served: i32, seq: i32): i32 => pgAsyncGap(seq, served, PG_ASYNC_SEQ_MASK)
1265
1549
 
1266
- /** Whether seat `seat`'s answer is lost: its connection failed at or before it. */
1550
+ /**
1551
+ * Where slot `s`'s `k`th seat is in the seat arrays, `s * PG_ASYNC_MAX_DEPTH
1552
+ * + k`: in `u32` the sum wraps rather than checks, and every caller checks
1553
+ * the seat against the arrays it reads.
1554
+ */
1555
+ const pgAsyncSeatAt = (s: i32, k: i32): i32 => toI32(toU32(s) * toU32(PG_ASYNC_MAX_DEPTH) + toU32(k))
1556
+
1557
+ /**
1558
+ * Whether seat `seat`'s answer is lost: its connection failed at or before
1559
+ * it. A seat that is not in the pool has no answer to read, so it counts as
1560
+ * lost.
1561
+ */
1267
1562
  const pgAsyncLostSeat = (pool: PgAsyncPool, seat: i32): boolean => {
1268
1563
  const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1564
+ if (
1565
+ seat < 0 ||
1566
+ s < 0 ||
1567
+ seat >= toI32(pool.seatSeq.length) ||
1568
+ s >= toI32(pool.doomAt.length) ||
1569
+ s >= toI32(pool.served.length)
1570
+ ) {
1571
+ return true
1572
+ }
1269
1573
  const at: i32 = pool.doomAt[s]
1270
- return at >= 0 && pgAsyncAhead(pool, s, pool.seatSeq[seat]) >= pgAsyncAhead(pool, s, at)
1574
+ const served: i32 = pool.served[s]
1575
+ return at >= 0 && pgAsyncAhead(served, pool.seatSeq[seat]) >= pgAsyncAhead(served, at)
1271
1576
  }
1272
1577
 
1578
+ /**
1579
+ * Whether seat `seat`'s answer is the next its connection gives, lost or
1580
+ * not. A seat that is not in the pool is never served.
1581
+ */
1582
+ const pgAsyncServed = (pool: PgAsyncPool, seat: i32): boolean => {
1583
+ const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1584
+ if (seat < 0 || s < 0 || seat >= toI32(pool.seatSeq.length) || s >= toI32(pool.served.length)) {
1585
+ return false
1586
+ }
1587
+ return pool.served[s] === pool.seatSeq[seat]
1588
+ }
1589
+
1590
+ /**
1591
+ * Whether seat `seat`'s answer is the next its connection gives and is not
1592
+ * lost. A seat that is not in the pool never has its turn.
1593
+ */
1594
+ const pgAsyncInTurn = (pool: PgAsyncPool, seat: i32): boolean =>
1595
+ pgAsyncServed(pool, seat) && !pgAsyncLostSeat(pool, seat)
1596
+
1273
1597
  /** The turn lane seat `seat` waits on: distinct for the seats of any eight slots in a row. */
1274
1598
  const pgAsyncTurnLane = (seat: i32): i32 => seat % PG_ASYNC_LANES
1275
1599
 
1276
1600
  /**
1277
1601
  * Whether a task waiting on slot `s`, other than `except`'s, may go on: its
1278
1602
  * turn came, its answer is lost, or an abandoned answer ahead of it waits to
1279
- * be read past.
1603
+ * be read past. No task waits on a slot that is not in the pool.
1280
1604
  */
1281
1605
  const pgAsyncReady = (pool: PgAsyncPool, s: i32, except: i32): boolean => {
1606
+ if (s < 0 || s >= toI32(pool.served.length)) {
1607
+ return false
1608
+ }
1609
+ const served: i32 = pool.served[s]
1282
1610
  let waiting: boolean = false
1283
1611
  for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1284
- const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1612
+ const seat: i32 = pgAsyncSeatAt(s, k)
1613
+ if (seat < 0 || seat >= toI32(pool.seatWaiting.length) || seat >= toI32(pool.seatSeq.length)) {
1614
+ // Past the pool's seats: none more on this slot.
1615
+ break
1616
+ }
1285
1617
  if (seat === except || toI32(pool.seatWaiting[seat]) === 0) {
1286
1618
  continue
1287
1619
  }
1288
- if (pool.seatSeq[seat] === pool.served[s] || pgAsyncLostSeat(pool, seat)) {
1620
+ if (pool.seatSeq[seat] === served || pgAsyncLostSeat(pool, seat)) {
1289
1621
  return true
1290
1622
  }
1291
1623
  waiting = true
@@ -1310,11 +1642,20 @@ const pgAsyncWakeTurns = (pool: PgAsyncPool, s: i32, except: i32): void => {
1310
1642
  }
1311
1643
  let after: i32 = -1
1312
1644
  for (let n: i32 = 0; n < PG_ASYNC_MAX_DEPTH; n++) {
1645
+ // Read again each round: the signal below is a call.
1646
+ if (s < 0 || s >= toI32(pool.served.length)) {
1647
+ return
1648
+ }
1649
+ const served: i32 = pool.served[s]
1313
1650
  let next: i32 = -1
1314
1651
  let nextAhead: i32 = PG_ASYNC_SEQ_WRAP
1315
1652
  for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1316
- const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1317
- const ahead: i32 = pgAsyncAhead(pool, s, pool.seatSeq[seat])
1653
+ const seat: i32 = pgAsyncSeatAt(s, k)
1654
+ if (seat < 0 || seat >= toI32(pool.seatSeq.length) || seat >= toI32(pool.seatWaiting.length)) {
1655
+ // Past the pool's seats: none more on this slot.
1656
+ break
1657
+ }
1658
+ const ahead: i32 = pgAsyncAhead(served, pool.seatSeq[seat])
1318
1659
  if (seat !== except && toI32(pool.seatWaiting[seat]) === 1 && ahead > after && ahead < nextAhead) {
1319
1660
  next = seat
1320
1661
  nextAhead = ahead
@@ -1330,16 +1671,34 @@ const pgAsyncWakeTurns = (pool: PgAsyncPool, s: i32, except: i32): void => {
1330
1671
 
1331
1672
  /**
1332
1673
  * Marks slot `s` lost from sequence number `seq` on, settles the abandoned
1333
- * seats it loses, and wakes those it fails.
1674
+ * seats it loses, and wakes those it fails. A slot that is not in the pool
1675
+ * has nothing to lose.
1334
1676
  */
1335
1677
  const pgAsyncDoom = (pool: PgAsyncPool, s: i32, seq: i32): void => {
1336
- if (pool.doomAt[s] < 0 || pgAsyncAhead(pool, s, seq) < pgAsyncAhead(pool, s, pool.doomAt[s])) {
1678
+ if (s < 0 || s >= toI32(pool.doomAt.length) || s >= toI32(pool.served.length)) {
1679
+ return
1680
+ }
1681
+ const at: i32 = pool.doomAt[s]
1682
+ const served: i32 = pool.served[s]
1683
+ if (at < 0 || pgAsyncAhead(served, seq) < pgAsyncAhead(served, at)) {
1337
1684
  pool.doomAt[s] = seq
1338
1685
  }
1339
1686
  // A seat freed here closes the connection only once no seat is left on it;
1340
1687
  // the one being read past is settled by its reader.
1341
1688
  for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1342
- const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1689
+ const seat: i32 = pgAsyncSeatAt(s, k)
1690
+ // Checked each round: settling a seat is a call.
1691
+ if (
1692
+ seat < 0 ||
1693
+ seat >= toI32(pool.seatAbandoned.length) ||
1694
+ seat >= toI32(pool.seatSeq.length) ||
1695
+ seat >= toI32(pool.seatUsed.length) ||
1696
+ s >= toI32(pool.skipping.length) ||
1697
+ s >= toI32(pool.served.length)
1698
+ ) {
1699
+ // Past the pool's seats: none more on this slot.
1700
+ break
1701
+ }
1343
1702
  const state: i32 = toI32(pool.seatAbandoned[seat])
1344
1703
  const reading: boolean = toI32(pool.skipping[s]) === 1 && pool.seatSeq[seat] === pool.served[s]
1345
1704
  if (
@@ -1357,9 +1716,13 @@ const pgAsyncDoom = (pool: PgAsyncPool, s: i32, seq: i32): void => {
1357
1716
  /**
1358
1717
  * Leaves seat `seat` to the pool: its task was cancelled with its answer
1359
1718
  * unread, so the next task to wait on the connection, or for a seat on it,
1360
- * reads past that answer instead of the connection being closed.
1719
+ * reads past that answer instead of the connection being closed. A seat that
1720
+ * is not in the pool has nothing to leave.
1361
1721
  */
1362
1722
  const pgAsyncAbandon = (pool: PgAsyncPool, seat: i32): void => {
1723
+ if (seat < 0 || seat >= toI32(pool.seatAbandoned.length)) {
1724
+ return
1725
+ }
1363
1726
  const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
1364
1727
  pool.seatAbandoned[seat] = 1
1365
1728
  pgAsyncWakeTurns(pool, s, seat)
@@ -1368,9 +1731,13 @@ const pgAsyncAbandon = (pool: PgAsyncPool, seat: i32): void => {
1368
1731
 
1369
1732
  /**
1370
1733
  * An abandoned seat whose answer is read past or lost: freed once its ticket is
1371
- * spent, else marked so `pgAsyncDone` frees it.
1734
+ * spent, else marked so `pgAsyncDone` frees it. A seat that is not in the pool
1735
+ * has nothing to settle.
1372
1736
  */
1373
1737
  const pgAsyncSettle = (pool: PgAsyncPool, seat: i32): void => {
1738
+ if (seat < 0 || seat >= toI32(pool.seatAbandoned.length)) {
1739
+ return
1740
+ }
1374
1741
  if (toI32(pool.seatAbandoned[seat]) === 2) {
1375
1742
  pgAsyncFree(pool, seat)
1376
1743
  } else {
@@ -1380,16 +1747,34 @@ const pgAsyncSettle = (pool: PgAsyncPool, seat: i32): void => {
1380
1747
 
1381
1748
  /** The abandoned seat in turn on slot `s` when no task reads past it yet, or -1. */
1382
1749
  const pgAsyncSkippable = (pool: PgAsyncPool, s: i32): i32 => {
1750
+ if (
1751
+ s < 0 ||
1752
+ s >= toI32(pool.fds.length) ||
1753
+ s >= toI32(pool.skipping.length) ||
1754
+ s >= toI32(pool.served.length)
1755
+ ) {
1756
+ return -1
1757
+ }
1383
1758
  if (pool.fds[s] < 0 || toI32(pool.skipping[s]) !== 0) {
1384
1759
  return -1
1385
1760
  }
1761
+ const served: i32 = pool.served[s]
1386
1762
  for (let k: i32 = 0; k < PG_ASYNC_MAX_DEPTH; k++) {
1387
- const seat: i32 = s * PG_ASYNC_MAX_DEPTH + k
1763
+ const seat: i32 = pgAsyncSeatAt(s, k)
1764
+ if (
1765
+ seat < 0 ||
1766
+ seat >= toI32(pool.seatAbandoned.length) ||
1767
+ seat >= toI32(pool.seatUsed.length) ||
1768
+ seat >= toI32(pool.seatSeq.length)
1769
+ ) {
1770
+ // Past the pool's seats: none more on this slot.
1771
+ break
1772
+ }
1388
1773
  const state: i32 = toI32(pool.seatAbandoned[seat])
1389
1774
  if (
1390
1775
  toI32(pool.seatUsed[seat]) === 1 &&
1391
1776
  (state === 1 || state === 2) &&
1392
- pool.seatSeq[seat] === pool.served[s] &&
1777
+ pool.seatSeq[seat] === served &&
1393
1778
  !pgAsyncLostSeat(pool, seat)
1394
1779
  ) {
1395
1780
  return seat
@@ -1398,41 +1783,151 @@ const pgAsyncSkippable = (pool: PgAsyncPool, s: i32): i32 => {
1398
1783
  return -1
1399
1784
  }
1400
1785
 
1786
+ /**
1787
+ * Moves the unread bytes of slot `s` to the front of `input`, its input, and
1788
+ * answers where the next read goes. It answers -1 when the input has no room
1789
+ * left, when its marks are out of order (`pgAsyncAnswer` then fails the
1790
+ * answer, or the reader past it loses the connection), and for a slot that
1791
+ * is not in the pool.
1792
+ */
1793
+ const pgAsyncRoom = (pool: PgAsyncPool, s: i32, input: u8[]): i32 => {
1794
+ if (s < 0 || s >= toI32(pool.inStart.length) || s >= toI32(pool.inEnd.length)) {
1795
+ return -1
1796
+ }
1797
+ const start: i32 = pool.inStart[s]
1798
+ const end: i32 = pool.inEnd[s]
1799
+ if (start < 0 || end < start || end > toI32(input.length)) {
1800
+ return -1
1801
+ }
1802
+ let room: i32 = end
1803
+ if (start > 0) {
1804
+ // In `u32`: `end` is at or past `start`, so the difference is the bytes kept.
1805
+ room = toI32(toU32(end) - toU32(start))
1806
+ if (!tryCopyBytes(input, 0, input, start, room)) {
1807
+ return -1
1808
+ }
1809
+ pool.inEnd[s] = room
1810
+ pool.inStart[s] = 0
1811
+ }
1812
+ return room < toI32(input.length) ? room : -1
1813
+ }
1814
+
1815
+ /**
1816
+ * Records `got` more bytes read into slot `s`'s input at `end`, where
1817
+ * `pgAsyncRoom` put the read: a read takes no more than it was given, so the
1818
+ * sum stays within the input's `length`.
1819
+ */
1820
+ const pgAsyncTook = (pool: PgAsyncPool, s: i32, end: i32, got: i32, length: i32): void => {
1821
+ if (s < 0 || s >= toI32(pool.inEnd.length)) {
1822
+ return
1823
+ }
1824
+ const next: i64 = toI64(end) + toI64(got)
1825
+ pool.inEnd[s] = next > toI64(length) ? length : toI32(next)
1826
+ }
1827
+
1828
+ /**
1829
+ * Marks the statement seat `seat` runs on slot `s` as not prepared, so the
1830
+ * next seat that runs it sends its Parse again. A seat or statement out of
1831
+ * the pool's range has nothing prepared.
1832
+ */
1833
+ const pgAsyncUnprepare = (pool: PgAsyncPool, s: i32, seat: i32): void => {
1834
+ // 64 is both PG_ASYNC_MAX_SIZE and PG_ASYNC_MAX_STATEMENTS, written as a
1835
+ // literal: the prover takes a bound from a literal but not from a module
1836
+ // constant, and the bounds prove the offset below cannot overflow.
1837
+ if (s < 0 || s >= 64 || seat < 0 || seat >= toI32(pool.seatStatement.length)) {
1838
+ return
1839
+ }
1840
+ const q: i32 = pool.seatStatement[seat]
1841
+ if (q < 0 || q >= 64) {
1842
+ return
1843
+ }
1844
+ const at: i32 = s * PG_ASYNC_MAX_STATEMENTS + q
1845
+ if (at < toI32(pool.prepared.length)) {
1846
+ pool.prepared[at] = 0
1847
+ }
1848
+ }
1849
+
1850
+ /**
1851
+ * Moves slot `s` past the answer in turn, seat `seat`'s at sequence number
1852
+ * `seq`: its input to where the answer ends, and its order to the next seat.
1853
+ * A Parse in the seat's write the answer does not show taken marks its
1854
+ * statement for parsing again. A slot or seat that is not in the pool has
1855
+ * nothing to move past.
1856
+ */
1857
+ const pgAsyncPast = (pool: PgAsyncPool, s: i32, seat: i32, seq: i32): void => {
1858
+ if (
1859
+ s < 0 ||
1860
+ s >= toI32(pool.inStart.length) ||
1861
+ s >= toI32(pool.inEnd.length) ||
1862
+ s >= toI32(pool.inAnswer.length) ||
1863
+ s >= toI32(pool.inParsed.length) ||
1864
+ s >= toI32(pool.served.length) ||
1865
+ seat < 0 ||
1866
+ seat >= toI32(pool.seatParse.length)
1867
+ ) {
1868
+ return
1869
+ }
1870
+ const end: i32 = pool.inEnd[s]
1871
+ const start: i32 = pool.inAnswer[s] >= 0 ? pool.inAnswer[s] : end
1872
+ if (start === end) {
1873
+ pool.inStart[s] = 0
1874
+ pool.inEnd[s] = 0
1875
+ } else {
1876
+ pool.inStart[s] = start
1877
+ }
1878
+ pool.served[s] = pgAsyncStep(seq, PG_ASYNC_SEQ_MASK)
1879
+ if (toI32(pool.seatParse[seat]) === 1 && toI32(pool.inParsed[s]) === 0) {
1880
+ pgAsyncUnprepare(pool, s, seat)
1881
+ }
1882
+ }
1883
+
1884
+ /** Marks slot `s` as read by no task, when it is in the pool. */
1885
+ const pgAsyncUnskip = (pool: PgAsyncPool, s: i32): void => {
1886
+ if (s >= 0 && s < toI32(pool.skipping.length)) {
1887
+ pool.skipping[s] = 0
1888
+ }
1889
+ }
1890
+
1401
1891
  /**
1402
1892
  * Reads past the answer of `seat`, an abandoned seat in turn on slot `s`,
1403
1893
  * and serves the next. An answer that is not a plain one ending idle (a
1404
1894
  * frame this module does not expect, a transaction left open, a setting
1405
1895
  * changed) or larger than the pool's input loses the connection from it on,
1406
1896
  * as does a socket error. A cancelled reader stops and leaves the bytes read
1407
- * for the next.
1897
+ * for the next. A slot that is not in the pool has nothing to read past.
1408
1898
  */
1409
1899
  const pgAsyncSkip = async (pool: PgAsyncPool, s: i32, seat: i32): Promise<void> => {
1900
+ if (
1901
+ s < 0 ||
1902
+ s >= toI32(pool.served.length) ||
1903
+ s >= toI32(pool.fds.length) ||
1904
+ s >= toI32(pool.inputs.length) ||
1905
+ s >= toI32(pool.skipping.length)
1906
+ ) {
1907
+ return
1908
+ }
1410
1909
  const seq: i32 = pool.served[s]
1411
1910
  const fd: i32 = pool.fds[s]
1412
1911
  const input: u8[] = pool.inputs[s]
1413
1912
  pool.skipping[s] = 1
1414
1913
  let fit: boolean = true
1415
1914
  while (!pgAsyncScan(pool, s)) {
1416
- if (pool.inStart[s] > 0) {
1417
- copyBytes(input, 0, input, pool.inStart[s], pool.inEnd[s] - pool.inStart[s])
1418
- pool.inEnd[s] -= pool.inStart[s]
1419
- pool.inStart[s] = 0
1420
- }
1421
- if (pool.inEnd[s] >= toI32(input.length)) {
1915
+ const end: i32 = pgAsyncRoom(pool, s, input)
1916
+ if (end < 0 || end >= toI32(input.length)) {
1422
1917
  fit = false
1423
1918
  break
1424
1919
  }
1425
- const got: i32 = netRead(fd, input, pool.inEnd[s], toI32(input.length) - pool.inEnd[s])
1920
+ const got: i32 = netRead(fd, input, end, toI32(input.length) - end)
1426
1921
  if (got === PG_ASYNC_AGAIN) {
1427
1922
  const waited: boolean = await readable(fd)
1428
1923
  if (pgAsyncLostSeat(pool, seat)) {
1429
- pool.skipping[s] = 0
1924
+ pgAsyncUnskip(pool, s)
1430
1925
  pgAsyncSettle(pool, seat)
1431
1926
  return
1432
1927
  }
1433
1928
  if (!waited && cancelled()) {
1434
1929
  // Another task reads on from where this one stopped.
1435
- pool.skipping[s] = 0
1930
+ pgAsyncUnskip(pool, s)
1436
1931
  pgAsyncWakeTurns(pool, s, -1)
1437
1932
  pgAsyncWakePool(pool)
1438
1933
  return
@@ -1445,23 +1940,16 @@ const pgAsyncSkip = async (pool: PgAsyncPool, s: i32, seat: i32): Promise<void>
1445
1940
  fit = false
1446
1941
  break
1447
1942
  } else {
1448
- pool.inEnd[s] += got
1943
+ pgAsyncTook(pool, s, end, got, toI32(input.length))
1449
1944
  }
1450
1945
  }
1451
- pool.skipping[s] = 0
1452
- if (!fit || pool.inAnswer[s] < 0 || !pgAsyncPlain(pool, s)) {
1946
+ pgAsyncUnskip(pool, s)
1947
+ // `pgAsyncPlain` answers false for an answer with no end found.
1948
+ if (!fit || !pgAsyncPlain(pool, s)) {
1453
1949
  pgAsyncDoom(pool, s, seq)
1454
1950
  return
1455
1951
  }
1456
- pool.inStart[s] = pool.inAnswer[s]
1457
- if (pool.inStart[s] === pool.inEnd[s]) {
1458
- pool.inStart[s] = 0
1459
- pool.inEnd[s] = 0
1460
- }
1461
- pool.served[s] = (seq + 1) % PG_ASYNC_SEQ_WRAP
1462
- if (toI32(pool.seatParse[seat]) === 1 && toI32(pool.inParsed[s]) === 0) {
1463
- pool.prepared[s * PG_ASYNC_MAX_STATEMENTS + pool.seatStatement[seat]] = 0
1464
- }
1952
+ pgAsyncPast(pool, s, seat, seq)
1465
1953
  pgAsyncSettle(pool, seat)
1466
1954
  pgAsyncWakeTurns(pool, s, -1)
1467
1955
  pgAsyncWakePool(pool)
@@ -1470,22 +1958,47 @@ const pgAsyncSkip = async (pool: PgAsyncPool, s: i32, seat: i32): Promise<void>
1470
1958
  /**
1471
1959
  * Whether the answer in turn on slot `s`, at `[inStart, inAnswer)`, leaves
1472
1960
  * the connection as it found it: only the frames a statement's answer has,
1473
- * ending with a ReadyForQuery that is idle.
1961
+ * ending with a ReadyForQuery that is idle. An answer with no end found, or
1962
+ * a slot that is not in the pool, is not one.
1474
1963
  */
1475
1964
  const pgAsyncPlain = (pool: PgAsyncPool, s: i32): boolean => {
1965
+ if (
1966
+ s < 0 ||
1967
+ s >= toI32(pool.inputs.length) ||
1968
+ s >= toI32(pool.inAnswer.length) ||
1969
+ s >= toI32(pool.inStart.length)
1970
+ ) {
1971
+ return false
1972
+ }
1476
1973
  const input: u8[] = pool.inputs[s]
1974
+ const length: i32 = toI32(input.length)
1477
1975
  const stop: i32 = pool.inAnswer[s]
1976
+ if (stop < 0 || stop > length) {
1977
+ return false
1978
+ }
1478
1979
  let at: i32 = pool.inStart[s]
1479
- while (at >= 0 && at + 5 < toI32(input.length) && at + 5 <= stop && stop <= toI32(input.length)) {
1980
+ // `at < length - 5` and `at <= stop - 5` are `at + 5 < length` and
1981
+ // `at + 5 <= stop`, written so they cannot overflow.
1982
+ while (at >= 0 && at < length - 5 && at <= stop - 5) {
1480
1983
  const type: i32 = toI32(input[at])
1481
- const next: i32 = at + 1 + getI32BE(input, at + 1)
1482
- // Not reached: `pgAsyncScan` refused a length under 4 before this answer
1483
- // could be read past. Kept so this walk does not rest on that.
1484
- if (next < at + 5) {
1984
+ // The frame's length, read here rather than with `getI32BE`, whose call
1985
+ // would end what the prover knows of `input`.
1986
+ const size: i32 =
1987
+ (toI32(input[at + 1]) << 24) |
1988
+ (toI32(input[at + 2]) << 16) |
1989
+ (toI32(input[at + 3]) << 8) |
1990
+ toI32(input[at + 4])
1991
+ // Not reached for a length under 4: `pgAsyncScan` refused one before this
1992
+ // answer could be read past. Kept so this walk does not rest on that. A
1993
+ // frame past `stop` is not one of this answer's.
1994
+ const left: i32 = stop - at
1995
+ if (size < 4 || size >= left) {
1485
1996
  return false
1486
1997
  }
1998
+ // In `u32`: the frame ends at or before `stop`, so the sum cannot wrap.
1999
+ const next: i32 = toI32(toU32(at) + toU32(1) + toU32(size))
1487
2000
  if (type === 90) {
1488
- return next === stop && next - at === 6 && toI32(input[at + 5]) === PG_ASYNC_IDLE
2001
+ return next === stop && size === 5 && toI32(input[at + 5]) === PG_ASYNC_IDLE
1489
2002
  }
1490
2003
  if (
1491
2004
  type !== 49 &&
@@ -1523,20 +2036,35 @@ const pgAsyncSkipAny = async (pool: PgAsyncPool): Promise<boolean> => {
1523
2036
 
1524
2037
  /**
1525
2038
  * Gives seat `seat` back; the connection closes once a lost one has no seat
1526
- * left. Wakes the tasks waiting for room.
2039
+ * left. Wakes the tasks waiting for room. A seat that is not in the pool has
2040
+ * nothing to give back.
1527
2041
  */
1528
2042
  const pgAsyncFree = (pool: PgAsyncPool, seat: i32): void => {
1529
2043
  const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
2044
+ if (
2045
+ seat < 0 ||
2046
+ s < 0 ||
2047
+ seat >= toI32(pool.seatUsed.length) ||
2048
+ seat >= toI32(pool.seatWaiting.length) ||
2049
+ seat >= toI32(pool.seatAbandoned.length) ||
2050
+ seat >= toI32(pool.seatClaims.length) ||
2051
+ s >= toI32(pool.seated.length) ||
2052
+ s >= toI32(pool.doomAt.length) ||
2053
+ s >= toI32(pool.fds.length)
2054
+ ) {
2055
+ return
2056
+ }
1530
2057
  pool.seatUsed[seat] = 0
1531
2058
  pool.seatWaiting[seat] = 0
1532
2059
  pool.seatAbandoned[seat] = 0
1533
- pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
1534
- pool.seated[s] -= 1
2060
+ pool.seatClaims[seat] = pgAsyncStep(pool.seatClaims[seat], PG_ASYNC_SEAT_MASK)
2061
+ pool.seated[s] = pgAsyncUncount(pool.seated[s])
1535
2062
  if (pool.doomAt[s] >= 0 && pool.seated[s] === 0) {
1536
- if (pool.fds[s] >= 0) {
1537
- netClose(pool.fds[s])
2063
+ const fd: i32 = pool.fds[s]
2064
+ if (fd >= 0) {
1538
2065
  pool.fds[s] = -1
1539
- pool.dropped += 1
2066
+ pool.dropped = pgAsyncCount(pool.dropped)
2067
+ netClose(fd)
1540
2068
  }
1541
2069
  pgAsyncForget(pool, s)
1542
2070
  }
@@ -1546,24 +2074,53 @@ const pgAsyncFree = (pool: PgAsyncPool, seat: i32): void => {
1546
2074
  /**
1547
2075
  * Whether the answer in turn on slot `s` lies whole in its input, from
1548
2076
  * `inStart`: `inAnswer` is set to where it ends, past its ReadyForQuery, or
1549
- * to -1 for a frame length no answer has, which `pgAsyncAnswer` fails.
2077
+ * to -1 for a frame length no answer has, which `pgAsyncAnswer` fails. A
2078
+ * slot that is not in the pool, or whose marks are out of order, holds no
2079
+ * whole answer.
1550
2080
  */
1551
2081
  const pgAsyncScan = (pool: PgAsyncPool, s: i32): boolean => {
2082
+ if (
2083
+ s < 0 ||
2084
+ s >= toI32(pool.inputs.length) ||
2085
+ s >= toI32(pool.inEnd.length) ||
2086
+ s >= toI32(pool.inStart.length) ||
2087
+ s >= toI32(pool.inParsed.length) ||
2088
+ s >= toI32(pool.inAnswer.length)
2089
+ ) {
2090
+ return false
2091
+ }
1552
2092
  const input: u8[] = pool.inputs[s]
2093
+ const length: i32 = toI32(input.length)
1553
2094
  const end: i32 = pool.inEnd[s]
2095
+ const most: i32 = pool.maxMessage
2096
+ if (end < 0 || end > length) {
2097
+ return false
2098
+ }
1554
2099
  let at: i32 = pool.inStart[s]
1555
2100
  pool.inParsed[s] = 0
1556
- while (end - at >= 5 && at >= 0 && at + 5 <= toI32(input.length)) {
1557
- const length: i32 = getI32BE(input, at + 1)
1558
- if (length < 4 || length > pool.maxMessage) {
2101
+ // `at < length - 4` is `at + 5 <= length`, written so it cannot overflow.
2102
+ while (at >= 0 && at < length - 4) {
2103
+ const left: i32 = end - at
2104
+ if (left < 5) {
2105
+ return false
2106
+ }
2107
+ // Read here rather than with `getI32BE`, whose call would end what the
2108
+ // prover knows of `input` and the pool's arrays.
2109
+ const size: i32 =
2110
+ (toI32(input[at + 1]) << 24) |
2111
+ (toI32(input[at + 2]) << 16) |
2112
+ (toI32(input[at + 3]) << 8) |
2113
+ toI32(input[at + 4])
2114
+ if (size < 4 || size > most) {
1559
2115
  pool.inAnswer[s] = -1
1560
2116
  return true
1561
2117
  }
1562
- if (end - at - 1 < length) {
2118
+ if (left - 1 < size) {
1563
2119
  return false
1564
2120
  }
1565
2121
  const type: i32 = toI32(input[at])
1566
- at += 1 + length
2122
+ // In `u32`: the frame ends at or before `end`, so the sum cannot wrap.
2123
+ at = toI32(toU32(at) + toU32(1) + toU32(size))
1567
2124
  if (type === 49) {
1568
2125
  pool.inParsed[s] = 1
1569
2126
  }
@@ -1598,6 +2155,17 @@ export const pgAsyncTurn = async (pool: PgAsyncPool, ticket: i32, sent: i32): Pr
1598
2155
  pgAsyncCheckCaps(pool)
1599
2156
  const seat: i32 = pgAsyncSeatOf(pool, ticket)
1600
2157
  const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
2158
+ if (
2159
+ seat < 0 ||
2160
+ s < 0 ||
2161
+ seat >= toI32(pool.seatSeq.length) ||
2162
+ seat >= toI32(pool.seatWaiting.length) ||
2163
+ s >= toI32(pool.writing.length)
2164
+ ) {
2165
+ // Not reached: `pgAsyncSeatOf` panicked on a ticket of no seat. A seat
2166
+ // out of the pool's arrays has no answer to wait for.
2167
+ return PG_ASYNC_BROKEN
2168
+ }
1601
2169
  const seq: i32 = pool.seatSeq[seat]
1602
2170
  if (sent === PG_ASYNC_UNSENT || sent === PG_ASYNC_UNSENT_CANCELLED) {
1603
2171
  // Nothing went out; `pgAsyncDone` hands its place in the order back
@@ -1605,15 +2173,17 @@ export const pgAsyncTurn = async (pool: PgAsyncPool, ticket: i32, sent: i32): Pr
1605
2173
  return sent
1606
2174
  }
1607
2175
  pool.writing[s] = 0
2176
+ if (sent >= 0) {
2177
+ pool.seatWaiting[seat] = 1
2178
+ }
1608
2179
  pgAsyncWakePool(pool)
1609
2180
  if (sent < 0) {
1610
2181
  pgAsyncDoom(pool, s, seq)
1611
2182
  return sent <= PG_ASYNC_BROKEN ? sent : PG_ASYNC_BROKEN
1612
2183
  }
1613
- pool.seatWaiting[seat] = 1
1614
2184
  let gaveUp: boolean = false
1615
2185
  let yields: i32 = 0
1616
- while (pool.served[s] !== seq && !pgAsyncLostSeat(pool, seat)) {
2186
+ while (!pgAsyncServed(pool, seat) && !pgAsyncLostSeat(pool, seat)) {
1617
2187
  if (cancelled()) {
1618
2188
  gaveUp = true
1619
2189
  break
@@ -1627,54 +2197,60 @@ export const pgAsyncTurn = async (pool: PgAsyncPool, ticket: i32, sent: i32): Pr
1627
2197
  yields += 1
1628
2198
  await sleep(0)
1629
2199
  } else {
1630
- pool.turnWaits += 1
2200
+ pool.turnWaits = pgAsyncCount(pool.turnWaits)
1631
2201
  await pgAsyncPark(pool, pgAsyncTurnLane(seat), -1)
1632
2202
  // The last of the waiters the byte woke reads it, as in the claim and
1633
2203
  // seat loops: a seat that waits again must not park on a byte nobody reads.
1634
2204
  pgAsyncDrain(pool, pgAsyncTurnLane(seat))
1635
2205
  }
1636
2206
  }
1637
- pool.seatWaiting[seat] = 0
2207
+ // Checked again: the waits above are calls.
2208
+ if (seat < toI32(pool.seatWaiting.length)) {
2209
+ pool.seatWaiting[seat] = 0
2210
+ }
1638
2211
  pgAsyncDrain(pool, pgAsyncTurnLane(seat))
1639
2212
  if (pgAsyncLostSeat(pool, seat)) {
1640
- return PG_ASYNC_BROKEN + (cancelled() ? PG_ASYNC_CANCELLED : 0)
2213
+ return pgAsyncBroken(cancelled() ? PG_ASYNC_CANCELLED : 0)
1641
2214
  }
1642
2215
  if (gaveUp) {
1643
2216
  // Its answer is on its way and this task will not read it: the next one does.
1644
2217
  pgAsyncAbandon(pool, seat)
1645
2218
  return PG_ASYNC_BROKEN + PG_ASYNC_CANCELLED
1646
2219
  }
2220
+ if (s >= toI32(pool.fds.length) || s >= toI32(pool.inputs.length)) {
2221
+ // Not reached: the slot's arrays are as long as `seatSeq` is in slots.
2222
+ pgAsyncDoom(pool, s, seq)
2223
+ return PG_ASYNC_BROKEN
2224
+ }
1647
2225
  const fd: i32 = pool.fds[s]
1648
2226
  const input: u8[] = pool.inputs[s]
1649
2227
  while (!pgAsyncScan(pool, s)) {
1650
- if (pool.inStart[s] > 0) {
1651
- copyBytes(input, 0, input, pool.inStart[s], pool.inEnd[s] - pool.inStart[s])
1652
- pool.inEnd[s] -= pool.inStart[s]
1653
- pool.inStart[s] = 0
1654
- }
1655
- if (pool.inEnd[s] >= toI32(input.length)) {
2228
+ const end: i32 = pgAsyncRoom(pool, s, input)
2229
+ if (end < 0 || end >= toI32(input.length)) {
1656
2230
  // Past the input: `pgAsyncAnswer` reads the rest of it alone.
1657
- pool.inAnswer[s] = -1
2231
+ if (s < toI32(pool.inAnswer.length)) {
2232
+ pool.inAnswer[s] = -1
2233
+ }
1658
2234
  return 0
1659
2235
  }
1660
- const got: i32 = netRead(fd, input, pool.inEnd[s], toI32(input.length) - pool.inEnd[s])
2236
+ const got: i32 = netRead(fd, input, end, toI32(input.length) - end)
1661
2237
  if (got === PG_ASYNC_AGAIN) {
1662
2238
  const waited: boolean = await readable(fd)
1663
2239
  const failed: i32 = pgAsyncWaitFailure(waited)
1664
2240
  if (failed === PG_ASYNC_CANCELLED) {
1665
2241
  // The bytes read stay in the input for the task that reads past the rest.
1666
2242
  pgAsyncAbandon(pool, seat)
1667
- return PG_ASYNC_BROKEN + failed
2243
+ return pgAsyncBroken(failed)
1668
2244
  }
1669
2245
  if (failed !== 0) {
1670
2246
  pgAsyncDoom(pool, s, seq)
1671
- return PG_ASYNC_BROKEN + failed
2247
+ return pgAsyncBroken(failed)
1672
2248
  }
1673
2249
  } else if (got <= 0) {
1674
2250
  pgAsyncDoom(pool, s, seq)
1675
- return PG_ASYNC_BROKEN + (got < 0 ? got : 0)
2251
+ return pgAsyncBroken(got)
1676
2252
  } else {
1677
- pool.inEnd[s] += got
2253
+ pgAsyncTook(pool, s, end, got, toI32(input.length))
1678
2254
  }
1679
2255
  }
1680
2256
  return 0
@@ -1690,8 +2266,9 @@ export const pgAsyncTurn = async (pool: PgAsyncPool, ticket: i32, sent: i32): Pr
1690
2266
  * with `reusable` false. It only reads the pool, so a spawned task may call
1691
2267
  * it.
1692
2268
  * @param pool The pool the ticket came from; a cap out of its range panics.
1693
- * @param ticket The ticket `pgAsyncTurn` used; any other panics, as does a
1694
- * ticket whose turn has not come.
2269
+ * @param ticket The ticket `pgAsyncTurn` used; any other panics. One whose
2270
+ * turn has not come, or whose connection failed at or before it, fails the
2271
+ * answer without reading, with `PG_ERR_CLOSED` and `reusable` false.
1695
2272
  * @param turn What `pgAsyncTurn` answered; one below 0 fails the answer
1696
2273
  * without reading, with `PG_ERR_ENCODING` for a parameter that could not be
1697
2274
  * sent and `PG_ERR_CLOSED` otherwise.
@@ -1712,20 +2289,39 @@ export const pgAsyncAnswer = async (pool: PgAsyncPool, ticket: i32, turn: i32):
1712
2289
  }
1713
2290
  return pgAsyncLost(result, PG_ERR_CLOSED, turn <= PG_ASYNC_BROKEN ? turn - PG_ASYNC_BROKEN : 0)
1714
2291
  }
1715
- if (pool.served[s] !== pool.seatSeq[seat] || pgAsyncLostSeat(pool, seat)) {
1716
- panic("nish/net/postgres-async: an answer read before its turn")
2292
+ if (
2293
+ !pgAsyncInTurn(pool, seat) ||
2294
+ s < 0 ||
2295
+ s >= toI32(pool.inputs.length) ||
2296
+ s >= toI32(pool.inStart.length) ||
2297
+ s >= toI32(pool.inEnd.length) ||
2298
+ s >= toI32(pool.inAnswer.length) ||
2299
+ s >= toI32(pool.fds.length)
2300
+ ) {
2301
+ // Read before its turn, or after its connection failed: there is no
2302
+ // answer of its own to read.
2303
+ return pgAsyncLost(new PgAsyncResult(), PG_ERR_CLOSED, 0)
1717
2304
  }
1718
2305
  // Copied into the task's memory: the spawn rules read an array of the pool
1719
2306
  // handed across an `await` as one the callee may grow.
1720
2307
  const input: u8[] = pool.inputs[s]
2308
+ const fd: i32 = pool.fds[s]
1721
2309
  const from: i32 = pool.inStart[s]
1722
2310
  const to: i32 = pool.inAnswer[s] >= 0 ? pool.inAnswer[s] : pool.inEnd[s]
1723
- const carried: u8[] = new Array<u8>(
1724
- from >= 0 && from <= to && to <= toI32(input.length) ? to - from : toI32(0)
1725
- )
1726
- copyBytes(carried, 0, input, from, toI32(carried.length))
2311
+ // In `u32`: `to` is at or past `from` here, so the difference is the bytes.
2312
+ const count: i32 = from >= 0 && from <= to && to <= toI32(input.length) ? toI32(toU32(to) - toU32(from)) : 0
2313
+ if (count < 0 || count > 65535) {
2314
+ // Not reached: an input is `PG_ASYNC_INPUT_SIZE` bytes. `pgAsyncZeroed`
2315
+ // would build a longer one by `push`, which the spawn rules read as
2316
+ // growing the pool, so this answer is failed as one too big to carry.
2317
+ return pgAsyncLost(new PgAsyncResult(), PG_ERR_TOO_BIG, 0)
2318
+ }
2319
+ const carried: u8[] = new Array<u8>(toU16(count))
2320
+ if (!tryCopyBytes(carried, 0, input, from, toI32(carried.length))) {
2321
+ return pgAsyncLost(new PgAsyncResult(), PG_ERR_CLOSED, 0)
2322
+ }
1727
2323
  return await pgAsyncRead(
1728
- pool.fds[s],
2324
+ fd,
1729
2325
  carried,
1730
2326
  true,
1731
2327
  pool.maxMessage,
@@ -1752,13 +2348,27 @@ export const pgAsyncAnswer = async (pool: PgAsyncPool, ticket: i32, turn: i32):
1752
2348
  export const pgAsyncDone = (pool: PgAsyncPool, ticket: i32, turn: i32, reusable: boolean): void => {
1753
2349
  const seat: i32 = pgAsyncSeatOf(pool, ticket)
1754
2350
  const s: i32 = toI32(seat / PG_ASYNC_MAX_DEPTH)
2351
+ if (
2352
+ seat < 0 ||
2353
+ s < 0 ||
2354
+ seat >= toI32(pool.seatSeq.length) ||
2355
+ seat >= toI32(pool.seatAbandoned.length) ||
2356
+ seat >= toI32(pool.seatClaims.length) ||
2357
+ seat >= toI32(pool.seatParse.length) ||
2358
+ s >= toI32(pool.nextSeq.length) ||
2359
+ s >= toI32(pool.writing.length) ||
2360
+ s >= toI32(pool.served.length)
2361
+ ) {
2362
+ // Not reached: `pgAsyncSeatOf` panicked on a ticket of no seat. A seat
2363
+ // out of the pool's arrays holds nothing to spend.
2364
+ return
2365
+ }
1755
2366
  const seq: i32 = pool.seatSeq[seat]
1756
- const statement: i32 = s * PG_ASYNC_MAX_STATEMENTS + pool.seatStatement[seat]
1757
2367
  const abandoned: i32 = toI32(pool.seatAbandoned[seat])
1758
2368
  if (abandoned === 1) {
1759
2369
  // Its answer is not read past yet: the ticket is spent, the seat stays until it is.
1760
2370
  pool.seatAbandoned[seat] = 2
1761
- pool.seatClaims[seat] = (pool.seatClaims[seat] + 1) % PG_ASYNC_SEAT_WRAP
2371
+ pool.seatClaims[seat] = pgAsyncStep(pool.seatClaims[seat], PG_ASYNC_SEAT_MASK)
1762
2372
  return
1763
2373
  }
1764
2374
  if (abandoned === 3) {
@@ -1769,30 +2379,27 @@ export const pgAsyncDone = (pool: PgAsyncPool, ticket: i32, turn: i32, reusable:
1769
2379
  // No other seat was taken here while it was being written, so its place
1770
2380
  // in the order is handed back.
1771
2381
  pool.nextSeq[s] = seq
2382
+ pool.writing[s] = 0
1772
2383
  if (toI32(pool.seatParse[seat]) === 1) {
1773
- pool.prepared[statement] = 0
2384
+ pgAsyncUnprepare(pool, s, seat)
1774
2385
  }
1775
- pool.writing[s] = 0
1776
2386
  pgAsyncFree(pool, seat)
1777
2387
  return
1778
2388
  }
1779
2389
  if (turn >= 0 && pool.served[s] === seq) {
1780
- pool.inStart[s] = pool.inAnswer[s] >= 0 ? pool.inAnswer[s] : pool.inEnd[s]
1781
- if (pool.inStart[s] === pool.inEnd[s]) {
1782
- pool.inStart[s] = 0
1783
- pool.inEnd[s] = 0
1784
- }
1785
- pool.served[s] = (seq + 1) % PG_ASYNC_SEQ_WRAP
1786
- if (toI32(pool.seatParse[seat]) === 1 && toI32(pool.inParsed[s]) === 0) {
1787
- pool.prepared[statement] = 0
1788
- }
2390
+ pgAsyncPast(pool, s, seat, seq)
1789
2391
  if (!reusable) {
1790
2392
  // A lost frame, a transaction left open or a setting changed: the
1791
2393
  // statements behind this one would be read out of step, or run in a
1792
2394
  // session they did not ask for.
1793
- pgAsyncDoom(pool, s, pool.served[s])
2395
+ pgAsyncDoom(pool, s, pgAsyncStep(seq, PG_ASYNC_SEQ_MASK))
1794
2396
  }
1795
2397
  pgAsyncWakeTurns(pool, s, seat)
2398
+ } else if (turn >= 0) {
2399
+ // Its answer was asked for before its turn and never read: nothing reads
2400
+ // past it, so the seats behind it would wait for good. The connection is
2401
+ // lost from here, as for an answer read out of step.
2402
+ pgAsyncDoom(pool, s, seq)
1796
2403
  }
1797
2404
  pgAsyncFree(pool, seat)
1798
2405
  }
@@ -1808,7 +2415,7 @@ export const pgAsyncDone = (pool: PgAsyncPool, ticket: i32, turn: i32, reusable:
1808
2415
  * @param sql One statement, `$1`, `$2`, ... naming the parameters; a NUL in
1809
2416
  * it fails the query with `PG_ERR_ENCODING` without sending anything.
1810
2417
  * @param params The parameters, as many as the statement names; a NUL in
1811
- * a text one fails the query the same way.
2418
+ * a text one, a Bind past 2^30 bytes, or unequal `values` and `nulls` fails it the same way.
1812
2419
  * @returns The answer; its `reusable` goes to `pgAsyncRelease`.
1813
2420
  */
1814
2421
  export const pgAsyncQuery = async (
@@ -1818,8 +2425,14 @@ export const pgAsyncQuery = async (
1818
2425
  params: PgAsyncParams
1819
2426
  ): Promise<PgAsyncResult> => {
1820
2427
  pgAsyncCheckCaps(pool)
1821
- const fd: i32 = pool.fds[pgAsyncSlot(pool, ticket)]
2428
+ const slot: i32 = pgAsyncSlot(pool, ticket)
1822
2429
  const result = new PgAsyncResult()
2430
+ if (slot < 0 || slot >= toI32(pool.fds.length)) {
2431
+ // Not reached: `pgAsyncSlot` panicked on a ticket of no slot. A slot out
2432
+ // of the pool's arrays has no connection to send on.
2433
+ return pgAsyncLost(result, PG_ERR_CLOSED, 0)
2434
+ }
2435
+ const fd: i32 = pool.fds[slot]
1823
2436
  if (cancelled()) {
1824
2437
  // Nothing is sent, so the connection is still in step and is given back.
1825
2438
  result.code = PG_CARRIER_FAILED
@@ -1837,8 +2450,9 @@ export const pgAsyncQuery = async (
1837
2450
  return result
1838
2451
  }
1839
2452
  let sent: i32 = 0
1840
- while (sent < toI32(out.length)) {
1841
- const n: i32 = netWrite(fd, out, sent, toI32(out.length) - sent)
2453
+ while (sent >= 0 && sent < toI32(out.length)) {
2454
+ // In `u32`: `sent` is below the `length` here, so the difference is the rest.
2455
+ const n: i32 = netWrite(fd, out, sent, toI32(toU32(out.length) - toU32(sent)))
1842
2456
  if (n === PG_ASYNC_AGAIN) {
1843
2457
  const waited: boolean = await writable(fd)
1844
2458
  const failed: i32 = pgAsyncWaitFailure(waited)
@@ -1848,7 +2462,9 @@ export const pgAsyncQuery = async (
1848
2462
  } else if (n <= 0) {
1849
2463
  return pgAsyncLost(result, PG_ERR_CLOSED, n)
1850
2464
  } else {
1851
- sent += n
2465
+ // A write takes no more than it was given, so `sent` stays within `out`.
2466
+ const next: i64 = toI64(sent) + toI64(n)
2467
+ sent = next > toI64(out.length) ? toI32(out.length) : toI32(next)
1852
2468
  }
1853
2469
  }
1854
2470
  const none: u8[] = []
@@ -1894,119 +2510,142 @@ const pgAsyncLost = (result: PgAsyncResult, failure: i32, socketError: i32): PgA
1894
2510
 
1895
2511
  /**
1896
2512
  * Parse (when `parse`), Bind, Execute and Sync for the statement `sql` and
1897
- * `params`, or null for a NUL in a parameter. `name` -1 is the unnamed
2513
+ * `params`, or null for a NUL in a parameter, more than 65535 of them, a
2514
+ * value without its null mark or one past them, or SQL or a Bind past 2^30
2515
+ * bytes, more than one message holds. `name` -1 is the unnamed
1898
2516
  * statement; 0 or more names it `n<name>`, which the connection keeps.
1899
2517
  */
1900
2518
  const pgAsyncEncode = (sql: u8[], name: i32, parse: boolean, params: PgAsyncParams): u8[] | null => {
1901
- const count: i32 = toI32(params.values.length)
1902
- if (count > 65535) {
2519
+ const values: string[] = params.values
2520
+ const nulls: boolean[] = params.nulls
2521
+ const count: i32 = toI32(values.length)
2522
+ // A parameter without its null mark (an array pushed to directly, past the
2523
+ // methods) would send a Bind whose count is not what follows it.
2524
+ if (count > 65535 || count !== toI32(nulls.length)) {
2525
+ return null
2526
+ }
2527
+ // A message's length is an i32 on the wire; each kept under 2^30 leaves the sums below room.
2528
+ const cap: i32 = 1073741823
2529
+ const sqlLength: i32 = toI32(sql.length)
2530
+ if (sqlLength > cap) {
1903
2531
  return null
1904
2532
  }
1905
- // The statement's name: none, or `n` and its decimal digits (at most 2).
1906
- const label: u8[] = pgAsyncLabel(name)
1907
- const named: i32 = toI32(label.length)
1908
- const values: u8[][] = []
2533
+ // The statement's name: none, or `n` and its decimal digits (at most 2), as `pgAsyncLabel` writes it.
2534
+ let named: i32 = 0
2535
+ if (name >= 10) {
2536
+ named = 3
2537
+ } else if (name >= 0) {
2538
+ named = 2
2539
+ }
1909
2540
  // The length, "" portal, the statement's name and NUL, no parameter formats,
1910
- // the count, no result formats: 4 + 1 + named + 1 + 2 + 2 + 2, held as an
1911
- // i32 in either number mode.
2541
+ // the count, no result formats: 4 + 1 + named + 1 + 2 + 2 + 2. Each sum is
2542
+ // counted in i64, where no two i32s can wrap it, before it is kept.
1912
2543
  let bind: i32 = toI32(12) + named
1913
- for (let i: i32 = 0; i < count; i++) {
1914
- const v = pgAsyncBytes(params.values[i])
1915
- if (v === null) {
2544
+ for (let i: i32 = 0; i < toI32(values.length) && i < toI32(nulls.length); i++) {
2545
+ const size: i32 = nulls[i] ? toI32(0) : toI32(values[i].length)
2546
+ const next: i64 = toI64(bind) + toI64(4) + toI64(size)
2547
+ if (next > toI64(cap)) {
1916
2548
  return null
1917
2549
  }
1918
- values.push(v)
1919
- bind += toI32(4)
1920
- if (!params.nulls[i]) {
1921
- bind += toI32(v.length)
1922
- }
2550
+ bind = toI32(next)
1923
2551
  }
1924
- const sqlLength: i32 = toI32(sql.length)
1925
- // The length, the statement's name and NUL, the SQL and its NUL, no parameter types.
1926
- const parseLength: i32 = parse ? sqlLength + named + toI32(8) : 0
1927
- // Parse, Bind, Execute ("" portal, no row limit: 4 + 1 + 4), Sync (4).
1928
- const total: i32 = (parse ? toI32(1) + parseLength : toI32(0)) + toI32(16) + bind
1929
- const out: u8[] = new Array<u8>(total)
1930
- let at: i32 = 0
2552
+ // Each part is pushed in order, so no write needs a position the prover must follow.
2553
+ const out: u8[] = []
1931
2554
  if (parse) {
1932
- out[at] = 80
1933
- setI32BE(out, at + 1, parseLength)
1934
- at += 5
1935
- for (let i: i32 = 0; i < toI32(label.length); i++) {
1936
- out[at + i] = label[i]
1937
- }
1938
- at += named
1939
- out[at] = 0
1940
- at += 1
1941
- for (let i: i32 = 0; i < sqlLength && at + i < total; i++) {
1942
- out[at + i] = sql[i]
1943
- }
1944
- at += sqlLength
1945
- out[at] = 0
1946
- out[at + 1] = 0
1947
- out[at + 2] = 0
1948
- at += 3
1949
- }
1950
- out[at] = 66
1951
- setI32BE(out, at + 1, bind)
1952
- at += 5
1953
- // The unnamed portal, the statement's name, no parameter format codes (all text).
1954
- out[at] = 0
1955
- at += 1
1956
- for (let i: i32 = 0; i < toI32(label.length); i++) {
1957
- out[at + i] = label[i]
1958
- }
1959
- at += named
1960
- out[at] = 0
1961
- out[at + 1] = 0
1962
- out[at + 2] = 0
1963
- setU16BE(out, at + 3, toU16(count))
1964
- at += 5
1965
- // Bounded by `values` rather than `count`, which it equals, so the prover reads the index.
1966
- const encoded: i32 = toI32(values.length)
1967
- for (let i: i32 = 0; i < encoded; i++) {
1968
- if (params.nulls[i]) {
1969
- setI32BE(out, at, -1)
1970
- at += 4
2555
+ // The length, the statement's name and NUL, the SQL and its NUL, no parameter types.
2556
+ out.push(80)
2557
+ pgAsyncPushI32(out, sqlLength + named + toI32(8))
2558
+ pgAsyncLabel(out, name)
2559
+ out.push(0)
2560
+ for (let i: i32 = 0; i < toI32(sql.length); i++) {
2561
+ out.push(sql[i])
2562
+ }
2563
+ out.push(0)
2564
+ out.push(0)
2565
+ out.push(0)
2566
+ }
2567
+ // The unnamed portal, the statement's name, no parameter format codes (all text), the count.
2568
+ out.push(66)
2569
+ pgAsyncPushI32(out, bind)
2570
+ out.push(0)
2571
+ pgAsyncLabel(out, name)
2572
+ out.push(0)
2573
+ out.push(0)
2574
+ out.push(0)
2575
+ out.push(toU8(count >> 8))
2576
+ out.push(toU8(count & 255))
2577
+ for (let i: i32 = 0; i < toI32(values.length) && i < toI32(nulls.length); i++) {
2578
+ if (nulls[i]) {
2579
+ pgAsyncPushI32(out, -1)
1971
2580
  continue
1972
2581
  }
1973
- const v: u8[] = values[i]
1974
- setI32BE(out, at, toI32(v.length))
1975
- copyBytes(out, at + 4, v, 0, toI32(v.length))
1976
- at += 4 + toI32(v.length)
2582
+ const v: string = values[i]
2583
+ pgAsyncPushI32(out, toI32(v.length))
2584
+ for (let j: i32 = 0; j < toI32(v.length); j++) {
2585
+ const c: i32 = toI32(v.charCodeAt(j))
2586
+ if (c === 0) {
2587
+ return null
2588
+ }
2589
+ out.push(toU8(c))
2590
+ }
1977
2591
  }
1978
2592
  // No result format codes: every column in text.
1979
- out[at] = 0
1980
- out[at + 1] = 0
1981
- at += 2
1982
- out[at] = 69
1983
- setI32BE(out, at + 1, 9)
1984
- out[at + 5] = 0
1985
- setI32BE(out, at + 6, 0)
1986
- at += 10
1987
- out[at] = 83
1988
- setI32BE(out, at + 1, 4)
2593
+ out.push(0)
2594
+ out.push(0)
2595
+ // Execute ("" portal, no row limit) and Sync.
2596
+ out.push(69)
2597
+ pgAsyncPushI32(out, 9)
2598
+ out.push(0)
2599
+ pgAsyncPushI32(out, 0)
2600
+ out.push(83)
2601
+ pgAsyncPushI32(out, 4)
1989
2602
  return out
1990
2603
  }
1991
2604
 
2605
+ /** Appends `v`'s four bytes to `out`, most significant first, as the protocol sends an Int32. */
2606
+ const pgAsyncPushI32 = (out: u8[], v: i32): void => {
2607
+ const u: u32 = toU32(v)
2608
+ out.push(toU8(u >> 24))
2609
+ out.push(toU8((u >> 16) & 255))
2610
+ out.push(toU8((u >> 8) & 255))
2611
+ out.push(toU8(u & 255))
2612
+ }
2613
+
1992
2614
  /**
1993
- * A prepared statement's name, `n` and the decimal digits of `name` (at most
1994
- * 2), or none for a negative `name`.
2615
+ * Appends a prepared statement's name to `out`: `n` and the decimal digits
2616
+ * of `name` (at most 2), or nothing for a negative `name`.
1995
2617
  */
1996
- const pgAsyncLabel = (name: i32): u8[] => {
2618
+ const pgAsyncLabel = (out: u8[], name: i32): void => {
1997
2619
  if (name >= 10) {
1998
- return [110, toU8(toI32(48) + toI32(name / 10)), toU8(toI32(48) + (name % 10))]
2620
+ out.push(110)
2621
+ out.push(toU8(toI32(48) + toI32(name / 10)))
2622
+ out.push(toU8(toI32(48) + (name % 10)))
2623
+ } else if (name >= 0) {
2624
+ out.push(110)
2625
+ out.push(toU8(toI32(48) + name))
2626
+ }
2627
+ }
2628
+
2629
+ /**
2630
+ * A zeroed byte array of `n` bytes, or an empty one for a negative `n`. Up to
2631
+ * 64 KiB it is one `new Array` of a `u16` length, which needs no check; a
2632
+ * longer one, the rare buffer for a message past that, is built by `push`.
2633
+ */
2634
+ const pgAsyncZeroed = (n: i32): u8[] => {
2635
+ if (n >= 0 && n <= 65535) {
2636
+ return new Array<u8>(toU16(n))
1999
2637
  }
2000
- if (name >= 0) {
2001
- return [110, toU8(toI32(48) + name)]
2638
+ const out: u8[] = []
2639
+ while (toI32(out.length) < n) {
2640
+ out.push(0)
2002
2641
  }
2003
- return []
2642
+ return out
2004
2643
  }
2005
2644
 
2006
2645
  /** `s`'s UTF-8 bytes, or null when one is zero, which a C string in the protocol cannot hold. */
2007
2646
  const pgAsyncBytes = (s: string): u8[] | null => {
2008
2647
  const n: i32 = toI32(s.length)
2009
- const b: u8[] = new Array<u8>(n)
2648
+ const b: u8[] = pgAsyncZeroed(n)
2010
2649
  const room: i32 = toI32(b.length)
2011
2650
  // Bounded by each length it indexes, which are equal, so the prover reads both.
2012
2651
  for (let i: i32 = 0; i < n && i < room; i++) {
@@ -2039,24 +2678,65 @@ const pgAsyncRead = async (
2039
2678
  maxResultBytes: i32
2040
2679
  ): Promise<PgAsyncResult> => {
2041
2680
  const result = new PgAsyncResult()
2681
+ // `pgAsyncCheckCaps` has already held every cap inside its range, so this
2682
+ // never fails; it is what lets the prover bound the sums below by the caps.
2683
+ if (
2684
+ maxMessage < 4 ||
2685
+ maxMessage > PG_ASYNC_MAX_CAP ||
2686
+ maxRows > PG_ASYNC_MAX_ROWS ||
2687
+ maxResultBytes < 0 ||
2688
+ maxResultBytes > PG_ASYNC_MAX_CAP
2689
+ ) {
2690
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2691
+ }
2692
+ // The seed is part of the pool's input, far shorter than this.
2693
+ if (toI32(seed.length) > PG_ASYNC_MAX_CAP) {
2694
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2695
+ }
2696
+ // `PG_ASYNC_MAX_CAP`, one past it, and five short of one past it, as
2697
+ // literals: inside a loop the prover takes a bound from a literal or a local
2698
+ // constant, not from a module constant.
2699
+ const cap: i32 = 1073741823
2700
+ const capEnd: i32 = 1073741824
2701
+ const capHead: i32 = 1073741819
2042
2702
  // The buffer starts the size of the seed, not a zero-filled 8 KiB: an answer
2043
2703
  // already scanned whole is parsed without clearing memory it never reads, and
2044
2704
  // only a read past it grows the buffer.
2045
- let buf: u8[] = new Array<u8>(toI32(seed.length))
2046
- copyBytes(buf, 0, seed, 0, toI32(seed.length))
2705
+ let buf: u8[] = pgAsyncZeroed(toI32(seed.length))
2706
+ if (!tryCopyBytes(buf, 0, seed, 0, toI32(seed.length))) {
2707
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2708
+ }
2047
2709
  let start: i32 = 0
2048
2710
  let end: i32 = toI32(seed.length)
2049
2711
  let refused: boolean = false
2050
2712
  let tooBig: boolean = false
2051
2713
  let changed: boolean = false
2052
2714
  let shaped: boolean = false
2053
- // The bytes of rows, tags and error fields kept, under `maxResultBytes`.
2054
- let kept: i32 = 0
2715
+ // What is left of `maxResultBytes` for the rows, tags and error fields kept.
2716
+ let left: i32 = maxResultBytes
2055
2717
  while (true) {
2056
- // Every whole message in [start, end).
2057
- while (end - start >= 5) {
2058
- // Always true, since `end` never passes the buffer; it proves the reads below.
2059
- if (start < 0 || start + 5 > toI32(buf.length)) {
2718
+ // Always false: `start` never passes `end`, `end` never passes the
2719
+ // buffer, the buffer is never longer than the seed or `maxMessage + 1`, and
2720
+ // `left` only shrinks from `maxResultBytes`. Each bound is stated on its
2721
+ // own because the prover reads ranges, not the chain between them.
2722
+ if (
2723
+ start < 0 ||
2724
+ end < 0 ||
2725
+ start > end ||
2726
+ start > capEnd ||
2727
+ end > capEnd ||
2728
+ end > toI32(buf.length) ||
2729
+ left < 0 ||
2730
+ left > cap
2731
+ ) {
2732
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2733
+ }
2734
+ // A whole message at `start` is taken here; anything short of one reads more below.
2735
+ const have: i32 = end - start
2736
+ if (have >= 5) {
2737
+ // Always false, since five bytes lie between `start` and `end`; it
2738
+ // proves the header's reads and, with `length`, the frame's end.
2739
+ if (start > toI32(buf.length) - 5 || start > capHead) {
2060
2740
  return pgAsyncLost(result, PG_ERR_FRAME, 0)
2061
2741
  }
2062
2742
  const type: i32 = toI32(buf[start])
@@ -2064,119 +2744,142 @@ const pgAsyncRead = async (
2064
2744
  if (length < 4) {
2065
2745
  return pgAsyncLost(result, PG_ERR_FRAME, 0)
2066
2746
  }
2067
- if (length > maxMessage) {
2747
+ // `maxMessage` is never past `PG_ASYNC_MAX_CAP`; the second test bounds the sums below.
2748
+ if (length > maxMessage || length > cap) {
2068
2749
  return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2069
2750
  }
2070
- if (end - start - 1 < length) {
2071
- break
2072
- }
2073
- const body: i32 = start + 5
2074
- const stop: i32 = start + 1 + length
2075
- start = stop
2076
- if (type === 90) {
2077
- // 'Z': ReadyForQuery, the end of the answer.
2078
- if (stop - body !== 1 || body < 0 || body >= toI32(buf.length)) {
2079
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2080
- }
2081
- // Bytes after the ReadyForQuery answer no statement this one sent,
2082
- // so the connection is out of step and closed rather than given
2083
- // back. A pipelined read stops at the ReadyForQuery, so none are
2084
- // read here unless the server sent them inside this answer.
2085
- result.reusable = toI32(buf[body]) === PG_ASYNC_IDLE && !changed && start === end
2086
- if (refused || tooBig) {
2087
- result.code = PG_CARRIER_FAILED
2088
- result.failure = tooBig ? PG_ERR_TOO_BIG : PG_ERR_NONE
2751
+ if (have - 1 >= length) {
2752
+ const body: i32 = start + 5
2753
+ const stop: i32 = start + 1 + length
2754
+ // The body's length, `stop - body`, which the prover bounds by `maxMessage`.
2755
+ const size: i32 = length - 4
2756
+ start = stop
2757
+ if (type === 90) {
2758
+ // 'Z': ReadyForQuery, the end of the answer.
2759
+ if (size !== 1 || body < 0 || body >= toI32(buf.length)) {
2760
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2761
+ }
2762
+ // Bytes after the ReadyForQuery answer no statement this one sent,
2763
+ // so the connection is out of step and closed rather than given
2764
+ // back. A pipelined read stops at the ReadyForQuery, so none are
2765
+ // read here unless the server sent them inside this answer.
2766
+ result.reusable = toI32(buf[body]) === PG_ASYNC_IDLE && !changed && start === end
2767
+ if (refused || tooBig) {
2768
+ result.code = PG_CARRIER_FAILED
2769
+ result.failure = tooBig ? PG_ERR_TOO_BIG : PG_ERR_NONE
2770
+ }
2771
+ return result
2089
2772
  }
2090
- return result
2091
- }
2092
- if (type === 68) {
2093
- // 'D': DataRow, a count then each column's length (-1 for NULL) and bytes.
2094
- if (stop - body < 2) {
2095
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2096
- }
2097
- const columns: i32 = toI32(getU16BE(buf, body))
2098
- if (columns > maxColumns) {
2099
- return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2100
- }
2101
- if (shaped && columns !== result.columns) {
2102
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2103
- }
2104
- // The frame's length bounds its cells' bytes; each cell costs its string besides.
2105
- const cost: i32 = stop - body + columns * PG_ASYNC_CELL_COST
2106
- if (tooBig || result.rows >= maxRows || cost > maxResultBytes - kept) {
2107
- tooBig = true
2773
+ if (type === 68) {
2774
+ // 'D': DataRow, a count then each column's length (-1 for NULL) and bytes.
2775
+ if (size < 2) {
2776
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2777
+ }
2778
+ const columns: i32 = toI32(getU16BE(buf, body))
2779
+ if (columns > maxColumns) {
2780
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2781
+ }
2782
+ if (shaped && columns !== result.columns) {
2783
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2784
+ }
2785
+ // The frame's length bounds its cells' bytes; each cell costs its string besides.
2786
+ const cost: i32 = size + columns * PG_ASYNC_CELL_COST
2787
+ const rows: i32 = result.rows
2788
+ if (tooBig || rows < 0 || rows >= maxRows || cost < 0 || cost > left) {
2789
+ tooBig = true
2790
+ continue
2791
+ }
2792
+ left -= cost
2793
+ if (!pgAsyncRow(buf, body + 2, stop, columns, result)) {
2794
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2795
+ }
2796
+ result.columns = columns
2797
+ shaped = true
2798
+ result.rows = rows + 1
2108
2799
  continue
2109
2800
  }
2110
- kept += cost
2111
- if (!pgAsyncRow(buf, body + 2, stop, columns, result)) {
2112
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2113
- }
2114
- result.columns = columns
2115
- shaped = true
2116
- result.rows += 1
2117
- continue
2118
- }
2119
- if (type === 67) {
2120
- // 'C': CommandComplete, a NUL-ended tag.
2121
- if (stop - body < 1 || toI32(buf[stop - 1]) !== 0) {
2122
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2801
+ if (type === 67) {
2802
+ // 'C': CommandComplete, a NUL-ended tag.
2803
+ if (size < 1 || stop > toI32(buf.length) || toI32(buf[stop - 1]) !== 0) {
2804
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2805
+ }
2806
+ // A tag is kept, so it costs the budget too; past it, the answer fails.
2807
+ if (size > left) {
2808
+ tooBig = true
2809
+ continue
2810
+ }
2811
+ left -= size
2812
+ result.tag = String.fromBytes(buf, body, stop - 1)
2813
+ continue
2123
2814
  }
2124
- // A tag is kept, so it costs the budget too; past it, the answer fails.
2125
- if (stop - body > maxResultBytes - kept) {
2126
- tooBig = true
2815
+ if (type === 69) {
2816
+ // 'E': ErrorResponse, fields of a code byte and a NUL-ended value.
2817
+ // Its kept fields cost the budget, bounded by the frame; past it, none is kept.
2818
+ refused = true
2819
+ if (size > left) {
2820
+ tooBig = true
2821
+ continue
2822
+ }
2823
+ left -= size
2824
+ if (!pgAsyncError(buf, body, stop, result)) {
2825
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2826
+ }
2127
2827
  continue
2128
2828
  }
2129
- kept += stop - body
2130
- result.tag = String.fromBytes(buf, body, stop - 1)
2131
- continue
2132
- }
2133
- if (type === 69) {
2134
- // 'E': ErrorResponse, fields of a code byte and a NUL-ended value.
2135
- // Its kept fields cost the budget, bounded by the frame; past it, none is kept.
2136
- refused = true
2137
- if (stop - body > maxResultBytes - kept) {
2138
- tooBig = true
2829
+ if (type === 83) {
2830
+ // 'S': a ParameterStatus after startup is a session setting a statement changed.
2831
+ changed = true
2139
2832
  continue
2140
2833
  }
2141
- kept += stop - body
2142
- if (!pgAsyncError(buf, body, stop, result)) {
2143
- return pgAsyncLost(result, PG_ERR_FRAME, 0)
2834
+ if (type === 49 || type === 50 || type === 73 || type === 78 || type === 65) {
2835
+ // ParseComplete, BindComplete, EmptyQueryResponse, a notice, a notification.
2836
+ continue
2144
2837
  }
2145
- continue
2146
- }
2147
- if (type === 83) {
2148
- // 'S': a ParameterStatus after startup is a session setting a statement changed.
2149
- changed = true
2150
- continue
2151
- }
2152
- if (type === 49 || type === 50 || type === 73 || type === 78 || type === 65) {
2153
- // ParseComplete, BindComplete, EmptyQueryResponse, a notice, a notification.
2154
- continue
2838
+ return pgAsyncLost(result, PG_ERR_UNEXPECTED, 0)
2155
2839
  }
2156
- return pgAsyncLost(result, PG_ERR_UNEXPECTED, 0)
2157
2840
  }
2158
2841
  // Room for the rest of the message at `start`, then more input.
2159
2842
  if (start > 0) {
2160
- copyBytes(buf, 0, buf, start, end - start)
2843
+ if (!tryCopyBytes(buf, 0, buf, start, end - start)) {
2844
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2845
+ }
2161
2846
  end -= start
2162
2847
  start = 0
2163
2848
  }
2164
2849
  if (end === toI32(buf.length)) {
2165
- const twice: i32 = toI32(buf.length) < PG_ASYNC_INPUT_SIZE ? PG_ASYNC_INPUT_SIZE : toI32(buf.length) * 2
2166
- const grown: u8[] = new Array<u8>(
2167
- twice > maxMessage + 1 && end < maxMessage + 1 ? maxMessage + 1 : twice
2168
- )
2169
- copyBytes(grown, 0, buf, 0, end)
2850
+ // A full buffer holds less than one whole message, so it is shorter
2851
+ // than `maxMessage + 1`; the test lets the prover read that.
2852
+ if (end < 0 || end > maxMessage || end > cap || maxMessage > cap) {
2853
+ return pgAsyncLost(result, PG_ERR_TOO_BIG, 0)
2854
+ }
2855
+ const twice: i32 = end < PG_ASYNC_INPUT_SIZE ? PG_ASYNC_INPUT_SIZE : end * 2
2856
+ const grown: u8[] = pgAsyncZeroed(twice > maxMessage + 1 ? maxMessage + 1 : twice)
2857
+ if (!tryCopyBytes(grown, 0, buf, 0, end)) {
2858
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2859
+ }
2170
2860
  buf = grown
2171
2861
  }
2862
+ // Always false, as above; it proves the read's range below.
2863
+ if (start < 0 || end < 0 || start > end || start > capEnd || end > capEnd || end > toI32(buf.length)) {
2864
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2865
+ }
2172
2866
  const room: i32 = toI32(buf.length) - end
2173
2867
  let want: i32 = room
2174
2868
  if (bounded) {
2175
2869
  // The rest of the frame at `start`, and the next header unless it is the ReadyForQuery.
2176
- want = toI32(5) - (end - start)
2177
- if (end - start >= 5 && start >= 0 && start < toI32(buf.length)) {
2870
+ const held: i32 = end - start
2871
+ want = toI32(5) - held
2872
+ if (held >= 5 && start < toI32(buf.length) - 5) {
2178
2873
  const length: i32 = getI32BE(buf, start + 1)
2179
- want = toI32(1) + length - (end - start) + (toI32(buf[start]) === 90 ? toI32(0) : toI32(5))
2874
+ // A length past `maxMessage` was failed before this read.
2875
+ if (length < 4) {
2876
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2877
+ }
2878
+ if (length > maxMessage || length > cap) {
2879
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2880
+ }
2881
+ const rest: i32 = toI32(1) + length - held
2882
+ want = toI32(buf[start]) === 90 ? rest : rest + 5
2180
2883
  }
2181
2884
  if (want > room) {
2182
2885
  want = room
@@ -2194,32 +2897,51 @@ const pgAsyncRead = async (
2194
2897
  } else if (got <= 0) {
2195
2898
  return pgAsyncLost(result, PG_ERR_CLOSED, got)
2196
2899
  } else {
2197
- end += got
2900
+ // A read never passes the room it was given, so this never fails; the
2901
+ // sum is taken in `i64` because the prover cannot chain `got <= want <= room`.
2902
+ const next: i64 = toI64(end) + toI64(got)
2903
+ if (next > toI64(buf.length)) {
2904
+ return pgAsyncLost(result, PG_ERR_FRAME, 0)
2905
+ }
2906
+ end = toI32(next)
2198
2907
  }
2199
2908
  }
2200
2909
  }
2201
2910
 
2202
2911
  /** One DataRow's `columns` cells in `[at, stop)` into `result`; false for a frame that does not add up. */
2203
2912
  const pgAsyncRow = (buf: u8[], at: i32, stop: i32, columns: i32, result: PgAsyncResult): boolean => {
2913
+ // `stop` never passes the buffer; the test lets the prover read each cell's range.
2914
+ if (at < 0 || at > stop || stop > toI32(buf.length)) {
2915
+ return false
2916
+ }
2917
+ // `PG_ASYNC_MAX_CAP`, and the last place a cell's length can start in a
2918
+ // frame that ends by one past it, as literals, which the prover reads inside
2919
+ // a loop where it does not read a module constant.
2920
+ const cap: i32 = 1073741823
2921
+ const lastCell: i32 = 1073741820
2204
2922
  let p: i32 = at
2205
2923
  for (let c: i32 = 0; c < columns; c++) {
2206
- if (stop - p < 4 || p < 0 || p + 3 >= toI32(buf.length)) {
2924
+ if (p < 0 || p > stop - 4 || p > toI32(buf.length) - 4 || p > lastCell) {
2207
2925
  return false
2208
2926
  }
2209
2927
  const n: i32 =
2210
2928
  (toI32(buf[p]) << 24) | (toI32(buf[p + 1]) << 16) | (toI32(buf[p + 2]) << 8) | toI32(buf[p + 3])
2211
- p += 4
2929
+ const from: i32 = p + 4
2212
2930
  if (n === -1) {
2213
2931
  result.values.push("")
2214
2932
  result.nulls.push(true)
2933
+ p = from
2215
2934
  continue
2216
2935
  }
2217
- if (n < 0 || n > stop - p) {
2936
+ // A cell never passes the frame, which is never past `PG_ASYNC_MAX_CAP`;
2937
+ // the second test is what lets the prover bound the sum below.
2938
+ if (n < 0 || n > stop - from || n > cap) {
2218
2939
  return false
2219
2940
  }
2220
- result.values.push(String.fromBytes(buf, p, p + n))
2941
+ const cellEnd: i32 = from + n
2942
+ result.values.push(String.fromBytes(buf, from, cellEnd))
2221
2943
  result.nulls.push(false)
2222
- p += n
2944
+ p = cellEnd
2223
2945
  }
2224
2946
  return p === stop
2225
2947
  }