raz / commit 12154405

commit
12154405164df11c2260d76bbd3fa1e88bbe8b90
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
f5a4769e
MEM_PROPOSAL.md: four adversarial reviews, appendices 4 to 7

Soundness (holes in the guarantee), the claims about other languages
and hardware, the proposal's own numbers and samples, and real code
ported under the rules. The body is left as drafted; the status says
the appendices stand where they contradict it.

patch · log

1 file changed, +2254 -1

MEM_PROPOSAL.md modified +2254 -1

@@ -1,7 +1,13 @@
11 # MEM_PROPOSAL: a memory-safe raz
22
33 **Status.** A proposal, drafted 2026-10-17 for the owner's review.
4-Nothing in it is built. It assumes that anything may change: the
4+Nothing in it is built. Four adversarial reviews, made the same day,
5+are appendices 4 to 7. They find real holes in the guarantee
6+(appendix 4), wrong and imprecise claims about other languages and
7+hardware (5), wrong counts and unsupported benchmark conclusions (6),
8+and pain in real code that sections 14 and 15 understate (7). The body
9+below is as first drafted; where an appendix contradicts it, the
10+appendix stands until the body is revised. It assumes that anything may change: the
511 language, the library, the compiler, and the programs written for
612 them. It builds on two entries of `PROPOSALS.md`, "Less that is
713 undefined" and part 3 of "What a call does with its arguments" (`ret`
@@ -66,6 +72,10 @@
6672 - Appendix 1: the survey's numbers
6773 - Appendix 2: the benchmarks
6874 - Appendix 3: the five programs of section 1
75+- Appendix 4: adversarial review, soundness
76+- Appendix 5: adversarial review, claims about other languages and hardware
77+- Appendix 6: adversarial review, the proposal's numbers and samples
78+- Appendix 7: adversarial review, porting real code
6979
7080 ---
7181
@@ -1915,3 +1925,2246 @@
19151925 ```
19161926
19171927 Prints `name-..b`, a space and eight bytes of junk, status 0.
1928+
1929+---
1930+
1931+## Appendix 4: adversarial review, soundness
1932+
1933+This appendix tests section 3's promise against parts A to F, read as
1934+written. It finds 12 ways a program of safe modules and the library, as
1935+section 17 would change it, still breaks the guarantee; 7 ambiguities
1936+or contradictions; and 3 problems with checking or building the rules
1937+in one pass. Two of the breaks are in today's language too, and the
1938+proposal leaves them as they are: a variant changed while `match` names
1939+its fields, and an `ERROR` written through a view. Both were run with
1940+today's compiler. The rest follow from the text of the proposal.
1941+
1942+### Breaks the guarantee
1943+
1944+**1. A variant changed under its `match`.**
1945+
1946+```
1947+type V = variant ptr(p: ^INT); num(n: INT); end;
1948+var v: V; (* a module variable *)
1949+proc flip(a: INT); begin v := num(a); end;
1950+...
1951+v := ptr(q);
1952+match v of
1953+| ptr(p): flip(h.(INT) + 8); p^ := 1000000; (* p reads num's bytes as a pointer *)
1954+| num(_n):
1955+end;
1956+```
1957+
1958+Run today, this sets the length of a heap slice, `h^.s`, to 1,000,000.
1959+Every operation in it stays safe under 5.1: the view only reads a
1960+pointer's bytes as an integer (10.3), and that is allowed. 7.4 says the
1961+names stand for the fields of `s` itself, and nothing stops the arm, a
1962+call it makes, or an alias (`var` parameter, pointer) from giving `s`
1963+another case. 10.4 covers only lending. Fix: in a safe module, an arm's
1964+names are a copy of the fields whenever the arm could change the
1965+variable (any call, any store through a pointer or `var` parameter, or
1966+the variable named), or each use of a name checks the tag first. Cost:
1967+a compare per use, or a copy per `match`, and one line less of 7.4.
1968+
1969+**2. An `ERROR` written through a view.** `e.(INT) := h.(INT);
1970+Out.str(MSG(e))` printed 64 KB of memory today. `ERROR` is an address
1971+(5.8), but the list in 5.1 and 10.3 of what may not be written through
1972+a view (pointer, procedure, slice, variant, enumeration, `BOOL`) leaves
1973+it out. Fix: add `ERROR`, and better, state the rule the other way round:
1974+a view may write only a variable made wholly of the types 6.9 allows as
1975+a view's `T`. Cost: none.
1976+
1977+**3. A safe module makes its own allocator.** `Mem.Allocator`'s fields
1978+are exported. 5.2 lets a safe procedure stand where an `unsafe proc`
1979+type is wanted. So a safe module can build `{alloc: mine, free: none}`
1980+and pass it to `NEW`. Its `mine` can return the same lasting `^U8` for
1981+every call, or a 1-byte block for a large `T`. Then `NEW` zeroes and
1982+hands out memory that two pointers of different types share, or that
1983+runs past its block. The same goes for copying `Arena.allocator(ar)^`,
1984+or `ar.base`, into a heap record and passing that: Arena's `alloc`
1985+casts its argument to `^Arena`, and reads past the copy. The trust of
1986+5.3 is broken by code the trusted module calls back. Fix: a field of an
1987+`unsafe proc` type may be set only in an unsafe module, and
1988+`Mem.Allocator` becomes a type safe code can't build or copy (its
1989+fields unexported, copying refused as for an owner). Cost: a rule in
1990+5.2 and in 7.6.
1991+
1992+**4. Procedures that take an allocator report arena memory as lasting.**
1993+`Mem.alloc`, `Str.copy` and the result of `NEW` through such a call
1994+carry no `ret` on their allocator, so by 6.1 what they return is
1995+lasting. Given `Arena.allocator(ar)`, they return arena memory. After
1996+`Arena.reset`, that memory goes to the next `NEW` of another type. The
1997+same holds for `Buf.init`, `Vec.init`, `Map.init`, `List.init` and
1998+`Pool.init`, which keep the allocator in the owner without a `keep`
1999+mark, against obligation 3. Fix: `ret a` on every procedure whose
2000+result comes from `a`, and `keep a` on every `init`. Then an arena's
2001+allocator can't be kept by a container, and what `Str.copy` gives from
2002+it is lent by the arena. Cost: marks on about ten headings.
2003+
2004+**5. Storing a lent slice in an element of a slice.** 6.2 allows a
2005+lent value to be "held in a local variable, or in a field or element of
2006+one". An element of a local slice is someone else's memory:
2007+
2008+```
2009+proc stash(s: [][]U8); (* s: the caller's array, or a Vec's block *)
2010+var buf: [8]U8;
2011+begin s[0] := buf[0..8]; end; (* allowed by 6.2's words; dangles after return *)
2012+```
2013+
2014+PROPOSALS' "outliving the call" lists `p^.f` and `p^[i]` but not
2015+`s[i]`. Fix: what is reached through a slice is a place that outlives
2016+the call, as through a pointer, unless the slice is lent only by the
2017+frame. Cost: a few false alarms on local slices of local arrays.
2018+
2019+**6. Only a call's result is counted.** 7.3 counts "where a call
2020+returns a reference lent by an owner". `t := s`, `t := s[1..3]` and
2021+`u := t^[0..10]`, with `s` held, are not calls. Read as written, `t`
2022+gets no hold. Then `s := []` lets the count fall to zero while `t`
2023+still points into the block, and the next growth frees it. Fix: every
2024+assignment to a local of a value lent by an owner sets that local's
2025+holds, whatever the expression. Cost: none beyond what was meant.
2026+
2027+**7. One hold, two owners.** A value may be lent by two owners at once:
2028+`Buf.bytes(all[0])` with `all := Bufs.all(v)`; `NEW(t, al)` with `T` an
2029+owner, then `Buf.bytes(t^)`; `pick(Buf.bytes(a), Buf.bytes(b))` with
2030+two `ret` parameters. 7.3 gives a local one hidden word. Whichever owner
2031+it leaves uncounted can free or move the memory: the outer `Vec` frees
2032+the block that holds the inner `Buf`, and the hold then lowers a word of
2033+freed memory. Fix: a hold per owner a value can be lent by, which the
2034+compiler knows from the heading. Or forbid an owner reached through an
2035+owner-lent value. Cost: a word per extra owner. The second choice
2036+forbids `Vec(Buf.Buf)` and `Pool` of owners in practice.
2037+
2038+**8. Library containers copy owners.** 7.6 forbids copies only in safe
2039+modules. `Vec`, `Pool`, `Map` and `List` are unsafe and generic, so
2040+they can't know that `T` is an owner. `Pool.get` returns a copy of a
2041+slot. `Vec`'s growth copies every element into the new block, and, with
2042+a lend held, keeps the old copy alive too. `Vec.pop`, `List.pop` and
2043+`Map.get` copy out. Two `Buf`s then own one block: one grows and frees
2044+it, and the other reads it. 7.6's rule also misses the result of a call
2045+(`b := Pools.get(p, h)` isn't "assigned from another variable"). Fix: a
2046+generic module's type parameter may be an owner only if the module says
2047+it takes owners. Those modules move owners, never copy them, and
2048+`get` is refused for them. Cost: a mark on generic parameters, and
2049+`Pool` and `Vec` written for both cases.
2050+
2051+**9. Other routes that copy or overwrite an owner.** None of these is in
2052+7.6's list:
2053+
2054+- `COPY(y, x)` on arrays of owners;
2055+- `match` on another module's variable, which today names fields of a
2056+ copy (confirmed by running it), and so counts on the copy;
2057+- a variant case built from an owner, `has(b)`, which isn't plainly
2058+ "a literal";
2059+- `b := {}`, `x^ := {}`, and `Pool.add(p, {})`, which 7.6 allows, and
2060+ `Buf.init(b, a)` on a `Buf` with a lend held. Each sets `lends` to
2061+ zero under a hold. The hold's later let-go makes it -1. The next lend
2062+ brings it back to 0 while that slice is held, and the next growth
2063+ frees the block under it.
2064+
2065+Fix: state the rule as "a value of a type that holds an owner is never
2066+copied or overwritten in a safe module, nor by the library while its
2067+`lends` is above zero". Add `COPY`, case construction, `match` on a
2068+copy, and `{}` over a variable that isn't already empty (or make
2069+`init` and `{}` stop when `lends` isn't zero). Cost: a few rules and a
2070+test in each `init`.
2071+
2072+**10. `take`, `swap` and the count.** 7.6 names `Buf.take(var from, to)`
2073+and `Buf.swap` and says nothing of `lends`. Holds point at `from.lends`.
2074+After the move, `to` owns the block with a count of 0, and frees it at
2075+its next growth while the slices are held. Fix: `take` and `swap` stop
2076+when either owner's `lends` is above zero. Cost: a compare each. Add it
2077+to obligation 2.
2078+
2079+**11. Letting go of a hold while a `match` names its fields.**
2080+
2081+```
2082+p := Vs.add(v); p^ := a("abc");
2083+match p^ of
2084+| a(s): p := nil; grow(v); Out.str(s); (* s names a field of a freed block *)
2085+| b:
2086+end;
2087+```
2088+
2089+The names stand for the variable in place, and assigning `p` lets its
2090+hold go. Fix: a `match` on a lent variable takes its own count for the
2091+whole statement. Cost: an add and a subtract per such `match`.
2092+
2093+**12. The library breaks its own obligations.** Section 17 leaves these
2094+as they are, and each lets a safe program reach freed memory:
2095+
2096+- `List.head*` and `Node.next*` are exported, against obligation 4.
2097+ `n := l.head; List.pop(l); n^.val` reads a freed node.
2098+- `Thread.join` unmaps the mapping that holds the `Thread` record. The
2099+ `^Thread` that `Task.spawn` returns stays "lasting", and a second
2100+ `join` or a `signal` reads, and unmaps by, whatever the address
2101+ holds next.
2102+- Over C, `Sys.nextEntry`'s name points into C's `readdir` buffer,
2103+ which `closeDir` frees. `Dir` is no owner, so nothing counts it. A
2104+ `nextEntry` or `closeDir` after `closeDir` hands C a freed `DIR`.
2105+- Over musl, `Sys.env`'s "lasting" result can be freed by a later
2106+ `setEnv` of the same name, since musl frees the strings it made.
2107+- `Names(V)`'s procedures that return a key must be `ret`, or `remove`
2108+ frees what they gave. The proposal doesn't give its headings.
2109+
2110+Fix: unexport `List`'s pointers and give an iterator that lends;
2111+`Task` returns an owner handle that `join` takes by `var` and empties;
2112+`Dir` an owner; `env` copied into lasting memory over C. Cost: small,
2113+but it shows that obligations 1 to 5 need an audit of each module, not
2114+only the marks of section 17.
2115+
2116+### Ambiguities and contradictions
2117+
2118+**13. Section 3 calls a racing container program safe.** Section 3's
2119+definition counts a program as safe if its threads race "only on
2120+variables of a basic, pointer, procedure or slice type". Two threads
2121+calling `Buf.add` on one `Buf` race only on such fields (`len`,
2122+`data`), so the guarantee claims their behaviour is defined. 9.2 says
2123+it isn't. Fix: put 9.2's "a container's procedures called at once"
2124+into section 3's sentence.
2125+
2126+**14. A slice in a packed record, or in a block aligned to 8.** E.1
2127+promises one access for every slice. A slice field of a packed record
2128+is read in parts (5.5). `Vec` asks its allocator for 8-byte alignment.
2129+Either tears, or `movdqa` faults on it. Fix: no slice in a packed
2130+record; every allocator call for a type holding a slice asks for 16.
2131+
2132+**15. Returning what an owner inside a parameter lent.** 6.2 forbids
2133+returning a value "lent by an owner", even when the owner is a `ret`
2134+parameter. So `proc bytes2(ret const b: Buf): []U8 begin return
2135+Buf.bytes(b) end` is an error, and 14.2's recommended
2136+`Http.name(ret const m: Message; i): []U8` can't be written. If it is
2137+allowed, a caller of `name` sees only `m`, which is no owner (7.2), and
2138+has no count to raise. Fix: allow it when the `ret` parameter is itself
2139+the owner. For a record that holds owners, the caller raises each of
2140+their counts, or the accessor is refused.
2141+
2142+**16. When the epilogue lets go.** 7.3 says the let-go happens "as a
2143+`defer` would". If it is placed as a `defer` at the assignment, a user
2144+`defer f(b, s)` written before it runs after the let-go, and `f` can
2145+grow `b` and read `s`. Fix: holds are let go after every deferred
2146+statement has run.
2147+
2148+**17. "The end of the statement" for compound statements.** A count
2149+taken in a `while` condition, a `for` bound, an `if` condition or a
2150+`match` head: is it lowered once per evaluation or at the statement's
2151+`end`? Lowered once at `end`, a `while` raises it each round and leaks
2152+counts. Then `done` stops though nothing is held. A `try` that leaves
2153+mid-statement must lower it too. Fix: say per evaluation, and on every
2154+exit.
2155+
2156+**18. Two arms of one rule for `{}`.** 7.6 forbids passing an owner as
2157+a value parameter but allows a literal that leaves it out. So is
2158+`Pool.add(p, {})` allowed? Item 9 shows why the answer matters.
2159+
2160+**19. Writable constants beyond strings.** F.2 covers a string's bytes.
2161+An array constant of variants, enumerations or `BOOL`s may be sliced
2162+(4), and on a target where constants are writable, a compiler that
2163+folds `match Rows[0]` from the constant's case reads fields of another
2164+case. Fix: on such targets, writing any constant through a slice stops
2165+the program, or slices of non-string constants can't be written.
2166+
2167+### One-pass and implementability problems
2168+
2169+**20. A hold must be kept for every reference local.** A local may hold
2170+a lasting value at one assignment and an owner's lend at a later one
2171+(a loop's next round), and one pass doesn't know the later one when it
2172+compiles the earlier. So every assignment to every slice or pointer
2173+local must test and lower a hold, and every copy from one local to
2174+another must pass the hold on. That cost is per assignment, not "per
2175+lend held", and it falls on `src/`'s pointer loops (`o := o^.next`).
2176+Section 13 doesn't count it. Fix: measure it, or let a hold word exist
2177+only for locals declared with a mark (say `lent s: []U8`), checked at
2178+`end`.
2179+
2180+**21. Atomic counts depend on the whole program.** E.5 makes the counts
2181+`lock xadd` "in a program that imports `Thread`". A module compiled
2182+before another module's `import Thread` is read can't know which to
2183+emit, and separate compilation (10) forbids depending on it. Fix:
2184+always `lock`, or read every module's imports first. Cost: about 20
2185+cycles per lend, or a pass over the import graph.
2186+
2187+**22. Re-entry through the procedures a container is given.** `Map`
2188+calls `hash` and `eq`, `Sort` calls `less`, `Guarded.with` calls its
2189+procedure, and `Rt.atExit` procedures run after a failed check inside
2190+any of these. A safe callback can call `put`, `remove` or `done` on the
2191+same container while its own code is mid-loop: `done` inside `eq` while
2192+`get` probes leaves `slots` nil with an index still in hand. No
2193+obligation in 5.3 speaks of it, and checking the trusted code for every
2194+re-entry is not one pass of anything. Fix: obligation 6, "a module that
2195+calls a procedure given by safe code holds its own `lends` across the
2196+call", so that `done` stops; the library's containers do it.
2197+
2198+### Checked and found covered
2199+
2200+- `Pool.at` across `Pool.free`: the slot keeps its type, so a stale
2201+ pointer reads the wrong record of the right type, as 8.2 says. That
2202+ holds except for variants (item 1) and owners in slots (items 7 to 9).
2203+- Retired blocks and `reset`: the bytes keep their type; a held slice
2204+ sees new contents, safely.
2205+- `var` parameters aliasing: `f(x, x)` with a `done` inside stops on
2206+ the count; a callee assigning the caller's held local through `var`
2207+ leaves the hold set, which errs on the safe side.
2208+- Holds and threads: a thread raises a count only while it already
2209+ holds one, so the count can't pass through zero under another
2210+ thread's test.
2211+- `Task.spawn`: `keep x` refuses lent values, and owners can't be
2212+ passed by value.
2213+- `a, b := f(x)` and `return f(x)`: each target is checked as a single
2214+ assignment.
2215+- A `const` parameter of another module's variable is passed in place
2216+ today (run to confirm), so its count lands on the real owner.
2217+- A safe generic module instantiated with an owner: each instance is
2218+ checked, so a copy inside it is refused there.
2219+
2220+---
2221+
2222+## Appendix 5: adversarial review, claims about other languages and hardware
2223+
2224+This appendix checks every claim MEM_PROPOSAL.md makes about other
2225+languages, hardware, research and precedent. Of 44 claims checked, 5
2226+are wrong, 22 imprecise, 15 correct and 2 unverifiable. None of the
2227+errors breaks the design. Three of them touch it, though: 21.5 leans on
2228+Swift for a cross-thread check that Swift doesn't make; 9.2 says a
2229+slice published with no lock is safe, which fails on ARM; and 11 files
2230+Chrome's BackupRefPtr under debugging heaps, when it is the closest
2231+precedent for part C. Most of the imprecise ones are table cells that
2232+leave out a condition or a newer fact.
2233+
2234+How it was checked: through the session's proxy, which let through only
2235+GitHub-hosted sources (raw.githubusercontent.com) and web search. So
2236+primary sources were read where they live on GitHub (the Go memory
2237+model and spec, the C# standard, swift-evolution, Zig's langref and
2238+library, Fil-C, Chromium, glibc, slotmap, generational-arena,
2239+portable-atomic, GCC's libatomic, the Linux kernel's MTE document, D's
2240+DIPs, CPython). Vendor manuals (Intel SDM, AMD APM, Arm ARM) and the
2241+Modula-3, Ada and Java texts were checked through quotations that web
2242+search returned. Where a manual's section number could not be seen
2243+directly, the entry says so.
2244+
2245+### Wrong
2246+
2247+**W1. Section 21.5: "changes from another thread without the lock stop
2248+the program, as Swift's exclusivity checks do."**
2249+Wrong. Swift's run-time exclusivity checks are not required to see
2250+accesses from other threads, and by design they don't look. SE-0176
2251+says: "Dynamic enforcement is not required to detect concurrent
2252+conflicting accesses, and we propose that by default it should not
2253+make any effort to do so ... it can track accesses in a thread-local
2254+data structure." Swift leaves races to Thread Sanitizer and, since
2255+Swift 6, to `Sendable` checking at compile time.
2256+Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md (section "Concurrency").
2257+Correct wording: "... stop the program. Swift's run-time exclusivity
2258+checks don't do this: they track accesses per thread. The nearest
2259+precedents are Go's run-time check for concurrent map writes and
2260+ThreadSanitizer."
2261+
2262+**W2. Section 12, Zig row: "`@ptrCast`, `@intToPtr` anywhere".**
2263+Wrong name. `@intToPtr` was renamed `@ptrFromInt` in Zig 0.11 (2023),
2264+and `@ptrToInt` became `@intFromPtr`. Today's langref has
2265+`@ptrFromInt` (7 uses) and `@intFromPtr` (6), and no `@intToPtr`.
2266+Source: https://raw.githubusercontent.com/ziglang/zig/master/doc/langref.html.in (Zig has since moved to Codeberg; the GitHub copy is the last one mirrored).
2267+Correct wording: "`@ptrCast`, `@ptrFromInt` anywhere".
2268+
2269+**W3. Section 12, "Java, C#" row: forged pointers "none".**
2270+Wrong for C#. C# has real pointers, pointer arithmetic and casts from
2271+integers in `unsafe` code. The same row names C#'s `unsafe` blocks as
2272+its fence, so the row contradicts itself. Also,
2273+`System.Runtime.CompilerServices.Unsafe` and `MemoryMarshal` reinterpret
2274+references with no `unsafe` keyword at all, so the fence has holes. Java
2275+can forge addresses through `sun.misc.Unsafe` (its memory methods were
2276+deprecated for removal in JDK 23, JEP 471) and through the FFM API's
2277+restricted methods, which warn unless `--enable-native-access` is given
2278+(JEP 454 and 472).
2279+Sources: https://github.com/dotnet/csharpstandard (unsafe code chapter); https://mail.openjdk.org/pipermail/jdk-dev/2024-May/008910.html (JEP 471); https://www.infoq.com/news/2024/07/jep-472-restrict-jni-jdk-24.
2280+Correct wording: split the row. Java: "none in the language;
2281+`sun.misc.Unsafe` and FFM restricted methods, behind a flag". C#: "in
2282+`unsafe` code; also the `Unsafe` and `MemoryMarshal` classes, which
2283+need no `unsafe`".
2284+
2285+**W4. Section 9.2, point 1: "A program that hands slices from thread to
2286+thread, publishing a buffer for others to read, is then safe with no
2287+lock."**
2288+Wrong on ARM, and true on x86-64 only if the compiler keeps the stores
2289+in order. Single-copy atomicity means the 16 bytes don't tear. It says
2290+nothing about the order in which other stores are seen. AArch64 is
2291+weakly ordered. A reader can see the new slice and still see old bytes
2292+in the buffer it points at, unless the store is a release (`STLR`, or
2293+`DMB` then `STP`) and the load an acquire. If the buffer was a recycled
2294+heap block, those old bytes may be another type's pointers. That breaks
2295+the type guarantee of section 3, which publication with no lock is
2296+meant to keep. x86-64's TSO keeps store order, so there it holds,
2297+provided the compiler doesn't reorder.
2298+Sources: https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs (needs FEAT_LRCPC3's `LDIAPP`/`STILP`, or barriers, for acquire and release); the Arm ARM's memory model, B2.3.
2299+Correct wording: "... is then safe with no lock on x86-64. On AArch64 a
2300+slice store that publishes is a release and its load an acquire;
2301+appendix A says how."
2302+
2303+**W5. Section 12, "Java, C#" row: "references never tear; `long` may in
2304+Java".**
2305+Wrong by omission for C#, the row's other language. The C# standard
2306+(9.6) promises atomic reads and writes only for `bool`, `char`, the
2307+integer types up to 32 bits, `float` and references. It says "Reads and
2308+writes of other types, including `long`, `ulong`, `double`, and
2309+`decimal`, as well as user-defined types, need not be atomic." So C#
2310+structs tear, and that includes multi-word ones such as `ArraySegment<T>`
2311+and `Memory<T>`. C# stays memory-safe anyway because every array access
2312+is checked again against the array itself. That is worth saying, since
2313+it is the other way out of the torn-slice problem.
2314+Source: https://github.com/dotnet/csharpstandard/blob/draft-v8/standard/variables.md#96-atomicity-of-variable-references.
2315+Correct wording: "references never tear; `long` and `double` may (in
2316+C#, structs too), but each array access is checked again".
2317+
2318+### Imprecise
2319+
2320+**I1. Section 9.2: "`movdqa`, which Intel and AMD guarantee single-copy
2321+atomic on processors with AVX"; section 4: "none on x86-64 with AVX".**
2322+Right in substance, but conditions are missing. Intel's SDM Vol. 3A,
2323+"Guaranteed Atomic Operations" (section 9.1.1 in the editions that GCC
2324+and Microsoft's STL quote; numbering shifts between editions), says:
2325+"Processors that enumerate support for Intel AVX (by setting the
2326+feature flag CPUID.01H:ECX.AVX[bit 28]) guarantee that the 16-byte
2327+memory operations performed by the following instructions will always
2328+be carried out atomically: MOVAPD, MOVAPS, and MOVDQA; VMOVAPD,
2329+VMOVAPS, and VMOVDQA when encoded with VEX.128; VMOVAPD, VMOVAPS,
2330+VMOVDQA32, and VMOVDQA64 when encoded with EVEX.128 and k0 (masking
2331+disabled)", with the operands 16-byte aligned. AMD's APM Vol. 2
2332+(Access Atomicity; I couldn't see the section number) is broader in one
2333+way and narrower in another: "Processors that report CPUID
2334+Fn0000_0001_ECX[AVX](bit 28) = 1 extend the atomicity for cacheable,
2335+naturally-aligned single loads or stores from a quadword to a double
2336+quadword." So AMD's covers any aligned 16-byte load or store, but only
2337+to cacheable memory. Neither promise belongs to "x86-64 with AVX" in
2338+general. GCC's libatomic trusts it only on Intel, AMD, Zhaoxin and
2339+newer Centaur parts, and clears AVX for other vendors: "We don't have
2340+a guarantee from vendors of other CPUs with AVX, like VIA."
2341+"Single-copy atomic" is Arm's term; Intel says "carried out
2342+atomically".
2343+Sources: https://gcc.gnu.org/pipermail/gcc-patches/2022-February/590960.html (PR104688, quoting the SDM); https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/init.c; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/x86_64.rs ("Intel, AMD, and Zhaoxin officially guarantee this behavior (VIA has not responded)"); https://github.com/microsoft/STL/issues/4480.
2344+Correct wording: "moved with `movdqa` from a 16-byte-aligned address.
2345+Intel (SDM Vol. 3A, Guaranteed Atomic Operations) and AMD (APM Vol. 2,
2346+Access Atomicity, for cacheable memory) guarantee this atomic on
2347+processors that report AVX, and so does Zhaoxin. Other vendors' AVX
2348+parts take the fallback."
2349+
2350+**I2. Section 9.2: "ARMv8.4 has 16-byte atomic `LDP`/`STP`
2351+(FEAT_LSE2)".**
2352+True, but the conditions and the reach are missing. FEAT_LSE2 is
2353+optional from Armv8.2 and mandatory from Armv8.4. The Arm ARM (DDI
2354+0487, B2.2.1.1, as quoted on LKML) makes LDP/LDNP/STP of two 64-bit
2355+registers single-copy atomic only when the access is 16-byte aligned
2356+and goes to Inner Write-Back, Outer Write-Back Normal cacheable memory.
2357+Many 64-bit Arm machines in use don't have it: Cortex-A72 (Raspberry
2358+Pi 4), Cortex-A76 (Pi 5), Neoverse N1 (AWS Graviton2, Ampere Altra).
2359+They need `LDXP`/`STXP` loops (Armv8.0) or `CASP` (FEAT_LSE, Armv8.1).
2360+Sources: https://lkml.iu.edu/2511.1/09040.html; https://raw.githubusercontent.com/taiki-e/portable-atomic/main/src/imp/atomic128/aarch64.rs ("LDP/STP: load/store (if Armv8.4 FEAT_LSE2 (optional from Armv8.2, mandatory from Armv8.4) is available)").
2361+Correct wording: "With FEAT_LSE2 (mandatory from Armv8.4) an aligned
2362+16-byte `LDP`/`STP` to normal cacheable memory is single-copy atomic.
2363+Earlier cores use `LDXP`/`STXP` or `CASP`."
2364+
2365+**I3. Section 9.2: "On x86-64 without AVX, the implementation uses
2366+`lock cmpxchg16b`".**
2367+Works, with three costs left unsaid. First, CMPXCHG16B (CPUID CX16) is
2368+not in the x86-64 baseline (x86-64-v1): the first AMD64 processors
2369+lack it. Second, a load done as `lock cmpxchg16b` writes the line. So
2370+it faults on read-only pages, needs the memory to be writable (as
2371+portable-atomic's safety comments say), and makes readers contend with
2372+one another. libatomic: "Since load and store are implemented with
2373+CAS, they are not fast." Third, a store needs a CAS loop. Raz keeps
2374+slice constants, `[]` among them, in read-only data. The compiler would
2375+have to know those are never raced and read them plainly.
2376+Sources: https://raw.githubusercontent.com/gcc-mirror/gcc/master/libatomic/config/x86/host-config.h; portable-atomic's x86_64.rs, as above.
2377+
2378+**I4. Section 13.3, row E: "none: two 8-byte moves become one 16-byte
2379+one".**
2380+Not free when the slice goes to or from general registers. That is
2381+the usual case, since raz returns a slice in rax and rdx. A 16-byte
2382+load into an XMM register then needs `movq` plus `pextrq` (or a shuffle
2383+and `movq`) to split it, and a store needs `movq` plus `pinsrq` or
2384+`punpcklqdq` to join it: two to three more uops, and a few cycles of
2385+latency. `pextrq` and `pinsrq` are SSE4.1, which is not baseline
2386+x86-64. This is the machine's cost, and it should be measured like the
2387+others.
2388+Correct wording: "a load or store of a slice through an XMM register:
2389+one or two more instructions where its words go to or from general
2390+registers; records holding slices may grow by padding to 16."
2391+
2392+**I5. Section 7.5: "`inc qword [r]` ... about two cycles each ... `lock
2393+xadd`, about 20 cycles".**
2394+Rough. On Intel, an uncontended `lock` read-modify-write measures about
2395+18 cycles (uops.info, Skylake). On recent AMD cores it is lower. It is
2396+a full barrier, and under contention, with the line bouncing between
2397+cores, it costs hundreds of cycles. That is the case that matters for
2398+two threads lending from one locked `Buf`. A memory-destination `inc`
2399+has a throughput near one a cycle, but about five to six cycles of
2400+latency when chained through store forwarding.
2401+Sources: https://uops.info/html-instr/INC_LOCK_M32.html; https://www.agner.org/optimize/instruction_tables.pdf.
2402+Correct wording: "... `lock xadd`, about 20 cycles uncontended on
2403+Intel, and far more when threads contend for one owner".
2404+
2405+**I6. Section 12, Zig row: "the debug allocator finds use after free and
2406+double frees at run time; nothing in release".**
2407+Partly. `std.heap.DebugAllocator` (renamed from `GeneralPurposeAllocator`
2408+in 0.14.0) lists "Double free detection" and "Leak detection, with
2409+stack traces". It doesn't detect use after free. It "Never reuses
2410+memory addresses" and gives freed pages back "so that it causes page
2411+faults when used", and in safe modes freed memory reads as `0xaa`. So
2412+a use after free may fault or read junk, and nothing reports it as
2413+such. The allocator is chosen by the program, not by the build mode:
2414+it works in ReleaseSafe too.
2415+Source: https://raw.githubusercontent.com/ziglang/zig/master/lib/std/heap/debug_allocator.zig (header comment).
2416+Correct wording: "the debug allocator finds double frees and leaks, and
2417+never reuses addresses, so a use after free tends to fault; a program
2418+chooses it, usually in Debug".
2419+
2420+**I7. Section 12, "C++, hardened" row: "hardened `std` containers;
2421+`-fbounds-safety` for C (clang)".**
2422+This mixes two things. `-fbounds-safety` is a C extension, not C++
2423+hardening. Apple designed it and ships it in Apple's clang. Upstream,
2424+it is "being incrementally upstreamed", behind
2425+`-fexperimental-bounds-safety`. On the C++ side, the newer fact is
2426+missing: C++26 standardizes library hardening (P3471, adopted at
2427+Hagenberg, February 2025), on top of libc++'s hardening modes and
2428+libstdc++'s `_GLIBCXX_ASSERTIONS`.
2429+Sources: https://lists.llvm.org/pipermail/cfe-commits/Week-of-Mon-20240513/579251.html; https://clang.llvm.org/docs/BoundsSafetyImplPlans.html; https://open-std.org/JTC1/SC22/WG21/docs/papers/2025/p3471r4.html.
2430+Correct wording: C row: "Spatial: none; Apple's `-fbounds-safety`
2431+extension (clang, partly upstream) adds checked bounds". C++ row:
2432+"hardened standard library (libc++, libstdc++; standard in C++26 by
2433+P3471)".
2434+
2435+**I8. Section 12, "Odin, Hare, C3" row: spatial "checked".**
2436+True by default for all three, but each can turn it off. C3 checks
2437+only in its safe (debug) mode, and in fast builds an out-of-bounds index
2438+is undefined. Hare checks every slice and array access, but its `[*]T`
2439+arrays are unchecked. Odin has `#no_bounds_check` and
2440+`-no-bounds-check`.
2441+Sources: https://c3-lang.org/language-rules/undefined-behaviour/; https://harelang.org/blog/2022-06-21-safety-features/.
2442+Correct wording: "checked by default (C3: in safe builds only); each can
2443+turn it off".
2444+
2445+**I9. Section 12, Swift row: fence "`Unsafe` in names".**
2446+Out of date. SE-0458, "Opt-in Strict Memory Safety Checking", is
2447+implemented in Swift 6.2. It adds `-strict-memory-safety`, an `@unsafe`
2448+attribute, a `@safe` attribute for a declaration that is "actually
2449+safe to use" though its signature holds unsafe types, and an `unsafe`
2450+expression "much like `try` and `await`". That is a real fence, and
2451+`@safe` is section 5.3's trust in a safe interface.
2452+Source: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0458-strict-memory-safety.md.
2453+Correct wording: "`Unsafe` in names; since Swift 6.2, an opt-in
2454+checked fence (`@unsafe`, `@safe`, `unsafe` expressions)".
2455+
2456+**I10. Section 12, Ada row: races "protected objects".**
2457+Protected objects are the tool, not the guarantee. In Ada, two
2458+unsynchronized conflicting uses of a shared variable are erroneous (RM
2459+9.10): "The execution of two concurrent actions is erroneous if the
2460+actions make conflicting uses of a shared variable." SPARK, under the
2461+Ravenscar and Jorvik profiles, proves there are no data races.
2462+Source: https://ada-lang.io/docs/arm/AA-9/AA-9.10/.
2463+Correct wording: "erroneous unless synchronized (protected objects,
2464+atomics); SPARK proves their absence".
2465+
2466+**I11. Section 12: "Ada's accessibility levels are part B's frame,
2467+parameters and lasting memory, nearly exactly."**
2468+Overstated. Ada's levels (RM 3.10.2) attach mainly to where an access
2469+type is declared. A library-level access type can't designate a
2470+deeper object. Most checks are static, but those for anonymous access
2471+parameters and some others run at run time and raise `Program_Error`.
2472+There is no notion of "lent by this parameter" for a result. The
2473+closest match to part B is C#'s ref-safety rules: their "safe-context"
2474+values are "declaration-block", "function-member" and
2475+"caller-context". Those are part B's frame, parameters and lasting
2476+nearly one for one. C# 11 adds `scoped` and `[UnscopedRef]`, which play
2477+the roles of `ret` and `keep`.
2478+Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md.
2479+Correct wording: "Ada's accessibility levels are the idea; C#'s
2480+safe-contexts (declaration block, function member, caller) are part
2481+B's three lenders nearly exactly."
2482+
2483+**I12. Section 5.3: "This is Modula-3's rule for an `UNSAFE MODULE`
2484+that implements a safe `INTERFACE`".**
2485+Right as far as it goes, but Modula-3 also fences imports, and raz
2486+doesn't. The Modula-3 report's Safety section says: "It is a static
2487+error for a safe interface to import an unsafe one or for a safe module
2488+to import or export an unsafe interface." Raz lets any safe module
2489+import an unsafe one and fences per procedure (`unsafe proc`). That is
2490+closer to D's `@safe`/`@trusted`/`@system` per function, and to Rust's
2491+`unsafe fn`, than to Modula-3.
2492+Source: https://www.cs.purdue.edu/homes/hosking/m3/reference/safety.html.
2493+Correct wording: add "Unlike Modula-3, which forbids a safe module to
2494+import an unsafe interface, raz fences per procedure, as D's
2495+`@trusted` and Rust's `unsafe fn` do."
2496+
2497+**I13. Section 12: "The unit of review is a file, as Wirth's languages
2498+always had it."**
2499+Modula-3 isn't Wirth's. It came from DEC SRC and Olivetti, building on
2500+Modula-2+. Pascal had no modules, so "always" is wrong. Modula-2 and
2501+Oberon do mark low-level code by importing `SYSTEM` per module.
2502+Correct wording: "The unit of review is a module, as in Modula-2's and
2503+Oberon's `IMPORT SYSTEM` and Modula-3's `UNSAFE`."
2504+
2505+**I14. Section 12, Vale row: "regions skip the check"; races "regions";
2506+fence "`unsafe`".**
2507+These are mostly Vale's plans. Vale's last release is 0.2 (2022). Its
2508+own project page lists the region borrow checker and hybrid-generational
2509+memory as medium-term goals, and its `unsafe` blocks and "Fearless
2510+FFI" were proofs of concept. Generational references themselves,
2511+section 8.2's claim, are right: each object carries a current
2512+generation, each non-owning reference a remembered one, checked on
2513+dereference. Owning references aren't checked.
2514+Sources: https://vale.dev/memory-safe; https://vale.dev/project; https://vale.dev/blog/version-0.2-released.
2515+Correct wording: "generational references, checked at each
2516+dereference; regions, which would skip the check, are designed and not
2517+finished".
2518+
2519+**I15. Section 12, Cyclone row: temporal "regions, checked
2520+statically".**
2521+Leaves out that Cyclone's heap region is garbage collected
2522+(conservatively, with the Boehm collector). Grossman's PLDI 2002 paper
2523+integrates regions "with stack allocation and a garbage collector".
2524+Unique and reference-counted pointers came later (Hicks et al.).
2525+Cyclone's temporal safety for the heap is a GC, which is what raz
2526+refuses.
2527+Sources: https://www.cs.umd.edu/~mwh/papers/GrossmanMJHWC02.html; https://www.cs.washington.edu/homes/djg/slides/cyclone_pldi02.pdf.
2528+Correct wording: "regions checked statically; the heap region garbage
2529+collected".
2530+
2531+**I16. Section 12, "Fil-C, CHERI" row: "Fil-C: a few times slower";
2532+"Fil-C: atomic capabilities"; "CHERI: revocation".**
2533+Fil-C's own figures are "about 1.5x-4x slower" (README and Manifesto,
2534+version 0.686). On races, Fil-C says "Pointer races on pointers not
2535+marked `_Atomic` or `volatile` lead to Fil-C panics, at worst". Only
2536+atomic pointers get an "atomic box". CHERI's capabilities give spatial
2537+safety in hardware. Its temporal safety needs software revocation
2538+sweeps (Cornucopia, in CheriBSD), and it costs 128-bit pointers.
2539+Sources: https://raw.githubusercontent.com/pizlonator/fil-c/deluge/README.md; https://raw.githubusercontent.com/pizlonator/fil-c/deluge/Manifesto.md.
2540+Correct wording: "Fil-C: 1.5 to 4 times slower, and a concurrent GC;
2541+CHERI: 128-bit capabilities, and revocation by software sweeps".
2542+
2543+**I17. Section 19: "[MTE and CHERI] aren't on x86-64, and they are
2544+probabilistic (MTE's four bits)."**
2545+Two fixes. First, only MTE is probabilistic: a 4-bit tag per 16-byte
2546+granule (Linux's document: "a 4-bit allocation tag for each 16-byte
2547+granule"), so a stale pointer passes 1 time in 16 by chance. CHERI's
2548+bounds are exact. Second, x86 is on its way: Intel and AMD announced
2549+ChkTag, a common x86 memory-tagging specification, on 13 October 2025,
2550+with no shipping date. MTE is also not only for debugging any more.
2551+Apple's Memory Integrity Enforcement runs Enhanced MTE always on and
2552+synchronously on the iPhone 17 (September 2025).
2553+Sources: https://raw.githubusercontent.com/torvalds/linux/master/Documentation/arch/arm64/memory-tagging-extension.rst; https://www.amd.com/en/blogs/2025/amd-and-intel-celebrate-first-anniversary-of-x86-ecosys.html; https://www.phoronix.com/news/AMD-Intel-One-Year-x86-Eco; https://security.apple.com/blog/memory-integrity-enforcement.
2554+Correct wording: "They aren't on x86-64 yet (Intel and AMD announced
2555+ChkTag in 2025). MTE is probabilistic, with four bits a tag; CHERI is
2556+exact, but needs software revocation for use after free."
2557+
2558+**I18. Section 11: "This is ... Chrome's MiraclePtr quarantine".**
2559+MiraclePtr is not a debugging heap, and its quarantine isn't a fixed
2560+count. `raw_ptr<T>`, implemented by BackupRefPtr, keeps a reference
2561+count in each PartitionAlloc slot. It is "quarantining the freed memory
2562+as long as any dangling `raw_ptr<T>` pointing to it exists, and
2563+poisoning it (with 0xEF..EF pattern)". Its constructor, destructor and
2564+assignment "need to maintain BackupRefPtr's ref-count (atomic
2565+increment/decrement)". It ships in production Chrome. That makes it a
2566+precedent for part C, not part G: count the references a block has
2567+lent, and retire the block instead of freeing it while the count is
2568+above zero. Its documentation also records the cost part C should
2569+expect: "on a couple occasions it led to significant memory leaks". A
2570+fixed FIFO quarantine with guard bytes, like part G's, is
2571+AddressSanitizer's quarantine and redzones, and GWP-ASan's.
2572+Source: https://raw.githubusercontent.com/chromium/chromium/main/base/memory/raw_ptr.md.
2573+Correct wording in 11: "This is AddressSanitizer's quarantine and
2574+redzones, Zig's debug allocator and glibc's `MALLOC_PERTURB_`, without
2575+their reach." Add to section 7: "Chrome's BackupRefPtr (MiraclePtr)
2576+does the same in C++: it counts a block's references and quarantines
2577+it on free while the count is above zero."
2578+
2579+**I19. Section 3 and 9.2, point 2: a race on a whole record or variant
2580+"is undefined, as in Go".**
2581+Go doesn't call it undefined. The memory model says a racy read of a
2582+multi-word value may see "inconsistent values not corresponding to a
2583+single write". Only "when the values depend on the consistency of
2584+internal (pointer, length) or (pointer, type) pairs, as can be the case
2585+for interface values, maps, slices, and strings in most Go
2586+implementations, such races can in turn lead to arbitrary memory
2587+corruption." Go sets itself apart from C and C++, "where the meaning of
2588+any program with a race is entirely undefined". A race on a plain
2589+struct of integers just gives mixed values.
2590+Source: https://raw.githubusercontent.com/golang/go/master/doc/go_mem.html (go.dev/ref/mem).
2591+Correct wording: "undefined. Go is narrower: a race tears such a value,
2592+and corrupts memory only through its pointer and length or type pairs."
2593+
2594+**I20. Section 9.1: Go's memory model on races over multi-word values.**
2595+The quotation is right, but the list it gives is short. Go names
2596+"interface values, maps, slices, and strings", hedged "in most Go
2597+implementations", and says such races "can in turn lead to arbitrary
2598+memory corruption". The proposal's list drops maps, and its "an
2599+interface, a slice, a string" reads as Go's words when they are a
2600+paraphrase.
2601+Source: as I19.
2602+Correct wording: "Go's memory model says that races on values made of
2603+(pointer, length) or (pointer, type) pairs, 'interface values, maps,
2604+slices, and strings in most Go implementations', 'can in turn lead to
2605+arbitrary memory corruption'."
2606+
2607+**I21. Section 12: "From Swift: checking exclusivity at run time where
2608+the compiler can't, as part C counts lends."**
2609+Loose. Swift's dynamic exclusivity tracks the start and end of each
2610+access to a class property, global or escaped variable, per thread
2611+(W1). It doesn't count. Part C counts outstanding loans and refuses or
2612+defers a release while any is held. That is Rust's `RefCell` (a borrow
2613+count that panics), CPython's `bytearray` (it keeps `ob_exports` and
2614+refuses to resize: "Existing exports of data: object cannot be
2615+re-sized"), Java's and .NET's fail-fast iterators (a modification
2616+count), and Chrome's BackupRefPtr (I18).
2617+Sources: https://raw.githubusercontent.com/python/cpython/main/Objects/bytearrayobject.c; https://raw.githubusercontent.com/rust-lang/rust/master/library/core/src/cell.rs.
2618+Correct wording: "From Rust's `RefCell`, CPython's buffer exports and
2619+Chrome's BackupRefPtr: a count of what is lent, checked at run time,
2620+where the compiler can't see it."
2621+
2622+**I22. Section 8.2: "Part of the first is that each slot is 32 bytes,
2623+not 16"; and open question 6, one word or two for a handle.**
2624+The precedent the proposal cites answers the question, and the
2625+proposal doesn't use it. slotmap's key is one 64-bit word: a 32-bit
2626+index and a 32-bit version (`idx: u32, version: NonZeroU32`). A slot
2627+costs `4 + max(sizeof(T), 4)` bytes. Versions wrap after 2^31 reuses of
2628+a slot, "and in all circumstances is the behavior safe". So the 32-byte
2629+slot of the benchmark comes from the two-word `Handle` chosen here, not
2630+from generational handles as such. The 1.5x past the caches is partly
2631+an artifact of that choice.
2632+Source: https://raw.githubusercontent.com/orlp/slotmap/master/src/lib.rs.
2633+Correct wording: add to 21.6: "slotmap takes one word, 32 bits each,
2634+and lets the version wrap; with it, a slot of a 16-byte `T` is 20 or
2635+24 bytes, not 32."
2636+
2637+### Correct
2638+
2639+**C1. Section 9.1: "Java closes it by tearing only `long` and `double`,
2640+never a reference."** Correct. JLS 17.7: a non-volatile `long` or
2641+`double` write may be treated "as two separate writes, one to each
2642+32-bit half"; "Writes to and reads of references are always atomic,
2643+regardless of whether they are implemented as 32-bit or 64-bit
2644+values." Source: https://docs.oracle.com/javase/specs/jls/se21/html/jls-17.html#jls-17.7 (read through a mirror: https://www.oreilly.com/library/view/the-java-language/9780133260335/ch17lev1sec7.html).
2645+
2646+**C2. Section 7.4: "This is Go's `append`: the old slice still sees the
2647+old array."** Correct for a growing append. The spec says: "If the
2648+capacity of s is not large enough to fit the additional values, append
2649+allocates a new, sufficiently large underlying array ... Otherwise,
2650+append re-uses the underlying array." In Go the GC keeps the old array
2651+while it is referenced. Raz retires the block and frees it at a later
2652+growth once the count is 0, which matches for every slice still held.
2653+Source: https://raw.githubusercontent.com/golang/go/master/doc/go_spec.html.
2654+
2655+**C3. Section 19: `append(s, s...)` is right in Go.** Correct: append
2656+copies with memmove semantics, so overlap is safe. Source: as C2.
2657+
2658+**C4. Section 12, Go row: checked, GC, forged pointers "only through
2659+`unsafe`", fence `import "unsafe"`.** Correct. cgo is the other way
2660+out, and it is also visible in imports (`import "C"`).
2661+
2662+**C5. Section 8.2: "the generational arena of Rust's `slotmap` and
2663+`generational-arena`".** Correct. slotmap: "persistent unique keys ...
2664+The keys returned by `slotmap` are versioned." generational-arena: "A
2665+safe arena allocator that allows deletion without suffering from the
2666+ABA problem by using generational indices." Sources: https://github.com/orlp/slotmap; https://github.com/fitzgen/generational-arena.
2667+
2668+**C6. Section 8.2: "the handle pattern Zig and game engines use".**
2669+Correct as practice. The pattern's best-known write-up is Andre
2670+Weissflog's "Handles are the better pointers" (2018), worth citing:
2671+https://floooh.github.io/2018/06/17/handles-vs-pointers.html.
2672+
2673+**C7. Section 12, Rust row, and 9.1: `Send`/`Sync` checked by the type
2674+system; `unsafe` blocks and functions.** Correct.
2675+
2676+**C8. Section 19: "non-lexical lifetimes are a fixpoint over the control
2677+flow, not one pass".** Correct. NLL (RFC 2094) computes liveness and
2678+region constraints by dataflow over MIR's control-flow graph.
2679+
2680+**C9. Section 12, Swift row: "exclusivity checked at compile and run
2681+time"; "Swift 6: `Sendable`, checked".** Correct. Swift 5 enabled
2682+run-time exclusivity checks in release builds; the Swift 6 language
2683+mode makes data-race checks errors. Source: https://github.com/swiftlang/swift-org-website/blob/main/_posts/2019-02-05-swift-5-exclusivity.md.
2684+
2685+**C10. Section 12, Modula-3 row: a GC for traced references, `DISPOSE`
2686+only in unsafe modules, `UNSAFE MODULE` and `UNSAFE INTERFACE`.**
2687+Correct. The report: "An interface or module not explicitly labeled
2688+UNSAFE is called safe." SRC's compiler: `IF Module.IsSafe () THEN
2689+Error.Msg ("DISPOSE: unsafe operation")`. Untraced references (`UNTRACED
2690+REF`) aren't collected. Sources: https://www.cs.purdue.edu/homes/hosking/m3/reference/unsafe.html; https://softwarepreservation.computerhistory.org/modula3/archive/DEC_SRC/release-2.11-unpacked/compiler/src/builtinOps/Dispose.m3.
2691+
2692+**C11. Section 12, Oberon row: unsafe only through `SYSTEM`, marked by
2693+`IMPORT SYSTEM`.** Correct. The GC belongs to the Oberon system rather
2694+than the language report, which is a fine point.
2695+
2696+**C12. Section 12, Ada row: `Unchecked_Deallocation`,
2697+`Unchecked_Conversion`, "SPARK adds ownership".** Correct. SPARK's
2698+pointers follow "the Rust model": move for pool-specific access types,
2699+borrow and observe for anonymous ones (SPARK Community 2020 onward).
2700+Source: https://docs.adacore.com/spark2014-docs/html/ug/en/source/access.html.
2701+
2702+**C13. Section 12, Zig row: bounds "checked in Debug and
2703+ReleaseSafe".** Correct. The langref: "In Debug and ReleaseSafe mode
2704+... triggers a safety panic"; ReleaseFast and ReleaseSmall assume
2705+the checks away.
2706+
2707+**C14. Section 11: "Zig's debug allocator".** Correct name since Zig
2708+0.14.0 (`std.heap.DebugAllocator`; `GeneralPurposeAllocator` survives
2709+as a deprecated alias). Source: https://ziglang.org/download/0.14.0/release-notes.html.
2710+
2711+**C15. Section 11: glibc's `MALLOC_PERTURB_`.** Correct: it fills
2712+blocks "when they are allocated ... and freed". It has no quarantine
2713+and no guard bytes; the proposal's "without their reach" allows for
2714+that. Source: https://raw.githubusercontent.com/bminor/glibc/master/manual/memory.texi.
2715+
2716+### Unverifiable
2717+
2718+**U1. Section 12, Zig row: races "UB".** Zig has no written memory
2719+model. Its atomics follow LLVM's, under which a data race on a
2720+non-atomic location is undefined, so the claim is very likely right.
2721+No Zig document says so.
2722+
2723+**U2. Section 12, Modula-3 row: races "not promised".** The report
2724+doesn't speak to it in what I could read. Since Modula-3's open arrays
2725+and `TEXT`s are behind references, a race in a safe module may not
2726+break memory at all. Leave it, or write "not addressed by the report".
2727+
2728+### Precedent the proposal misses
2729+
2730+- **D: `@safe`, `@trusted`, `@system`, and DIP1000's `scope` and `return
2731+ scope`.** This is the closest match to parts A and B together.
2732+ `@trusted` is section 5.3's trust, per function. `return scope` is
2733+ `ret`, and plain `scope` is the opposite of `keep`. PROPOSALS.md
2734+ cites DIP1000; MEM_PROPOSAL.md doesn't. It should, together with D's
2735+ lesson that the corners (fields, generics, delegates) took years.
2736+ DIP1000 is still behind `-preview=dip1000`, and its document is marked
2737+ "Superseded". Source: https://github.com/dlang/DIPs/blob/master/DIPs/other/DIP1000.md.
2738+- **C#: `ref struct`, `Span<T>`, `scoped`, ref-safety contexts.** C#
2739+ checks with local, one-pass rules that a `Span<T>` never outlives what
2740+ it points at, with three contexts that are part B's three lenders
2741+ (I11). It is the strongest evidence that part B works in a
2742+ mainstream compiler without lifetimes in types. Source: https://github.com/dotnet/csharplang/blob/main/proposals/csharp-11.0/low-level-struct-improvements.md.
2743+- **Swift: `~Escapable` types, lifetime dependencies, `Span`, and
2744+ SE-0458.** Swift 6.2's non-escapable types (SE-0446) and `Span`
2745+ (SE-0447) give a slice that can't outlive its source, with a
2746+ dependence written on the function. That is `ret` again. SE-0458's
2747+ `@safe` and `@unsafe` are the fence and the trust. Sources: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0446-non-escapable.md; .../0447-span-access-shared-contiguous-storage.md; .../0458-strict-memory-safety.md.
2748+- **Chrome's BackupRefPtr.** Counted references with quarantine on
2749+ free, in production C++ (I18). It is the precedent for part C's
2750+ retirement, with measured costs and recorded leaks.
2751+- **Rust's `RefCell`, CPython's buffer exports, Java's `modCount`.**
2752+ Run-time counts of loans that refuse a change while one is held
2753+ (I21). CPython's `bytearray` refusing to resize while exported is
2754+ part C's "stop" alternative from section 19, shipped for years.
2755+- **Checked C.** Microsoft's extension of C with checked pointer types
2756+ (`_Ptr`, `_Array_ptr` with bounds) and `_Checked`/`_Unchecked`
2757+ scopes. It is a fence in a C-like language, at a finer grain than a
2758+ module, and it shows the cost of a per-block fence.
2759+ https://github.com/checkedc/checkedc.
2760+- **SafeStack (clang).** It moves address-taken locals to a separate
2761+ stack. That is relevant to what an unsafe module's `ADR` of a local
2762+ can reach, and to part F's frame slots. https://clang.llvm.org/docs/SafeStack.html.
2763+- **Hylo (formerly Val).** Mutable value semantics: no stored
2764+ references at all, only projections that last the call. That is the
2765+ extreme of section 14's "a record can't keep a slice into a buffer
2766+ that belongs to someone else", and it argues that the limit is
2767+ livable. https://www.hylo-lang.org.
2768+- **Austral.** Linear types with lexical borrows, kept small on purpose
2769+ so that one person can hold the whole checker in their head. That
2770+ matters to raz's "a beginner can follow". https://austral-lang.org.
2771+- **Mojo and Carbon.** Mojo has ownership with inferred "origins", a
2772+ Rust-like model with lighter syntax. Carbon plans a safe subset
2773+ reached by incremental migration from C++, as part of section 20's
2774+ order of work. Both are worth a line in section 19's view of Rust's
2775+ way. https://docs.modular.com/mojo/manual/values/lifetimes; https://github.com/carbon-language/carbon-lang/blob/trunk/docs/design/safety/README.md.
2776+- **Modula-2+ and Cedar.** They had safe and unsafe (Cedar: checked,
2777+ trusted, unchecked) modules before Modula-3, and are where the
2778+ module fence of section 12 comes from.
2779+- **AddressSanitizer and GWP-ASan.** The real models for part G's
2780+ quarantine and guard bytes (I18).
2781+
2782+---
2783+
2784+## Appendix 6: adversarial review, the proposal's numbers and samples
2785+
2786+**Summary.** The five demo programs compile with `-Werror`, print what
2787+the proposal says, and do the undefined thing claimed. The callgrind
2788+figures repeat to within a thousand instructions. Several other things
2789+don't hold:
2790+
2791+- The survey counts lines, not operations, and the proposal calls them
2792+ operations.
2793+- Its "test/libc" row is really `lib/Sys.raz`.
2794+- rnet's TLS backends and two of its tests were never compiled.
2795+- Most `ADR`s in rnet, rjson, rlX11 and ravite are arguments to the
2796+ programs' own procedures, not to the library. So the claim that
2797+ v0.19.0 "removed them already" is wrong.
2798+- Every one of raz's own benchmark kernels says `check off;`.
2799+- The kernels don't run "past the caches": the machine reports a
2800+ 260 MB L3.
2801+- The 16-to-32-byte and fat-pointer conclusions are confounded by node
2802+ layout and by noise.
2803+- Part C's run-time rule would stop the library's own `Opt.say`, the
2804+ compiler's `Parse.moduleParams` and ravite's `load`.
2805+- 7.3 forbids the accessor that 14.2 recommends.
2806+- No container's `init` is marked `keep`, so a `Buf` over an `Arena`
2807+ (used by `Fmt.eprint` and `examples/Sh`) can't be written safely.
2808+- Three of the sample error messages are wrong, and one gives help that
2809+ doesn't compile.
2810+- The compiler cost is likely low by 40 to 70%, judged against
2811+ PROPOSALS' own revised figure.
2812+
2813+Commands below were run on 2026-10-17. The scratch data used is in
2814+`/tmp/claude-0/-home-user-raz/bab05b52-9d9d-4262-9f3e-de1807ce50a5/scratchpad/`
2815+(S below). Files made for this review are in
2816+`/tmp/claude-0/-home-user/f9bd1744-45c5-5c51-82fd-fddfc77d01cc/scratchpad/`
2817+(W below).
2818+
2819+### 1. Survey counts
2820+
2821+**1.1 "Places", counted once each, are lines (2.1, 2.2, appendix 1).**
2822+`Diag.tally` prints `path:line` with no column, and `agg.py` keys on
2823+(kind, file, line). So two operations of one kind on one line count
2824+once. I rebuilt the tally compiler to print the offset as well
2825+(`W/tc/raz`) and compiled `src/Raz.raz` with it:
2826+
2827+| kind | lines (proposal) | distinct places |
2828+|---|---|---|
2829+| `ADR` | 27 | 32 |
2830+| deref | 1,015 | 1,410 |
2831+| `p[i]` | 277 | 372 |
2832+| `p[a..b]` | 30 | 44 |
2833+| ptr cast | 42 | 48 |
2834+| `p ± i` | 3 | 4 |
2835+
2836+The distinct places are themselves a floor: nested operations at one
2837+position still merge. **Correction:** call them "lines with", or give
2838+the operation counts. The ratios between modules hold.
2839+
2840+**1.2 The `test/libc` row is library code.** `test/libc/mods/Sys.raz`
2841+is a link to `lib/Sys.raz`, the C `Sys`. It holds 108 of the row's 110
2842+`ADR`s, 63 of its 64 casts and all 35 of its `p[i]`. The tests' own
2843+files hold 2 `ADR`s, 1 cast and 1 `NEW`. **Correction:** move 242
2844+fenced operations to `lib/` (`lib/Sys`, the C one), and say so when
2845+naming the library's unsafe modules (2.2, "Sys (287 operations)" is
2846+the Linux file only).
2847+
2848+**1.3 rnet was compiled in part.** `S/out/rnet.log` shows
2849+`test/Net.raz` and `test/Https.raz` failing, because `module Tls is in
2850+.../gnutls/Tls.raz and .../openssl/Tls.raz`. So neither TLS backend
2851+was counted. Both are `extern` modules: 26 and 35 `extern`s, 27 and 24
2852+`ADR`s. **Correction:** 5.4 says "rnet needs it only to keep
2853+`Http.Message`". In fact both `tls/*/Tls.raz` must say `unsafe;`, as
2854+`Sqlite` must. Section 15's rnet row should list them.
2855+
2856+**1.4 rnet's and rjson's `ADR` totals disagree with appendix 1.** 2.2
2857+gives rnet 572 and rjson 77. Appendix 1 gives 471 and 91 (lines, from
2858+the tally). A grep outside comments finds 792 occurrences in rnet (621
2859+lines) and 110 in rjson. rlX11's 89 doesn't come out either: grep
2860+finds 108, 78 of them in `src/`. ravite's 202 and rmacs's 560 match a
2861+grep.
2862+
2863+**1.5 "Almost every ADR is ... the library's old pointer parameters"
2864+is wrong for most repositories.** I sorted each `ADR` by the call it
2865+is an argument to (`W/py/adr.py`, a textual parser):
2866+
2867+| repo | `ADR`s | to the library | to its own procedures and modules | casts and other |
2868+|---|---|---|---|---|
2869+| rnet | 792 | 226 | 525 | 41 (34 to `Tls`) |
2870+| rjson | 110 | 35 | 70 | 5 |
2871+| rflate | 67 | 48 | 16 | 3 |
2872+| rsqlite | 42 | 12 | 27 (some to C) | 3 |
2873+| rmacs | 560 | 424 | 132 | 4 |
2874+| ravite | 202 | 107 | 93 | 2 |
2875+| rlX11 | 108 | 5 | 100 | 3 |
2876+
2877+The top callees in rnet are its own `fetches`, `resolves`,
2878+`Conn.close` and `parseAnswer`. In rlX11 it is its own `expect`. Those
2879+are the programs' pointer-taking headings. They mend by `var`, but the
2880+programs have to be rewritten for it; v0.19.0's library didn't remove
2881+them. **Correction:** "Most `ADR`s are arguments; in rmacs and rflate
2882+mostly to the library, in rnet, rjson and rlX11 mostly to the
2883+programs' own pointer parameters."
2884+
2885+**1.6 "Nobody uses `check off;`" (2.2, 13.2) is wrong.** All seven
2886+kernels in `test/bench` say `check off;` (`grep -l '^check off'
2887+test/bench/*.raz` gives 7 of 7). The Makefile says so too: "the
2888+kernels of test/bench, which say check off". So does
2889+`test/run/mods/Unchecked.raz`. The survey left `test/` out, but the
2890+inference "no one has wanted them off" doesn't follow: raz's own speed
2891+comparison with FPC turns the checks off. **Correction:** "No library
2892+module or program surveyed turns them off. raz's benchmark kernels do,
2893+to match FPC -O2."
2894+
2895+**1.7 Frees and `done`s (2.2, 8.1).**
2896+
2897+- The hand frees match: `src/` 7, rmacs 9 (4 `Mem.free` plus 5
2898+ `Heap.heap^.free`), rjson 6, ravite 2, rlX11 1, others 0.
2899+- rnet has 41 `done`s, not 30: `src/` has 30, its tests 11. With 41,
2900+ "54 to 26" becomes 65 to 25 or 26. That still makes the point.
2901+- The mendings in section 15 misdescribe some of the frees:
2902+ - rjson's 6 are all `Mem.free` of grown arrays (`nodes`, `kids`,
2903+ `stack`), with no `Str.free`. They mend by `Vec`, not by `Names`
2904+ or `Buf`.
2905+ - ravite's 2 are `Text`'s grown `data` and `changes`, not windows.
2906+ They mend by `Vec` or `Buf`, not `Pool`.
2907+ - Only rmacs's 5 `Heap` frees, of windows and parts, are `Pool`
2908+ material.
2909+
2910+**1.8 "35 places assign Buf.bytes, Vec.all or Windows.all"** holds.
2911+A grep finds 36 assignments to locals and 3 to fields (`m^.body`, and
2912+`res^.body` twice). The only `.all` is rmacs's `Windows.all`.
2913+
2914+**1.9 "Records that hold slices: src/ 10" isn't reproduced.** I find
2915+three slice fields in `src/`'s records: `Diag.File.path`,
2916+`Sym`'s `path*` (line 116) and `X64.Said.text`. 13.3 repeats "10".
2917+**Correction:** 3, or say how 10 was counted.
2918+
2919+**1.10 Dereferences: "Every one is a pointer from NEW on the heap,
2920+which the compiler never frees" (2.2) is false today.** Some are not:
2921+
2922+- `X64`'s `r^`, `size^` and `o^` point at locals through `ADR(r)` and
2923+ `ADR(ao[an])`.
2924+- `Elf`'s `dynSize^` and `roExtra^` point at locals.
2925+- `Scan`'s `bits^` points at a local.
2926+- `Diag`'s `f^` and `Chunk`'s `c^` point into grown arrays that
2927+ `regrab` frees (`Scan.raz:137`, `Diag.raz:103`).
2928+
2929+They are few (tens), and part A's mendings would remove them. But the
2930+sentence should say "nearly every".
2931+
2932+**1.11 The `src/` `ADR`-and-cast table (2.2) misses some sites and
2933+miscounts others.** The table sums to 55. There are 62 distinct lines
2934+with an `ADR` or a cast.
2935+
2936+- Grown arrays: 31 lines are `grab`/`regrab`/`free` of arrays. 3 more
2937+ are single records, `^Buf.Buf(Scan.grab(SIZE(Buf.Buf)))`, which
2938+ should be `NEW`, not `Vec`.
2939+- "A real's bits" are 4 lines (Item 152, 165, 364; Scan 879). 3 more
2940+ are a value's bytes for data (`Gen.raz:293`, `Parse.raz:3186`,
2941+ `Parse.raz:3334`). They need `setData` and the copy to take a slice,
2942+ besides the view.
2943+- `intern`: 7, correct. Two `Elf.putBytes(ADR(s[0]), LEN(s))` are
2944+ missing.
2945+- Out-parameters: 4 lines, 8 `ADR`s, not 5.
2946+- Not listed at all:
2947+ - `ADR(chunks[n])`, `ADR(files[i])` ×2 and `ADR(ao[an])`;
2948+ - `Scan.raz:119` (`return ADR(sbuf[0])`, the allocator);
2949+ - `Item.raz:2155` (`^I64(p)`);
2950+ - `Raz.raz`'s two `SYSCALL`s (`memfd_create`, and `execve` with
2951+ `ARGV() + first`).
2952+
2953+ The `SYSCALL`s mend by `Sys.memFile`, and `Sys.execve` with
2954+ `Sys.envAt`, but they are not "1 SYSCALL".
2955+
2956+### 2. The five programs
2957+
2958+Each was extracted from appendix 3 and compiled with
2959+`/home/user/raz/raz -Werror`. Each is identical to `S/demo/`.
2960+
2961+| program | printed | status |
2962+|---|---|---|
2963+| SelfAppend | 24 `a` | 0 |
2964+| Stale | `1 2` | 0 |
2965+| Escape | `########` | 0 |
2966+| Kept | `name-001: missing`, `name-002: missing` | 0 |
2967+| Temp | `name-..b`, a space, then `01 00 00 00 00 00 00 00` | 0 |
2968+
2969+All as claimed.
2970+
2971+**2.1 SelfAppend's explanation (1.2) is vague where it could be
2972+exact.**
2973+
2974+- `Buf.room` copies, then frees the old block (`Buf.raz:36-37`).
2975+ `Buf.str` then copies from `s`.
2976+- The old block is size class 3 and the new one class 4. `Heap.free`
2977+ writes only the 16-byte header (`b := ^Block(h)`, `Heap.raz:96`).
2978+ Nothing allocates between the free and the copy.
2979+- So with `Heap` in one thread the program is always right. That is
2980+ not luck "in time".
2981+- A block past 4,080 bytes gets pages of its own, and `free` unmaps
2982+ them. Filled to 8,192 bytes, the same line stops the program:
2983+ `Buf.raz:67:5: stopped by a bad address` (`W/demo/SelfBig.raz`).
2984+ That makes a stronger demonstration than the one shown.
2985+
2986+**2.2 Stale.** Holds as explained:
2987+
2988+- The class-4 block of 16 elements is freed when the `Vec` grows to 32.
2989+- `p` points into the class-5 block, which is freed at the next growth.
2990+- `free` touches only headers, so `first[0]` and `first[1]` read 1
2991+ and 2.
2992+
2993+**2.3 Escape** holds.
2994+
2995+**2.4 Temp.** The listing (`raz -S`) confirms one slot,
2996+`[rbp - 40]`, for both calls.
2997+
2998+- `a` was printed before anything overwrote the slot, so it shows
2999+ `b`'s bytes.
3000+- `b` points at the same slot. That slot was overwritten by the next
3001+ call's argument, `Out.str(" ")`, whose length 1 lands at
3002+ `[rbp - 40]`. Hence `01 00 ...`.
3003+- "Whatever came after" is right. The precise cause is the next
3004+ statement's temporaries.
3005+
3006+**2.5 "Three are what the library's own documentation warns of" (1.2)
3007+is two.** `Buf` ("until it next grows") and `Vec` warn. `Map`'s
3008+documentation says nothing about keeping its keys: neither the module
3009+comment nor `put`'s "k now maps to v". The proposal itself says the
3010+caller "must know, from the documentation alone". **Correction:** "two
3011+are what the library's documentation warns of, one what it doesn't
3012+say, and two what 7.3 and 8 warn of." Or mend `Map`'s comment.
3013+
3014+### 3. Benchmarks
3015+
3016+The machine is a 4-core Xeon VM at 2.1 GHz, with AVX-512. `lscpu`
3017+reports L2 2 MiB a core and **L3 260 MiB**. THP is `madvise`.
3018+
3019+**3.1 Two runs each of MemBench and GenBench (ms):**
3020+
3021+| kernel | proposal | mine, run 1 | mine, run 2 |
3022+|---|---|---|---|
3023+| big, raw, 16-byte nodes | 8,312 / 7,515 | 5,300 | 4,859 |
3024+| big, handles, 32-byte slots | 12,336 / 11,992 | 10,665 | 10,429 |
3025+| small, raw | 857 / 810 | 864 | 876 |
3026+| small, handles | 1,631 / 1,643 | 1,829 | 1,734 |
3027+| big, raw, 32-byte nodes | 14,001 / 13,725 | 13,734 | 13,499 |
3028+| big, fat pointers | 8,672 / 10,145 | 9,232 | 10,624 |
3029+| small, raw, 32-byte | 870 / 917 | 852 | 870 |
3030+| small, fat | 830 / 1,047 | 815 | 888 |
3031+| sum, big, `^U8` / `[]U8` | 305 / 342; 271 / 434 | 296 / 279 | 318 / 370 |
3032+| sum, small, `^U8` / `[]U8` | 261 / 265; 256 / 306 | 336 / 428 | 387 / 392 |
3033+
3034+Findings:
3035+
3036+- **Big handles cost 2.0 to 2.2 times here, not 1.5 to 1.6.** The raw
3037+ baseline varies by 40% between sessions.
3038+- **The working sets are not "past the caches".** The big arrays are
3039+ 16 MB and 32 MB, inside a reported 260 MB L3. So "doesn't fit in
3040+ the caches" and `Big = 1000000; (* past the caches *)` are wrong
3041+ here. What grows with the node is the page-walk footprint and the
3042+ share of L3, not a miss to DRAM.
3043+- **"Half of it the larger slot" is not supported.** Across the two
3044+ programs, the 32-byte raw chase (13.5 s) is *slower* than the
3045+ 32-byte handle chase (10.5 s). The two programs aren't comparable.
3046+
3047+**3.2 Why big-gen beats big-ptr.** I tested three explanations:
3048+
3049+- Run order (`W/mb/GenOrder.raz`): not it. Gen first or second, gen
3050+ 11.4 to 11.6 s, ptr 13.4 s.
3051+- Array placement in bss (`W/mb/GenSwap.raz`): not it. Ptr stays
3052+ slower.
3053+- Layout and code (`W/mb/GenWhy.raz`, 50M steps):
3054+ - ptr 6.8 s;
3055+ - gen 3.8 to 4.5 s;
3056+ - gen with no check 2.7 to 3.9 s;
3057+ - a raw pointer chase over the *gnodes* array 4.2 to 5.8 s.
3058+
3059+ In `W/mb/Offs.raz`, the same 32-byte node chased raw takes 6.3 to
3060+ 6.5 s with the link at offset 0, and 5.3 to 5.9 s with it at offset
3061+ 8.
3062+
3063+So part of the gap is the node's layout (where the link and the value
3064+sit), and the rest is noise of ±20 to 30% on this VM. The generation
3065+check itself isn't what the rows measure. Its cost is within noise;
3066+calling it "free" or "the check is free here" goes further than the
3067+data. The same layout effect sits inside the "+70–85%" for doubling a
3068+node: the comparison is across two programs with different layouts.
3069+**Correction:** "On this machine, wider records and handles cost 1.5 to
3070+2.2 times in a pointer chase; the measurements can't separate the
3071+check from layout and noise." Keep the conclusion against fat
3072+pointers on other grounds: C interop, record size.
3073+
3074+**3.3 MemBench understates a real `Pool`.** `chaseHandle` indexes a
3075+fixed module array inline: no call, no copy of `T`, no heap
3076+indirection, no `LENDS` count. `Pool.get` (8.2) is a call that copies
3077+`T`, through a `const p: Pool`, into a heap block. `Pool.at` adds a
3078+counted lend. Expect more than the table's figure.
3079+
3080+**3.4 The bounds-check sums** do test the check: the listing shows
3081+`cmp r12, rsi; jae` in the loop. My figures run from -6% to +27%.
3082+"0–15%" is about right, given the noise.
3083+
3084+**3.5 The scanner experiment** repeats: `valgrind --tool=callgrind`
3085+of `S/base/raz` and `S/safe/raz` over `src/Raz.raz` gives 240,850,230
3086+and 251,594,863 instructions, +4.46%.
3087+
3088+Caveats:
3089+
3090+- The "safe" `Scan` still uses `PTR(cur.buf)` and
3091+ `intern(PTR(buf) + start, ...)`, so it isn't safe. The cost of
3092+ `intern(s)` taking a slice isn't measured.
3093+- `PTR` is not in v0.19.0, so this `Scan` can't be built by `BOOT`
3094+ yet.
3095+- Wall-clock times of the 348,025-line bench were 688 to 891 ms for
3096+ the base compiler and 723 to 858 ms for the "safe" one, interleaved
3097+ six times. The "safe" one was sometimes faster. Wall clock can't
3098+ show 5% here.
3099+- The proposal's "625 to 660 ms" was a quiet moment. At this
3100+ session's best (688 ms, 506,000 lines a second) 5% more is about
3101+ 480,000, still above the floor. On a slow run (891 ms, 390,000) the
3102+ floor already fails today.
3103+
3104+**3.6 "Two 8-byte moves become one 16-byte one" (13.3)** is true only
3105+from memory to memory. Into the rax/rdx pair the ABI returns a slice
3106+in, or from it, a `movdqa` needs `movq` and `pextrq`/`pinsrq`. That is
3107+three instructions and a domain crossing, not none.
3108+
3109+### 4. Library signatures, report sections, quotations
3110+
3111+- **Exact:**
3112+ - `Thread.spawn*(p: proc(arg: ^U8); arg: ^U8): (^Thread, ERROR)`;
3113+ - `Str.copy*(a: ^Mem.Allocator; s: []U8): ([]U8, BOOL)`;
3114+ - `Buf.spare*(var b: Buf; n: INT): []U8`;
3115+ - `Buf.bytes*(const b: Buf): []U8`;
3116+ - `Map.put*(var m: Map; k: K; v: V): BOOL`;
3117+ - `Sys.mmap`, `Sys.munmap`, `Sys.nextEntry(var d: Dir)`,
3118+ `Sys.read(fd: INT; buf: []U8): INT`;
3119+ - `Item.raz:58` is `frame*: BOOL` with the comment the proposal
3120+ describes;
3121+ - `C` has 96 `extern`s and `CAbi` 2; `Vec` has 11 fenced lines;
3122+ - `src/` is about 11,550 lines of code by a comment-stripping count
3123+ (rloc isn't installed), so "about 11,500" holds.
3124+- **`Vec.all`'s comment** is "The elements, until the array next
3125+ grows." "Good until the array next grows" is in `Vec`'s module
3126+ comment and in `add`'s (capitalized). The quote is fair, but not
3127+ `all`'s own words.
3128+- **7.6 is misquoted (9.1).** The report says a variable raced on
3129+ "holds no particular value then: a read of it gives a value it had
3130+ or was given, or a mixture of their bytes. Nothing else of the
3131+ program becomes undefined by it." The proposal puts "holds" in
3132+ front of "a value it had or was given", which the report doesn't
3133+ say. **Correction:** quote "a read of it gives a value it had or was
3134+ given, or a mixture of their bytes".
3135+- **Section 10's "no run time besides the code it uses" (19)** is said
3136+ of "a program that doesn't [use C]". The quote is exact. It is a
3137+ property of programs without C, not a promise of the language. That
3138+ weakens the argument a little; line 7 of the report ("no hidden run
3139+ time") supports it better.
3140+- **5.3 (16):** a slice's alignment is set in 5.1 ("a slice is aligned
3141+ as an address is"), not 5.3. The sentence to change is there.
3142+- **Elf "writes the executable through `Sys.write`" (5.4):** it uses
3143+ `Files.write(path, buf[0..len])` (`Elf.raz:442`). The conclusion
3144+ holds.
3145+- **Zig in 12:** `@intToPtr` has been `@ptrFromInt` since Zig 0.11.
3146+- **The Go memory-model wording** in 9.1, "arbitrary memory
3147+ corruption", is accurate.
3148+- **Section 15's `ret` list** leaves out `Vec.tryAdd`, which 17 marks.
3149+ **Neither list marks `init`'s allocator `keep`** on `Buf`, `Vec`,
3150+ `Map`, `List` or `Pool`. Every one stores `a` in its record, and
3151+ 5.3(3) says "what it doesn't mark keep, it doesn't hold past the
3152+ call". See 5.5 below.
3153+
3154+### 5. Code samples and the proposal's own rules
3155+
3156+**5.1 Today's-raz samples compile.**
3157+
3158+- Appendix 2 and 3 compile.
3159+- 6.4's `greet`, `first` (without `ret`) and `remember` compile.
3160+- 7.1's loop compiles (`W/demo/Samples.raz`).
3161+
3162+**5.2 The help in 6.4 and 14.3 doesn't compile.** "give put a copy
3163+that lasts: `Str.copy(Heap.heap, buf[0..8])`". `Str.copy` has two
3164+results:
3165+
3166+```
3167+Samples.raz:31:27: error: copy returns several results
3168+ help: they go to variables: a, b := copy(...)
3169+```
3170+
3171+**Correction:** "copy it first: `k, ok := Str.copy(Heap.heap,
3172+buf[0..8])`".
3173+
3174+**5.3 The message positions are off.** The positions shown don't match
3175+the programs:
3176+
3177+- `Kept.raz:10:30`: the call is at line 11, column 27.
3178+- `Escape.raz:14:12`: it is at 15:12.
3179+- `Window.raz:41:13 ... XNextEvent(dpy, ADR(ev))`: the line in
3180+ `examples/Window.raz` is 59, `_ := XNextEvent(d, ^U8(ADR(ev)))`.
3181+
3182+Window's help, "or pass ev as a var", is impossible. An `extern`'s
3183+parameters are integers, `BOOL`, reals, pointers or procedures (report
3184+9), and the module is unsafe for its `extern`s anyway. Pick a safe
3185+module's `ADR` for that example.
3186+
3187+**5.4 The Escape message assumes a `head` that 6.2 forbids.** It says
3188+"head's result points into what it is given (ret h)". Appendix 3's
3189+`head(var h: Hex)` has no `ret`, so under 6.2 the first error is in
3190+`head` itself: "returning what is lent by h, not marked ret".
3191+
3192+**5.5 7.3 forbids what 14.2 recommends.** 7.3 says an owner-lent
3193+reference "returned ... is an error". 14.2's option 1 is `proc
3194+name*(ret const m: Message; i: INT): []U8; (* m^.head's bytes, lent by
3195+m *)`, which returns bytes of `m.head`, a `Buf`. That is exactly an
3196+owner-lent return. 7.2 also says a `Message` is not an owner, so it
3197+can't lend through `ret` at all.
3198+
3199+The same rule refuses `tools/Widths.raz`'s `load(path; var b:
3200+Buf.Buf): []U8 ... return Buf.bytes(b)`, yet section 15 says `tools/`
3201+has "none found". It also refuses any safe wrapper over `Vec.all` or
3202+`Pool.at`.
3203+
3204+Either 7.3 allows returning through a `ret` parameter that is itself
3205+an owner, or the library's own exports, which do this, need a
3206+different rule from safe code. If returning is allowed, the hold must
3207+pass to the caller, and 7.3 doesn't say how.
3208+
3209+**5.6 Part C stops correct programs, the library's and the compiler's
3210+included.** 7.3 lets a local's hold go only when the procedure
3211+returns, and 7.4 makes `done` stop while a count is above zero. A scan
3212+for a slice held from `Buf.bytes(b)` and a later `Buf.done(b)` in one
3213+procedure (`W/py/heldone.py`) finds:
3214+
3215+- `lib/Opt.raz` `say`: `s := Buf.bytes(b)`, loop, `Buf.done(b)`;
3216+- `src/Parse.raz` `moduleParams`, lines 3696 to 3699 (every generic
3217+ instance);
3218+- ravite's `load` (`Ravite.raz:1402`, done at 1411).
3219+
3220+Five more do `defer Buf.done(x)` and then hold `Buf.bytes(x)`:
3221+`examples/Elf.raz` `main`, rnet `Dns.init` and `fromHosts`, and rmacs
3222+`writeFile` and `loadInit`. Whether those stop depends on whether a
3223+hold's let-go runs before or after the deferred statements. The
3224+proposal says only "as a defer would".
3225+
3226+So the compiler itself would stop on every program with a generic
3227+import. 14.2 calls this "a false alarm only when name is never read
3228+again", and these are exactly such cases. Section 15's claim that
3229+every break is found when compiling, but `done`, should count them.
3230+**Correction:** let a hold go at the variable's last use, or at a
3231+`done` of the owner from the same procedure (both known in one pass
3232+only for straight-line code). Or count these breaks and mend them with
3233+`s := []`.
3234+
3235+**5.7 A `Buf` or `Vec` over an `Arena` has no safe form.** By 8.4,
3236+`Arena.allocator(ar)` is lent by `ar`, and a lent value can't be
3237+stored in a record (6.2) or given to `keep` (5.5 above). `Buf.init`
3238+keeps its allocator, so `Buf.init(b, Arena.allocator(ar))` is an
3239+error. This pattern appears in:
3240+
3241+- `Fmt.eprint`;
3242+- `Fmt`'s test;
3243+- `Buf`'s test;
3244+- `examples/Sh.raz`, lines 88 and 188.
3245+
3246+So "Fmt ... can be safe" (5.4, 15, 17) and "Sh ... mended by var" (5.4,
3247+15) fail. `Fmt.format` also takes `^Buf.Buf` with `nil` for standard
3248+output, which needs an interface change.
3249+
3250+**5.8 Other "can be safe" claims (5.4).**
3251+
3252+- `Files.arg` *is* `ARGV()[i]` and pointer indexing
3253+ (`Files.raz:10-13`). 5.1 fences `ARGV` and names `Files.arg` as the
3254+ safe form, so `Files` must stay unsafe, or `ARGV` must move into a
3255+ trusted module.
3256+- `Str.copy` and `Str.free` index and free a `Mem.alloc` pointer. `Str`
3257+ can be safe only if `Mem` gains a safe slice allocation. Section 17
3258+ doesn't add one, and `free` is an `unsafe proc` in a module 17 calls
3259+ safe.
3260+- `Lock` needs E.4 (`CAS` on a variable) first.
3261+- `examples/Workers.raz` uses `Thread.spawn(work, nil)` and
3262+ `XADD(ADR(next), 1)`. It needs `Task` and E.4, not `var`.
3263+
3264+**5.9 Owners can't sit in generic containers.** 7.6 forbids passing an
3265+owner as a value parameter or copying it. `Vec.push(x: T)`,
3266+`Pool.add(keep x: T)`, `Map.put(..., v: V)` and `List.push` all copy.
3267+So `Vec(Buf.Buf)`, `Pool(Window)` where a `Window` holds a `Buf`, and
3268+`Names(Buf.Buf)` can't be used. Yet 14.2 turns rmacs's windows, which
3269+hold `Buf`s, into a `Pool(Window)`. The proposal needs an `add` that
3270+gives a zero slot in place (`Pool.at` after a zero `add`) and says
3271+that copies are refused there.
3272+
3273+### 6. The compiler's cost (section 18)
3274+
3275+- **A, 120:** about right, perhaps to 150. It needs `unsafe proc`'s
3276+ rules in `Sym.same` and assignability, the two contextual places the
3277+ word stands, the interface check, and a generic instance taking its
3278+ module's mark.
3279+- **B, 300–450: low.** PROPOSALS' own second review (its open
3280+ question 4, PROPOSALS.md line 476) revised part 3 to "400 to 600
3281+ lines, not 250 to 400", for slices alone. This proposal adds
3282+ pointers, owners as lenders, `match` names (10.4), literal parts and
3283+ generic instances checked one by one. Likely 550 to 800.
3284+- **C, 200: low.**
3285+ - Hidden hold slots per local.
3286+ - A raise at each call that returns an owner-lent value.
3287+ - A lower at the end of each statement. Only `const`'s temporaries
3288+ have such a point today.
3289+ - A let-go on every exit, `try` and early `return` included, with
3290+ an order against `defer` (5.6).
3291+ - The copy check at assignment, value parameters, results, literals,
3292+ comparison, views and generic instances (5.9).
3293+ - Likely 300 to 450.
3294+- **D, 20:** plausible.
3295+- **E, 80: low.**
3296+ - 16-byte alignment of slices changes record layout in `Sym`, and
3297+ frame-slot and temporary alignment in `Gen`.
3298+ - Every slice load and store goes through xmm, with
3299+ `movq`/`pinsrq`/`pextrq` for the rax/rdx pair. `X64` today
3300+ encodes `movdqu` but not those.
3301+ - Records holding slices are copied by `rep movsb` past `MaxMoves`.
3302+ - `CAS`, `XCHG` and `XADD` change from pointer to variable in
3303+ `Parse` and `Item`.
3304+ - `lock xadd` when `Thread` is imported.
3305+ - Likely 150 to 250.
3306+- **F, 20:** plausible, since `defer`'s reserved slots exist.
3307+- **Messages, 100:** plausible for about 10 new kinds with help.
3308+
3309+**In all, likely 1,250 to 1,700, not 840 to 990.** That still fits
3310+under 14,000, from about 11,550, but with much less room than 18
3311+suggests for the documentation the house style requires.
3312+
3313+The `src/` rewrite is also larger than "35 grown arrays". `Chunk.chunks`,
3314+`Chunk.text` and `Chunk.rodata` are exported and indexed from `Item`,
3315+`Parse`, `Gen`, `Raz`, `Elf`, `Link` and `X64`: about 250 lines of
3316+`p[i]` and `p[a..b]` outside `Scan`. Each would become a `Vec.all(...)`
3317+with a counted lend, often in `X64`'s emitter and `Link`'s patching,
3318+which are hot. 13.1's "cost nothing measurable" for these is
3319+unmeasured.
3320+
3321+### 7. `src/` becoming safe (2.2, 5.4, 15)
3322+
3323+The plan is plausible module by module, with three gaps:
3324+
3325+- **Elf:** its buffers are a `grab`/`regrab` byte array (a `Buf`), plus
3326+ `putBytes(ADR(s[0]), LEN(s))` (a slice parameter) and
3327+ `sizeTables(ADR, ADR)` (`var`). It can be safe.
3328+- **Diag:** `files` is a grown array (`Vec`), and two `^Buf.Buf(grab)`
3329+ become `NEW`. `File.buf: ^U8` keeps a pointer to the scanner's
3330+ source. As a slice it is lasting only if `Scan`, unsafe, promises
3331+ so. It can be safe.
3332+- **Link:** four arrays sized once from `Scan.grab`, then `p[i]` 63
3333+ times. They need `Vec(INT)` with `resize`, or a typed `grab` that
3334+ gives a slice. Safe, at the cost of checks on the linker's paths.
3335+- **Chunk:** grown record arrays exported to every module, and
3336+ `ADR(chunks[n])`. Safe as `Vec`s, but see 6 on cost and lines.
3337+- **X64:** `said` is grown, `^Buf.Buf(grab)` becomes `NEW`, and the
3338+ `isReg` out-parameters and `operand(ADR(ao[an]))` become `var`. It
3339+ writes `Chunk.text` per byte. Safe, with that cost.
3340+- **Gaps:**
3341+ - `Raz.raz` needs its `SYSCALL`s and `ARGV() + first` replaced:
3342+ `Sys.memFile`, and `Sys.execve` with an environment built from
3343+ `Sys.envAt`.
3344+ - `Scan.grab`'s callers outside `Scan` (`Item.raz:2154`,
3345+ `Parse.raz:452`, `Parse.raz:3812`, `Raz.raz:165`) index its
3346+ `^U8`. `grab` must give a slice.
3347+ - `Parse.moduleParams` stops at run time under part C (5.6).
3348+
3349+"`src/` keeps one unsafe module: Scan" can be reached, but it is
3350+several hundred changed lines, not the table's 55 sites.
3351+
3352+### Confirmed
3353+
3354+- The demos' outputs and status 0, and that each does the undefined
3355+ thing claimed.
3356+- The callgrind counts, +4.5%.
3357+- Appendix 1's per-module tallies, as the aggregator gives them, read
3358+ as lines.
3359+- The hand-free counts.
3360+- rmacs's 560 and 556, and ravite's 202, `ADR`s.
3361+- About 36 held `Buf.bytes`/`Windows.all` slices.
3362+- `tools/` has no fenced operation.
3363+- Threads in rnet (`Http`'s server, tests) and rsqlite (`Sqlite`'s
3364+ test) only.
3365+- Lines per repository, about 50,000.
3366+- `src/`'s 7 frees all in grown arrays.
3367+- The cited signatures, and `Item.raz:58`.
3368+- 7.3's and 8's text on what isn't caught.
3369+- `C` 96 and `CAbi` 2 `extern`s.
3370+- The sums' bounds check really emitted.
3371+- `src/` about 11,500 lines of code.
3372+
3373+---
3374+
3375+## Appendix 7: adversarial review, porting real code
3376+
3377+Section 14 says most raz stays as it is and the pain is narrow. To
3378+test that, six pieces of real code were ported on paper under parts A
3379+to F, read as strictly as a compiler would read them: rnet's `Http`
3380+with its test servers, rmacs's buffers and windows, the compiler's
3381+name table, grown arrays, files and scopes, the library's `Fmt`, `Opt`,
3382+`Map` and the containers, `examples/Sh.raz`, and rjson's `Json`. About
3383+25,000 lines were read; about 900 of them change for parts B to F, 4%,
3384+on top of the `ADR`s the fence turns into `var`, which `STANDARDS.md`
3385+asks for anyway. By lines, then, the claim holds. By kind it doesn't.
3386+The changes gather in the one type each piece is built round
3387+(`Http.Message`, rmacs's `Text` and its accessors, `Chunk`'s arrays,
3388+`Sh`'s arena, `Json.Doc`), and each of those needs a redesign, not a
3389+mark. Three rules cause most of it: an owner's lend can't be returned
3390+by any procedure but the owner's own, can't sit in a record, and the
3391+fence has no safe form for a pointer to "the caller's state". The
3392+port also found six holes in the rules as written (A7.7): four let
3393+unsafe code through, and two leave a trap or an undecided stop. It
3394+found eight places in correct code that would stop at run time with
3395+`done` while held, and no real bug in today's code.
3396+Most of the pain goes away with seven additions that weaken nothing
3397+(A7.10).
3398+
3399+### A7.1 How it was done
3400+
3401+Each piece was first brought to today's library, so that an `ADR` at a
3402+call where the library now takes `var` doesn't count. Then each rule
3403+was applied to every line. Where the proposal is unclear, the stricter
3404+reading was taken, and noted:
3405+
3406+- **A pointer parameter is lent by its parameter** (6.1, 6.5). Storing
3407+ one in a module variable or a record needs `keep`.
3408+- **Reading through a pointer gives a lasting value.** Only lasting
3409+ values may be stored through a pointer (6.2), so what is read back
3410+ is lasting too. The more lenient reading is taken here.
3411+- **An owner's lend may be returned only through a `ret` parameter
3412+ that is the owner itself**, as `Buf.bytes` does. 7.3 says that
3413+ returning one is an error. 6.2 allows it through `ret`. The middle
3414+ reading is the only one under which the caller still knows whose
3415+ count to raise.
3416+- **A local array or record may not hold an owner's lend** (7.3), not
3417+ even one of slices.
3418+
3419+"Changed" counts lines touched, written or removed, against the
3420+source as it stands. The counts come from reading and `grep`, not from
3421+a compiler, and are good to about a fifth.
3422+
3423+### A7.2 rnet's `Http` (`src/Http.raz`, `src/Conn.raz`, `test/Webserver.raz`, `test/Server.raz`, `examples/Hello.raz`)
3424+
3425+**What the rules reject.**
3426+
3427+| Line or construct | Rule | The compiler's error |
3428+|---|---|---|
3429+| `m^.headers[m^.n] := {name: l[0..colon], value: trim(...)}` (`parseHeaders`), `l` a slice of `Buf.bytes(m^.head)` | 6.2, 7.3 | `Buf.bytes(m^.head) is lent by m^.head, which counts what it lends: hold it in a slice variable` |
3430+| `m^.raw := text`, `m^.method := l[0..i]`, `m^.target := ...`, `m^.reason := ...` | 7.3 | the same |
3431+| `m^.body := Buf.bytes(ADR(m^.data))` (`readWhole`) | 7.3 | the same |
3432+| `res^.body := Buf.bytes(ADR(text))` (Webserver, twice) | 7.3 | the same, in the program that uses `Http` |
3433+| `Http.add(res, "Location", Buf.bytes(ADR(text)))` (Webserver, twice), `add(ADR(res), "Date", Buf.bytes(ADR(when)))` (`serveConn`) | 6.2: `add` stores `name` and `value`, so it is `keep` | `Http.add keeps its value, and Buf.bytes(text) is lent by text` |
3434+| `head := m^.head; ... m^ := {..., head: head, data: data}` (`reset`) | 7.6 | `a Buf.Buf owns memory, and can't be copied` |
3435+| `out := req^` (`open`): a `Message` with two `Buf`s, copied | 7.6 | the same |
3436+| `try parseUrl(Buf.bytes(ADR(here)), ADR(u))`: `parseUrl` keeps slices of `s` in `u^` | 6.2 | `parseUrl keeps s, and Buf.bytes(here) is lent by here` |
3437+| `cl^.scheme := u^.scheme` (`connect`), always `"http"` or `"https"` | 6.2: `u`'s parts are lent as `u` is | `u.scheme is lent by u, a parameter not marked keep` |
3438+| `r^ := {conn: c, ...}` (`startBody`), `c` an `ADR` of a local `Conn` or of `cl^.conn` | 5.1, then 6.2 | `ADR is for unsafe modules`; with `var c`, `c is a var parameter and can't be kept` |
3439+| `return ADR(cl^.body), nil` (`open`) | 5.1 | `ADR is for unsafe modules` |
3440+| `Thread.spawn(work, ^U8(s))`, `s := ^Server(arg)` | 5.1, 5.2 | `a conversion to a pointer is for unsafe modules`; `Thread.spawn is an unsafe procedure` |
3441+| `Handler = proc(req, res: ^Message; arg: ^U8)`: a safe handler can't turn `arg` back into its own type | 5.1 | the same, in every program with state |
3442+| `t := ^Text(c^.state)` (`Http`'s and `Conn`'s tests); `Conn.state: ^U8` | 5.1 | the same |
3443+| `proc trim(s: []U8): []U8` returns `s` | 6.2 | `trim's result is lent by s, which isn't marked ret` |
3444+| every `^Message`, `^Conn.Conn`, `^Reader`, `^Url`, `^Client`, `^Server` parameter given `ADR(local)`: 228 `ADR`s in `Http.raz`, 37 in `Conn.raz` | 5.1 | `ADR is for unsafe modules` |
3445+
3446+The last row is what `STANDARDS.md` asks for, `var` or `const`. It
3447+changes `Http`'s whole interface, and every program that calls it.
3448+It is counted apart below.
3449+
3450+Section 14.2 offers a way out: `Http` says `unsafe;` and keeps
3451+`Message` as it is. That breaks the proposal's own rule 4 of 5.3. A
3452+safe program can read `req^.body` after `Http.done(req)`, so the
3453+exported slice fields are just what a safe module could misuse. And
3454+the programs that *write* messages (Webserver, `Hello`) are safe
3455+modules: they still can't store a `Buf`'s bytes in `res^.body`. So the
3456+spans are the only design that compiles.
3457+
3458+**Rewritten.** The text a message holds goes in its own buffers, as
3459+spans. Everything a program gives it is copied in.
3460+
3461+```
3462+(* Before *)
3463+Header* = record
3464+ name*, value*: []U8;
3465+end;
3466+Message* = record
3467+ method*, target*: []U8;
3468+ status*: INT;
3469+ reason*: []U8;
3470+ minor*: INT;
3471+ headers*: [MaxHeaders]Header;
3472+ n*: INT;
3473+ body*: []U8;
3474+ maxBody*: INT;
3475+ close*: BOOL;
3476+ raw*: []U8;
3477+ head, data: Buf.Buf;
3478+end;
3479+
3480+(* After *)
3481+Span = record at, len: INT; end; (* bytes at up to at + len of one of the buffers *)
3482+Header = record name, value: Span; end; (* in head *)
3483+Message* = record
3484+ status*, minor*, n*, maxBody*: INT;
3485+ close*: BOOL;
3486+ method, target, reason, raw: Span; (* in head *)
3487+ headers: [MaxHeaders]Header;
3488+ body: Span; (* in data *)
3489+ head, data: Buf.Buf; (* all of its text, read or to be written *)
3490+end;
3491+
3492+(* s added to b, and where it stands there *)
3493+proc put(var b: Buf.Buf; s: []U8): Span;
3494+begin
3495+ Buf.str(b, s);
3496+ return {at: b.len - LEN(s), len: LEN(s)};
3497+end;
3498+
3499+proc add*(var m: Message; name, value: []U8): ERROR;
3500+begin
3501+ if m.n = MaxHeaders then return TooManyHeaders; end;
3502+ m.headers[m.n] := {name: put(m.head, name), value: put(m.head, value)};
3503+ INC(m.n);
3504+ return nil;
3505+end;
3506+
3507+proc setBody*(var m: Message; s: []U8); (* new: s copied into the message *)
3508+begin
3509+ Buf.reset(m.data);
3510+ m.body := put(m.data, s);
3511+end;
3512+
3513+(* The bytes of sp in b *)
3514+proc bytesOf(ret const b: Buf.Buf; sp: Span): []U8;
3515+begin
3516+ return Buf.bytes(b)[sp.at..sp.at + sp.len]; (* fine: b is the owner, and ret *)
3517+end;
3518+
3519+proc target*(ret const m: Message): []U8;
3520+begin
3521+ return bytesOf(m.head, m.target); (* refused as written: lent by m.head, a part of m; see A7.7, H2 *)
3522+end;
3523+```
3524+
3525+`target`, `method`, `reason`, `raw`, `body`, `header`, `name(i)` and
3526+`value(i)` are new accessors, and the setters `setMethod`,
3527+`setTarget`, `setReason` and `setBody` are new too. They need the
3528+relaxation R1 of A7.10 to compile at all. In the programs:
3529+
3530+```
3531+(* Before (Webserver) *)
3532+path := req^.target;
3533+Fmt.write(ADR(text), "{}", [Fmt.int(conns)]);
3534+res^.body := Buf.bytes(ADR(text));
3535+
3536+(* After *)
3537+path := Http.target(req); (* held, and counted on req's head *)
3538+Fmt.write(text, "{}", [Fmt.int(conns)]);
3539+Http.setBody(res, Buf.bytes(text)); (* copied *)
3540+```
3541+
3542+`reset` keeps its buffers by moving them out and back:
3543+
3544+```
3545+proc reset*(var m: Message);
3546+var head, data: Buf.Buf; max: INT;
3547+begin
3548+ Buf.take(m.head, head);
3549+ Buf.take(m.data, data);
3550+ max := m.maxBody;
3551+ m := {minor: 1, maxBody: max}; (* the owners left out: empty *)
3552+ Buf.take(head, m.head);
3553+ Buf.take(data, m.data);
3554+ Buf.reset(m.head);
3555+ Buf.reset(m.data);
3556+end;
3557+```
3558+
3559+`m := {minor: 1, maxBody: max}` alone also compiles. It drops both
3560+buffers' memory and their allocator, so the next `Buf.add` calls a
3561+`nil` allocator and stops (A7.7, H4).
3562+
3563+A `Reader` can't hold the `Conn` it reads from, since no safe pointer
3564+to a local `Conn`, or to `cl^.conn`, exists. Either the `Conn` comes
3565+from `NEW`, and a `Client`'s 16 KB buffer can never be freed (D), or
3566+the reader takes the connection on each call:
3567+
3568+```
3569+proc read*(var r: Reader; var c: Conn.Conn; b: []U8): (INT, ERROR);
3570+proc readBody*(var cl: Client; b: []U8): (INT, ERROR); (* open no longer returns ^Reader *)
3571+```
3572+
3573+`parseUrl` fills a local `Url` with slices of a `Buf`, and the `Url`
3574+dies before the `Buf` does. That is PROPOSALS' false alarm of "a record
3575+that lives in the frame". Returning the `Url` as a result doesn't help,
3576+since a local record may not hold a lend (7.3). The cure that compiles
3577+copies the URL into a frame array, whose slices a local record *may*
3578+hold:
3579+
3580+```
3581+var here: [MaxUrl]U8; hereLen: INT; u: Url;
3582+...
3583+try parseUrl(here[0..hereLen], u); (* frame-lent: allowed in the local u; parseUrl's s is keep *)
3584+```
3585+
3586+So a URL gets a fixed limit only to get past the rule. `cl^.scheme :=
3587+u.scheme` becomes `cl.tls := u.scheme = "https"`. The server's threads
3588+become `Task(^Server)`, `Hello` makes its `Server` with `NEW`, and
3589+`arg: ^U8` goes from `Handler`. A server with state keeps it in module
3590+variables, shared by its workers with no lock unless it uses
3591+`Lock.Guarded`. The tests that cast `Conn.state` go into an unsafe
3592+module of their own.
3593+
3594+**Count.** About 2,700 lines, tests included. The fence alone
3595+(`ADR` to `Http`'s own pointer parameters, casts): about 330 lines.
3596+Parts B to F: `Message` and its accessors and setters about 120, the
3597+readers and writers that use them about 40, `reset` and `open`'s copy
3598+15, `Url` 15, `Reader` and `Client` 20, threads and the handler 10,
3599+Webserver 8, `Server` 16, `Hello` 3. About 230 lines in all, 9%.
3600+
3601+**Judgement: worse.** Every field is now a call. Each header and each
3602+body a handler makes is copied once more, and a 100,000-byte body made
3603+in a `Buf` is copied whole. Fixed limits come in only to dodge a rule
3604+(`MaxUrl`), and handlers lose their context. In return, "good until the
3605+message is read again or reset", which `Http`'s header comment asks a
3606+reader to remember, is now checked.
3607+
3608+**Contortions and false alarms:** `parseUrl` into a frame array; the
3609+scheme as a BOOL; `Reader` without its `Conn`; the accessors, which
3610+don't compile without R1. **Run-time stops in correct code:** none
3611+found. **Real bugs caught:** none. `reset`'s copy of the `Buf`s, which
3612+section 7.6 calls "safe by luck", is right: the copies are put back at
3613+once. `res^.body := req^.body` in `test/Server.raz` is right by the
3614+order `serveConn` keeps.
3615+
3616+### A7.3 rmacs (`src/Core.raz`, `Commands.raz`, `Text.raz`, `Mini.raz`, `Dired.raz`, `Windows.raz`)
3617+
3618+**What the rules reject.**
3619+
3620+| Line or construct | Rule | The compiler's error |
3621+|---|---|---|
3622+| `Text`: `data: ^U8`, `Mem.alloc`, `Mem.free`, `t^.data[i]`, `^U8(t^.changes)` | 5.1, 5.2 | `Mem.free is an unsafe procedure`, `indexing a pointer is for unsafe modules` |
3623+| `proc slice*(lo, hi: I64): []U8; ... return Text.slice(ADR(b^.t), lo, hi)` (`Core`), 12 callers | 7.3: returned, lent by the owner `b^.t`, which no parameter names | `Text.slice(b^.t, lo, hi) is lent by b^.t, which counts what it lends, and can't be returned` |
3624+| `proc text: []U8` (`Mini`), the same through `Core.mini^.t` | 7.3 | the same |
3625+| `proc nameAt(i: I64): []U8` (`Dired`), a slice of the module `Buf` `names` | 7.3 | the same |
3626+| `bufferNames(i)` returns `Buf.bytes(ADR(choices[i]^.name))`, as a `Mini.Names` procedure value | 7.3 | the same; and no mark on `Mini.Names` could allow it |
3627+| `Heap.heap^.free(Heap.heap, ^U8(x))` (`Core.kill`), four in `Windows` | 5.1, 5.2, D | `Heap's free is an unsafe procedure` |
3628+| `t := ADR(w^.buf^.t)` (`Rmacs.colours`) | 5.1 | `ADR is for unsafe modules` |
3629+| `DEC(out^.len)`, `DEC(line.len)`, `s.len := ...`, `t^.log.len := ...`: 7 writes of a `Buf`'s `len` | 5.3 rule 4 (see A7.7, H3) | nothing, as the proposal stands: a safe hole |
3630+| `selected := w`, `shown := x`, `Core.b := x`: a pointer parameter stored in a module variable (8 procedures) | 6.2, read strictly | `w is lent by the parameter w; mark it keep` |
3631+| 139 `ADR`s given to rmacs's own pointer parameters (`Text.len(ADR(b^.t))`, `Mini.read(..., ADR(answer))`) | 5.1 | `ADR is for unsafe modules` |
3632+
3633+**Rewritten.** No procedure but the owner's own can hand out what an
3634+owner lends, so `Core.slice` can't be written, and each of its twelve
3635+callers names the text itself:
3636+
3637+```
3638+(* Before *)
3639+Buf.str(ADR(Core.tmp), Core.slice(p, b));
3640+(* After *)
3641+Buf.str(Core.tmp, Text.slice(Core.b^.t, p, b));
3642+```
3643+
3644+A procedure value can't return a lend either, so `Mini.Names` changes
3645+to write the name into a buffer it is given:
3646+
3647+```
3648+(* Before *)
3649+Names* = proc(i: I64): ([]U8, BOOL);
3650+proc bufferNames(i: I64): ([]U8, BOOL);
3651+begin
3652+ if i >= numChoices then return "", false; end;
3653+ return Buf.bytes(ADR(choices[i]^.name)), true;
3654+end;
3655+
3656+(* After *)
3657+Names* = proc(i: I64; var name: Buf.Buf): BOOL; (* the i-th name, into name *)
3658+proc bufferNames(i: I64; var name: Buf.Buf): BOOL;
3659+begin
3660+ if i >= numChoices then return false; end;
3661+ Buf.reset(name);
3662+ Buf.str(name, Buf.bytes(choices[i]^.name));
3663+ return true;
3664+end;
3665+```
3666+
3667+`gather`'s loop and `commandNames` change to match: about 10 lines. A
3668+killed buffer and a closed window are not freed. Their contents are
3669+(`Text.done`, `Buf.done`), and the empty record, about 200 bytes, is
3670+kept to the end of the run:
3671+
3672+```
3673+Text.done(x^.t);
3674+Buf.done(x^.name);
3675+Buf.done(x^.path);
3676+(* x itself is kept, empty: part D lets no safe module free it *)
3677+```
3678+
3679+That is five lines taken out. The `Pool(Buffer)` that section 14.2
3680+offers would touch about 370 dereferences of `^Buffer` and `^Window`.
3681+`Pool` can't take a `Buffer` at all anyway: `add(var p; keep x: T)`
3682+passes `x` by value, and a `Buffer` holds owners (7.6). `Pool` would
3683+need an `alloc(var p): Handle` that hands out a zeroed slot.
3684+
3685+`Text` either says `unsafe;` and carries the owner's protocol by hand
3686+(a `LENDS` field, retiring in `room`, `ret` on `slice`: about 25
3687+lines), or is rebuilt on `Vec(U8)` and `Vec(Change)` (about 60 lines).
3688+Its gap moves under a slice that is held (`moveGap`), which the rules
3689+let pass, since it is memory-safe. That is right: today's comment,
3690+"good until the next change", stays a comment.
3691+
3692+**Count.** 4,931 lines. The fence alone: about 160 (the 139 `ADR`s,
3693+the casts, `Text`'s heading). Parts B to F: `Text` 25, the four
3694+accessors and their 20 callers 35, `Mini.Names` 10, `colours` 7, frees
3695+5, `len` writes 7: about 90, 2%.
3696+
3697+**Judgement: the same.** Twelve calls grow a little longer.
3698+`Mini.Names` copies each name once per keystroke of ido, about 256
3699+small copies, which doesn't show.
3700+
3701+**Run-time stops in correct code.** `writeFile` holds `p :=
3702+Buf.bytes(abs)` under `defer Buf.done(abs)`, and `loadInit` holds
3703+`s := Buf.bytes(b)` under `defer Buf.done(b)`. Section 7.3 lets a
3704+hold go "when the procedure returns", but doesn't say whether that is
3705+before or after its deferred statements. If after, `C-x C-w` stops
3706+the editor every time, and so does starting it with a `~/.rmacs`
3707+(A7.7, H5). **Real bugs caught:** none. No self-
3708+append or kill-while-held was found. `killBuffer` and `deleteWindow`
3709+take care with `Core.b` and `Core.selected` already.
3710+
3711+### A7.4 The compiler (`src/Scan.raz`, `Chunk.raz`, `Diag.raz`, `Sym.raz`, and their users)
3712+
3713+**Scan's name table: can be safe, and is clearer.** Today names are
3714+three hand-grown arrays and a table, all freed and copied by hand, and
3715+the bytes sit in 64 KB chunks that are never freed. Safe, the chunks
3716+come from `NEW` (lasting, so their slices last), and the arrays are
3717+`Vec`s:
3718+
3719+```
3720+var
3721+ chunk: ^[PoolChunk]U8; (* from NEW, never freed: its slices last *)
3722+ chunkUsed: INT;
3723+ names: Strs.Vec; (* import Strs := Vec([]U8) *)
3724+ hashes, table: Ints.Vec; (* import Ints := Vec(INT) *)
3725+
3726+proc intern*(s: []U8): INT; (* was intern(p: ^U8; n: INT), called with ADR(s[0]), LEN(s) *)
3727+var h, i, k: INT; t, hs: []INT; p: []U8;
3728+begin
3729+ h := hash(s);
3730+ t := Ints.all(table);
3731+ hs := Ints.all(hashes);
3732+ i := h & tableMask;
3733+ while t[i] # 0 do
3734+ k := t[i] - 1;
3735+ if (hs[k] = h) and (Strs.get(names, k) = s) then return k; end;
3736+ i := (i + 1) & tableMask;
3737+ end;
3738+ if (chunk = nil) or (LEN(s) > PoolChunk - chunkUsed) then NEW(chunk, Heap.heap); chunkUsed := 0; end;
3739+ p := chunk^[chunkUsed..chunkUsed + LEN(s)];
3740+ COPY(p, s);
3741+ INC(chunkUsed, LEN(s));
3742+ k := names.len;
3743+ Strs.push(names, p); (* keep: p lasts *)
3744+ Ints.push(hashes, h); (* may grow hashes: hs is retired, and not read again *)
3745+ t[i] := k + 1;
3746+ t := []; (* or grow's Ints.done(table) stops the program *)
3747+ hs := [];
3748+ if (k + 1) * 2 > tableMask then grow; end;
3749+ return k;
3750+end;
3751+```
3752+
3753+Two things here aren't in the proposal. `Strs.get` is new: `return
3754+Strs.all(names)[n]` is refused, since an element of an owner's lend is
3755+lent (6.1), though what it holds was stored by `keep` and lasts (A7.10,
3756+R4). And `t := []` before `grow` is needed only to get past `done`'s
3757+stop. Today's `intern` checks `n > chunkLeft` and then copies `n`
3758+bytes into a 64 KB chunk: a name longer than 65,536 bytes would
3759+overrun it. That can't happen, since `MaxStr` is 65,536 and `MaxIdent`
3760+is 63, so the bound holds only by the coincidence of two constants.
3761+The safe form checks it. About 40 lines change; the scanner's buffer
3762+stays unsafe, as section 21 suggests.
3763+
3764+**Chunk's grown arrays: can be safe, and grow longer.** `text`,
3765+`rodata`, `chunks`, `fixups`, `dataFixups`, `lines` and `varNotes`
3766+become `Buf`s and `Vec`s. `put1` becomes `Buf.add(text, U8(b & 0FFH))`,
3767+which is clearer. But there are about 200 places in `Link`, `X64`,
3768+`Elf`, `Gen`, `Parse` and `Item` that read `Chunk.chunks[c].adr` or
3769+`Chunk.lines[i].at`, and each one becomes either
3770+
3771+```
3772+Chunks.all(Chunk.chunks)[c].adr := a; (* a count raised and lowered, each time *)
3773+```
3774+
3775+or a local held over the procedure, `cs := Chunks.all(Chunk.chunks)`.
3776+The obvious mending, `proc at*(c: INT): ^Chunk` in `Chunk`, can't be
3777+written, since it returns a lend of an owner that no parameter names
3778+(7.3). And a held `cs` across a `newChunk` that grows the array is a
3779+new trap. The writes through `cs` go into the retired block and are
3780+lost, with no message, even in the debugging heap, which poisons
3781+retired blocks for reads only (11). Today that is a use after free.
3782+Under the proposal it is a wrong executable, and the proposal calls it
3783+"lost, but harmless" (7.4). For a compiler it is not harmless.
3784+
3785+**Diag's files and messages.** `files: ^File` becomes `Vec(File)`, and
3786+`pathOf` needs `Vec.get` (R4). `say` keeps every message for good, in
3787+a `Buf` from `grab` that is never freed:
3788+
3789+```
3790+(* Before *)
3791+b := ^Buf.Buf(grab(SIZE(Buf.Buf)));
3792+Buf.init(b^, Heap.heap);
3793+Fmt.write(b^, f, args);
3794+return Buf.bytes(b^);
3795+
3796+(* After, with Buf.leak (R5) *)
3797+var b: Buf.Buf;
3798+Buf.init(b, Heap.heap);
3799+Fmt.write(b, f, args);
3800+return Buf.leak(b); (* b gives its block up for good: it lasts *)
3801+```
3802+
3803+Without `Buf.leak` the only safe form is a second copy, `Str.copy` of
3804+the bytes and then `Buf.done`, for every message. `Sym.typeName` is the
3805+same, and so are four `grab`-and-slice strings in `Parse`, `Item` and
3806+`Raz`.
3807+
3808+**Sym's scopes.** The hash table `hashTab: ^^Obj` becomes `Vec(^Obj)`,
3809+and `rehash` builds a new one and drops the old. `Obj`s and `Type`s
3810+come from `NEW` and are never freed, so the 1,015 dereferences stay as
3811+they are, as 8.1 says. Under the strict reading of 6.1, though, each
3812+procedure that stores a pointer it is given needs `keep`: `newObj`'s
3813+`typ`, `insert`'s `obj`, and the 17 procedures of `Item` and `Parse`
3814+that put a `^Sym.Type` or `^Sym.Obj` parameter into a `var x: Item`.
3815+That is about 40 headings across `src/`, and every argument is a
3816+pointer from `NEW` already (R3 removes them). `Parse`'s `curLoop :=
3817+ADR(lp)` becomes a stack of loops in a module array, about 10 lines.
3818+
3819+**Count.** 14,285 lines. The fence's own list (section 2.2): about 60
3820+sites. Parts B to F and what the mending entails: Scan 40, Chunk 60,
3821+the 200 accesses, Diag and the kept strings 30, Sym 20, `keep` marks
3822+40, loops 10. About 420 lines, 3%.
3823+
3824+**Judgement.** Scan's table and `Diag.say` come out clearer. `Chunk`
3825+and `Link` come out longer, and no clearer, unless R1 allows accessors.
3826+Speed: a call, a count and a bounds check where a pointer index stood,
3827+on the symbol lookup and code emission paths. That is not measured; an
3828+estimate is 1 to 3% of instructions, on top of the 4.5% of 13.1 if
3829+`Scan` goes safe as well. **Run-time stops in correct code:**
3830+`Parse.raz:3696`, `text := Buf.bytes(s)` and then `Buf.done(s)`, would
3831+stop at the first generic instance the compiler made, and so `make
3832+check` would stop in its first minute. **Real bugs caught:** none,
3833+beyond the bound in `intern` that holds by luck.
3834+
3835+### A7.5 The library (`Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files`) and `examples/Sh.raz`
3836+
3837+**`Fmt` can't be made safe as section 5.4 says.** `format` takes
3838+`b: ^Buf.Buf`, with `nil` for standard output, and `write` and
3839+`eprint` pass `ADR(b)`. Without `ADR`, the `nil` must become a flag,
3840+and `print` has no `Buf` to pass:
3841+
3842+```
3843+(* After *)
3844+var none: Buf.Buf; (* never written: what print passes for b *)
3845+
3846+proc put(var b: Buf.Buf; out: BOOL; s: []U8);
3847+begin
3848+ if out then Out.str(s); else Buf.str(b, s); end;
3849+end;
3850+
3851+proc print*(f: []U8; args: []Arg);
3852+begin
3853+ format(none, true, f, args);
3854+end;
3855+```
3856+
3857+This is a contortion: an owner kept only to stand in for "none".
3858+`eprint` builds its text in a `Buf` over an arena, so that a program
3859+that doesn't call it carries no heap. Under the proposal
3860+`Buf.init(b, Arena.allocator(ar))` is refused. `init` keeps its
3861+allocator, so its parameter is `keep`, and the arena's allocator is
3862+lent by the arena (8.4). So `eprint` moves to the heap and loses the
3863+reason its comment gives. No container can take memory from an arena
3864+in safe code. About 15 lines change.
3865+
3866+**`Opt` is safe, with one stop in correct code.** `left` and
3867+`leftWidth` take `const r: Row` for `ADR(p.table[i])`, six lines.
3868+`init` is `keep name, table`, and `scope` is `keep name`. `say` would
3869+stop:
3870+
3871+```
3872+proc say(fd: INT; var b: Buf.Buf);
3873+var s: []U8; n: INT;
3874+begin
3875+ s := Buf.bytes(b);
3876+ while LEN(s) > 0 do
3877+ n := Sys.write(fd, s);
3878+ if n <= 0 then break; end;
3879+ s := s[n..LEN(s)];
3880+ end;
3881+ s := []; (* new: else the next line stops, though s is empty and never read again *)
3882+ Buf.done(b);
3883+end;
3884+```
3885+
3886+Every usage message and every `--help` of every program goes through
3887+`say`.
3888+
3889+**`Map` marks are easy, and its uses narrow.** `put(var m; keep k: K;
3890+keep v: V)` is one heading. `Map([]U8, V)` keys must now last, so a
3891+key made in a `Buf` is `Str.copy`'d and never freed, or goes in
3892+`Names(V)`. `Map(K, Buf.Buf)` can't be made at all: `put` takes `V` by
3893+value, and an owner can't be copied. A map of strings to buffers, an
3894+editor's "buffer by name", has no safe form but `Pool` handles.
3895+
3896+**The containers export what breaks them.** `Buf.len*`, `Vec.len*`,
3897+`List.head*` and `List.Node.next*` are fields a safe module can write.
3898+`b.len := 1 shl 40; Buf.bytes(b)` reads any memory, because `bytes`
3899+slices `b.data`, a pointer, unchecked. `l.head := other.head;
3900+List.clear(l)` frees another list's nodes. This is 5.3's rule 4, but
3901+section 17 doesn't list it. Hiding the fields changes every read of
3902+`b.len` in every program, dozens in rmacs alone, unless fields can be
3903+exported read-only (R6). `Files.load` writes `INC(b.len, n)` after
3904+`Buf.spare`, as `spare`'s own comment says to, so `Files` isn't safe
3905+either until `Buf` gets a checked `took(var b; n)`. `examples/Words`
3906+walks `order.head` and `n^.next`, three lines that become
3907+`Names.first` and `Names.next`.
3908+
3909+**`examples/Sh.raz`: its arena has no safe form.** `Sh` builds each
3910+word in a `Buf` over a module arena, keeps `Buf.bytes(b)` in the module
3911+variable `text` and in `Command.args`, and resets the arena for each
3912+script. Every one of those is refused: the `Buf` over the arena (keep,
3913+8.4), `text := Buf.bytes(b)` (7.3), `c^.args[c^.n] := text` through a
3914+pointer (6.2), `return Buf.bytes(b), true` in `find` (7.3), and `s :=
3915+script` from `run(Buf.bytes(line))` (keep). Building `argv` from spans
3916+at `spawn` is refused too, since a local array of slices may not hold
3917+a lend (7.3). What compiles is a bump allocator written by hand over a
3918+module array, whose slices last:
3919+
3920+```
3921+var
3922+ pool: [1 shl 24]U8; (* the words of what is being run; a module's array lasts *)
3923+ used: INT;
3924+
3925+proc add(c: U8);
3926+begin
3927+ if used = LEN(pool) then say("out of room for words", []); Rt.exit(2); end;
3928+ pool[used] := c;
3929+ INC(used);
3930+end;
3931+
3932+(* in readWord, for Buf.init(b, ADR(arena.base)) ... text := Buf.bytes(b) *)
3933+start := used;
3934+...
3935+text := pool[start..used];
3936+```
3937+
3938+The rules let this pass, and that's right: `used := 0` makes old words
3939+show new bytes, which is a matter of logic, not memory. But it shows
3940+that the arena was refused for what it is, not for anything it does.
3941+`ADR(p^.cmds[i])` becomes an index, and `builtin` and `start` take
3942+`const`. The scanner's module state (`s`, `at`, `text`) goes into a
3943+`Scanner` record passed by `var`, so that `run` needn't keep its
3944+script. That is 45 of 387 lines, 12%. The scanner comes out clearer,
3945+and the allocator worse: an `Arena` was one line, and this is ten.
3946+
3947+### A7.6 rjson's `Json` (`src/Json.raz`, `test/Suite.raz`)
3948+
3949+`Doc` grows its nodes by hand with `Mem.alloc` and `Mem.free`, and
3950+copies strings into a list of chunks that `reset` frees. So `Json`
3951+says `unsafe;` and carries the owner protocol itself: a `LENDS` field,
3952+retiring chunks in `reset`, `ret` on `text`, `key` and `copy`. That is
3953+about 25 lines of trusted code outside the library, and the same holds
3954+for every program with a container of its own (`Text` in rmacs). The
3955+audit surface grows with each one. The zero-copy design ("the text
3956+must live as long as the document") means `parse` keeps its text. The
3957+suite's
3958+
3959+```
3960+v := Json.parse(ADR(d), Buf.bytes(ADR(text))); (* twice *)
3961+```
3962+
3963+is refused, since a `Buf`'s bytes don't last. Such a program either
3964+leaks each file's bytes with `Buf.leak`, which is fine for a test but
3965+not for a server parsing request bodies, or `Json` gets a `parseCopy`
3966+that copies the text into the document first: one copy per parse,
3967+small next to parsing. About 40 lines change, 4%.
3968+
3969+### A7.7 Holes the port found in the rules
3970+
3971+Each of these lets unsafe code through as the proposal is written, or
3972+leaves undecided whether correct code stops.
3973+
3974+- **H1. A store through a slice isn't a store that outlives.** 6.2
3975+ lists module variables, `p^.f` and `var` parameters. It doesn't list
3976+ `s[i] := e` for a slice `s`. So `proc fill(names: [][]U8); var buf:
3977+ [8]U8; begin names[0] := buf[0..8]; end;` puts a slice of the frame
3978+ in the caller's array. `Vec.all(v)[i] := e` puts a lend in a
3979+ container the same way. The rule must say that a store through a
3980+ slice not lent by the frame alone is a store that outlives.
3981+- **H2. A `ret` through a record that holds owners loses the owner.**
3982+ `name*(ret const m: Message; i: INT): []U8`, the accessor section
3983+ 14.2 recommends, returns a lend of `m.head`. The caller knows only
3984+ that the result is lent by `m`, which isn't an owner (7.2), so it
3985+ doesn't know whose count to raise, and it raises none. Then
3986+ `readRequest` grows `m.head`, frees the old block, and the held
3987+ slice dangles. Either the accessor is refused, and 14.2's way out
3988+ doesn't compile, or it is allowed, and the count is lost. R1
3989+ mends it.
3990+- **H3. The containers' exported fields** (A7.5): `Buf.len*`,
3991+ `Vec.len*`, `List.head*`, `Node.next*`, and `Files.load`'s `INC(b.len,
3992+ n)` by design.
3993+- **H4. A literal over a live owner.** `m := {minor: 1}` is allowed
3994+ (7.6: a literal may leave an owner out). It drops the owner's block,
3995+ which is a safe leak, and zeroes its allocator, so the owner's next
3996+ growth stops. It is a trap that compiles, and the obvious rewrite of
3997+ `Http.reset` falls into it.
3998+- **H5. The order of a hold's let-go and `defer`.** If holds are let go
3999+ after the deferred statements, every `defer Buf.done(b)` over a
4000+ local that holds `Buf.bytes(b)` stops the program. If before, a
4001+ deferred statement that reads the local reads memory still allocated,
4002+ which is fine. Section 7.3 must say "before".
4003+- **H6. Option 2 of 14.2 breaks rule 4 of 5.3** (A7.2). An unsafe
4004+ `Http` with exported slice fields hands a safe module a slice it can
4005+ read after `Http.done`.
4006+
4007+### A7.8 The verdict, in numbers
4008+
4009+| Code | Lines | The fence alone (`ADR` to own pointers, casts) | Parts B to F | Share | Result |
4010+|---|---|---|---|---|---|
4011+| rnet `Http`, `Conn`, tests, `Hello` | 2,700 | 330 | 230 | 9% | worse |
4012+| rmacs | 4,931 | 160 | 90 | 2% | the same |
4013+| raz `src/` | 14,285 | 60 sites | 420 | 3% | Scan, Diag clearer; Chunk, Link longer |
4014+| `lib/`: `Fmt`, `Opt`, `Map`, `Buf`, `Vec`, `List`, `Files` | 1,500 | 15 | 70 | 5% | Fmt worse; the rest the same |
4015+| `examples/Sh.raz` | 387 | 10 | 45 | 12% | scanner clearer, allocator worse |
4016+| rjson `Json`, `Suite` | 1,050 | 15 | 40 | 4% | the same, with a copy per parse |
4017+| **All** | **24,850** | **about 590** | **about 895** | **4%** | |
4018+
4019+Where parts B to F's 895 lines come from, by rule:
4020+
4021+| Rule | Lines | Share | What it hits |
4022+|---|---|---|---|
4023+| 7.3: an owner's lend returned, or held in a record or array | 450 | 50% | `Message`, `Url`, `Core.slice`, `Mini.Names`, `Chunk`'s accessors, `Sh`'s words, `Json`, `Diag.say` |
4024+| 5.1 and 8.4: no safe form for a context pointer, or for a container over an arena | 200 | 22% | `Conn.state`, `Server.arg`, `Thread.spawn`, `Fmt.eprint`, `Sh`'s arena |
4025+| 6.1 and 6.2 read strictly: `keep` on a pointer parameter that is stored | 60 | 7% | `Sym`, `Item`, rmacs's `Core` |
4026+| 7.6: owners aren't copied | 30 | 3% | `Http.reset`, `open`'s `out := req^` |
4027+| 5.3 rule 4: the containers' fields hidden | 20, or every read of `.len` | 2% | rmacs, `Files` |
4028+| D: no `free` | 5, leaking | 1% | rmacs's buffers and windows |
4029+| the rest: `ret` marks, `t := []`, views | 130 | 15% | everywhere, a line at a time |
4030+
4031+**Stops at run time in correct code: 8**, found by a search for a
4032+local holding `Buf.bytes(b)` when `b` is done: `Opt.say`,
4033+`Parse.raz:3696`, `examples/Elf.raz`, rmacs's `Commands` (two),
4034+ravite's `Ravite.raz`, rnet's `Dns` (two). Five of them depend on H5.
4035+Each is found the first time its code runs, and each is mended with one
4036+line. But there is one in the compiler and one in the library, so
4037+`make check` would stop the day part C came in.
4038+
4039+**Real bugs caught: none** in about 25,000 lines. One bound holds by
4040+the coincidence of two constants (Scan). Every slice held across a
4041+change of its buffer was right, by an order the code keeps. So the
4042+rules make "right by discipline" checked. They guard tomorrow's code;
4043+they don't mend today's. The five programs of section 1.2 were written
4044+to show the holes. None of them was found in this code.
4045+
4046+**Is the pain narrow?** By lines, yes: 96% of the code is left alone,
4047+or changes only where `STANDARDS.md` already asks it to. By kind, no.
4048+Five of the six pieces need a redesign of the one type they are built
4049+round. Each such type keeps a slice of a buffer in a record, or hands
4050+one out from a procedure that isn't the buffer's own, and those are
4051+the pieces that do I/O or hold data. Code that only computes, `Parse`'s
4052+statements, `Item`, `Gen`, rflate's inflater, `Fmt`'s formatting, is
4053+left alone, as section 14.1 says.
4054+
4055+### A7.9 Beside Rust and beside today's raz
4056+
4057+**Beside today's raz.** Today the six pieces compile as they are, and
4058+their rules of lifetime are comments ("good until the buffer next
4059+grows", "the text must live as long as the document"). Under the
4060+proposal four of those comments become checks, and the code that
4061+leans on them grows by about 4%. It loses three things that were
4062+easy: a record of slices of someone else's buffer, an accessor that
4063+returns a slice of a buffer, and a container over an arena.
4064+
4065+**Beside Rust.** Where a record holds slices of its *own* buffer
4066+(`Message`, `Doc`), Rust can't do it either: a struct can't borrow
4067+from itself, so Rust programs use spans, as here, or a crate built for
4068+it. Where a record holds slices of *another's* buffer (`Url` of a
4069+`Buf`, `Sh`'s `argv`, a `Doc` over a file's bytes), Rust writes
4070+`Url<'a>` and is done; raz must copy, or use a frame array. Where a
4071+procedure returns a slice of an owner it reaches through a global or a
4072+pointer (`Core.slice`, `bufferNames`, `Chunk.at`), Rust writes
4073+`&'static` or a lifetime on the result; raz can't write it at all.
4074+Where a callback needs its context (`Server.arg`, `Conn.state`), Rust
4075+has closures and trait objects; raz has `^U8`, which is fenced. On
4076+the other hand, 96% of the code needs no mark at all, where a Rust
4077+port of `Sym`, `Item` and `Parse`'s trees, with their `^Obj` and
4078+`^Type` links everywhere, would need `Rc`, arenas with lifetimes or
4079+indexes throughout. And Rust would reject at compile time the eight
4080+`done`-while-held places, where this proposal stops at run time. In
4081+short, the proposal costs much less than Rust in the code that
4082+computes, more than Rust in the code that holds buffers, and it has
4083+nothing for type-erased context, where Rust has a great deal.
4084+
4085+### A7.10 Relaxations and additions
4086+
4087+Each of these removes pain found above. Each says what it would cost,
4088+and what, if anything, it weakens.
4089+
4090+- **R1. A lend carries its count.** An owner's lend returned from any
4091+ procedure carries the address of its owner's count, in a hidden word,
4092+ as a held local already does. Then the caller counts it on the right
4093+ owner, whoever returned it. This allows `Core.slice`, `Mini.text`,
4094+ `Dired.nameAt`, `Chunk.at`, `Http.target` and `Json.text`, mends H2,
4095+ and removes about 250 of the 450 lines of 7.3. A procedure type
4096+ must say that its result carries a count (`proc(i: I64): lent
4097+ []U8`). It costs a register on return. It weakens nothing.
4098+- **R2. A local array or record may hold lends** (question 4 of section
4099+ 21: yes), with one hold for each owner it holds lends of, all let go
4100+ when the local is assigned whole or the procedure returns. This
4101+ allows `Url` of a `Buf`, `Sh`'s `argv`, and a local `[]Fmt.Arg` of
4102+ several `Buf`s, and removes about 60 lines. It costs a few words in
4103+ the frame. It weakens nothing.
4104+- **R3. A pointer parameter lasts, as STANDARDS says it does** ("a
4105+ pointer, only when it is kept"). An unmarked `^T` parameter may be
4106+ stored. An owner's pointer (`Vec.add`, `Pool.at`) may not be passed
4107+ as a `^T` argument, only dereferenced at the call, `f(p^)` to a `var`.
4108+ This removes the 60 `keep` marks, and it puts the check on the rare
4109+ case, the owner's pointer, not the common one. It weakens nothing.
4110+- **R4. `Vec.get(const v; i: INT): T` and `Vec.set(var v; i: INT;
4111+ keep x: T)`.** A copy of an element holds what was kept, and that
4112+ lasts. This mends `Scan.nameOf` and `Diag.pathOf`. Library only,
4113+ and it weakens nothing.
4114+- **R5. `Buf.leak(var b: Buf.Buf): []U8` and `Vec.leak`.** The owner
4115+ gives its block up for good and is left empty, and the block lasts,
4116+ since no one holds what could free it. This is Rust's `Box::leak`. It
4117+ mends `Diag.say`, `Sym.typeName`, `Parse`'s and `Item`'s kept
4118+ strings, and a test's file. Library only, and it weakens nothing,
4119+ but leak-freedom, which the guarantee doesn't promise (3).
4120+- **R6. Fields exported read-only**, Oberon-2's `len-: INT`, and
4121+ `Buf.took(var b; n: INT)`, checked against the room `spare` made. This
4122+ closes H3 and keeps every read of `b.len` as it is, while the seven
4123+ writes in rmacs become `Buf.cut`. A language change of one mark.
4124+ It weakens nothing, and without it the containers aren't safe.
4125+- **R7. `done` with a lend held is caught when compiling where it
4126+ can be, and otherwise retires.** In one pass, the compiler knows when
4127+ a local was last assigned a lend of `b` and has not been assigned
4128+ since, so at `Buf.done(b)` it can say "`s` still holds a lend of `b`:
4129+ write `s := []` first". That turns six of the eight stops into
4130+ messages. The two through a pointer stay. For those, `done` retires
4131+ the block instead of stopping: question 3 of section 21, answered
4132+ "leak". With H5 settled as "before", the eight become none. It weakens
4133+ leak-freedom, not safety, and the debugging heap can report each
4134+ leak.
4135+- **R8. A checked context pointer.** A type `^ANY`, which any pointer
4136+ from `NEW` converts to, and a conversion back, `^T(p)`, checked
4137+ against a type word that `NEW` writes before the record. A wrong
4138+ type stops the program, as Oberon's type guard does. This mends
4139+ `Conn.state`, `Http.Server.arg`, `Thread.spawn`'s `arg` and the
4140+ tests' casts, about 150 lines, and lets a server keep its state
4141+ without module variables shared across threads. It costs a word per
4142+ record that is ever made `^ANY`, if `NEW` is told so, and a compare
4143+ per conversion. It weakens nothing.
4144+- **R9. Growth with a *writable* lend held stops; with a lend that
4145+ only reads, it retires.** `Vec.add` and `Buf.spare` lend for
4146+ writing, and `bytes` and `all` lend for reading. A write into a
4147+ retired block is lost with no message (A7.4); a stop says where.
4148+ `Buf.str(b, Buf.bytes(b))` still runs. This is a tightening, not a
4149+ relaxation. It costs a second count per owner, and `all` must split
4150+ in two, since today it lends for both.
4151+
4152+Some pain has no relaxation that keeps the guarantee:
4153+
4154+- **A container over an arena** (`Fmt.eprint`, `Sh`). Making it safe
4155+ needs the container to hold the arena's count for as long as it
4156+ lives: an owner holding a lend, which is a lifetime in a record,
4157+ Rust's apparatus. A module array with an index does it safely, as
4158+ `Sh`'s rewrite shows, at a fixed size. Otherwise such code stays
4159+ unsafe.
4160+- **A record that keeps slices of its own buffer** (`Message`, `Doc`)
4161+ stays spans and accessors, in raz as in Rust. With R1 the accessors
4162+ compile, and that is all the help there is.
4163+- **Freeing records one by one.** `Pool`, or leaking. For an editor
4164+ leaking is the plain choice, and it is safe. `Pool` needs an `alloc`
4165+ that hands out a zeroed slot, for records that hold owners.
4166+
4167+With R1 to R8, the port's 895 lines fall to about 400, under 2%. The
4168+contortions left are `Fmt`'s stand-in and `Sh`'s allocator, and no
4169+correct code stops at run time. The holes H1 to H6 are mended by
4170+R1, R6 and two sentences in 6.2 and 7.3.