17. Strict mode and ownership
Managed code releases ordinary acyclic objects automatically; cycles can still leak. Strict code gives you full control and takes the safety net away, and in exchange the compiler proves you did it right. A file opts in with its first line:
@file:MemoryMode(Mode.Strict)
import mini.memory.*In Strict mode every allocation has exactly one owner, and the owner must release it exactly once on every path, or hand it on. If the compiler cannot prove that, the program does not compile. Everything below is a live Check cell: edit the code and press Check to watch the checker answer. Diagnostics carry a stable code such as M0102; click it for the reference page.
By the end: follow an owned allocation through every exit path, distinguish borrowing from moving, and repair a leak without creating a double free. These are checker experiments: an expected diagnostic is a result to understand, not an instruction to execute unsafe code.
A leak
This function forgets to release buf on the early-return path:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Buffer(val size: Int) : AutoCloseable {
override fun close() = println("close $size")
}
fun fill(b: Buffer): Boolean = b.size > 100
context(h: Heap)
fun load(n: Int): @Owned Buffer? {
val buf = Buffer(n)
if (!fill(buf)) return null // leaks `buf`
return buf
}
fun main() {
context(Heap()) { load(8).free() }
}Press Check. The error names the allocation (allocated here), the path that leaks (early return) and a suggested fix. The checker follows control flow: the path where fill(buf) is false returns null while buf is still owned. The fix releases on that path too. Edit the cell above and add buf.free() before return null to see the error go away, or check the fixed program:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Buffer(val size: Int) : AutoCloseable {
override fun close() = println("close $size")
}
fun fill(b: Buffer): Boolean = b.size > 100
context(h: Heap)
fun load(n: Int): @Owned Buffer? {
val buf = Buffer(n)
if (!fill(buf)) {
buf.free() // release on this path too
return null
}
return buf // ownership moves to the caller
}
fun main() {
context(Heap()) { load(8).free() }
}On the other path return buf moves the ownership to the caller (the return type is @Owned), and the caller frees it.
Use after free
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun main() {
context(Heap()) {
val b = Box(1)
b.free()
println(b.v) // use after free
}
}M0101. Once b.free() has run, b is dead. The error is at the use, not at the free.
Double free
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun main() {
context(Heap()) {
val b = Box(1)
b.free()
b.free() // freed twice
}
}M0103. Without the checker this is the classic memory corruption bug. Here it is one line of red text.
Moving ownership
A plain assignment only borrows: val alias = a leaves a the owner. To hand the obligation to someone else, move it explicitly. After a move the old name is dead:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
context(h: Heap)
fun run() {
val a = Box(1)
val b = a.move()
println(a.v) // `a` was moved into `b`
b.free()
}
fun main() {
context(Heap()) { run() }
}M0104. The accepted version does not touch a after the move:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
context(h: Heap)
fun run() {
val a = Box(1)
val alias = a // plain assignment only borrows: `a` stays the owner
println(alias.v)
val b = a.move() // explicit move: `b` is the owner now, `a` is dead
println(b.v)
b.free()
}
fun main() {
context(Heap()) { run() }
}Borrowing and owning parameters
Parameters are borrowed by default: the callee may read the object but not free it. A parameter marked @Owned takes over the obligation:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun peek(b: Box): Int = b.v // parameters are borrowed by default
fun consume(b: @Owned Box) { // @Owned: this function takes over the obligation
println("consuming ${b.v}")
b.free()
}
fun main() {
context(Heap()) {
val b = Box(7)
println(peek(b)) // lend: b is still ours afterwards
consume(b) // move: b is gone after this call
}
}Freeing a borrowed parameter is an error, M0107:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun drop(b: Box) {
b.free() // `b` is only borrowed here
}
fun main() {
context(Heap()) {
val b = Box(1)
drop(b)
b.free()
}
}Resources: use {}
AutoCloseable objects can be released with use { }, which runs close() on every path out of the block, including return and exceptions:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Resource(val name: String) : AutoCloseable {
override fun close() {
println("close $name")
}
}
context(h: Heap)
fun run() {
Resource("a").use { println("using ${it.name}") } // close() runs on every path out of the block
val b = Resource("b")
println("open ${b.name}")
b.free() // free() calls close() first
}
fun main() {
context(Heap()) { run() }
}No allocation at all
@NoAlloc promises that a function does not allocate. An object that does not escape lives on the stack and is allowed; one that escapes would be a real allocation and is an error. This one is a complete program, so it runs too:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Vec(val x: Int, val y: Int)
@NoAlloc
fun dist2(a: Int, b: Int): Int {
val v = Vec(a, b) // does not escape: lives on the stack, allowed
return v.x * v.x + v.y * v.y
}
fun main() {
println(dist2(1, 2))
}Press Run and it prints 5. This variant escapes the object and is rejected:
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
@NoAlloc
context(h: Heap)
fun make(): @Owned Box = Box(1) // the Box escapes, so it is a real allocation
fun main() {
context(Heap()) { make().free() }
}What the checker does not do
It follows references to instances of classes declared in a Strict file (and the Arena and Pool resources). Int, String and objects of Managed classes carry no obligations. Escape analysis for stack placement (M0201, M0203) is specified but not implemented. The Strict mode reference and the diagnostics reference list every rule and code, and the checker internals explain how it works.
Checkpoint
If one branch returns early, where must an allocation be released? Is val alias = owner an ownership transfer? Can you free a borrowed parameter?
Reasoning
Every exit path must discharge or transfer the ownership obligation. An alias only borrows; move() explicitly transfers ownership. Borrowed parameters do not grant permission to free the object.
Exercise
Exercise: fix the leak
The checker reports M0102 because one branch forgets to free. Fix it so the checker accepts the program. Hint: both branches have to end the ownership of b.
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun main() {
context(Heap()) {
val b = Box(5)
if (b.v > 3) {
println("big")
b.free()
} else {
println("small")
}
}
}Show solution
@file:MemoryMode(Mode.Strict)
import mini.memory.*
class Box(val v: Int)
fun main() {
context(Heap()) {
val b = Box(5)
if (b.v > 3) {
println("big")
} else {
println("small")
}
b.free() // one release after the branches covers both paths
}
}