debug
Tools for finding a bug: assertions, a hand-kept call stack, tracing and timing.
import debug
The debug package holds a few small tools for when the program is not doing the right thing. Assert checks a condition that should always hold. Enter and Exit keep a call stack by hand, so an error message can say where in the program it happened. Trace prints what the program is doing, the timers show which part is slow, and MemStats counts allocations to find a leak.
It is meant for development. For messages a running service keeps, use log; for exact timing and allocation counters in your own code, runtime and mem; for benchmarks inside tests, testing.
The things people get wrong:
Assertis an ordinary function: it runs in release builds too, and its message is built even when the condition holds. Keep expensive work out of the message.- The stack, the trace switch and the timers are globals with no lock, shared by every thread. In a program with threads the stack mixes frames from all of them.
- The stack is only as good as its
EnterandExitcalls. Always pair them withdefer debug.Exit(). MemStatsonly has numbers in a build with memory counting on; a normal run gets a line saying so.
Trace lines and failed assertions go to standard error, so they do not mix with the program's normal output.
Say where an error happened
An error message like empty price is hard to act on in a big program: which item, and who asked for it? Call Enter at the start of the functions you care about and defer debug.Exit() right after it, so the frame is removed on every return path. Stack then gives the path from the outermost frame to the current one, joined with >. The frame is just text, so it can carry the item being worked on.
import debug
func fail(msg: str): bool:
println "error in", debug.Stack() + ":", msg
ret false
end
func parse_price(text: str): bool:
debug.Enter("parse_price")
defer debug.Exit()
if text.Len() == 0:
ret fail("empty price")
end
ret true
end
func load_item(name: str, price: str): bool:
debug.Enter("load_item " + name)
defer debug.Exit()
ret parse_price(price)
end
func load_catalogue(): int:
debug.Enter("load_catalogue")
defer debug.Exit()
mut loaded := 0
if load_item("tea", "4.50"): loaded++ end
if load_item("cake", ""): loaded++ end
if load_item("milk", "1.20"): loaded++ end
ret loaded
end
func main:
println load_catalogue(), "items loaded, depth now", debug.Depth()
endAfter the outer function returns, Depth is back at 0. If it is not, some function called Enter without a matching Exit, which is exactly the bug that defer prevents.
Trace the calls of a recursive function
EnableTrace(true) switches tracing on: from then on Enter and Exit print an enter and an exit line, and Trace prints its message after the current stack. With tracing off, Trace prints nothing, so trace calls can stay in the code and be switched on with a flag, for instance from a setting or a command line option.
import debug
import str
func fib(n: int): int:
debug.Enter("fib " + str.FromInt(n as i64))
defer debug.Exit()
if n < 2:
debug.Trace("base case")
ret n
end
ret fib(n - 1) + fib(n - 2)
end
func main:
debug.Trace("not printed, tracing is off")
debug.EnableTrace(true)
result := fib(3)
debug.EnableTrace(false)
debug.Trace("not printed either")
printerrln "fib(3) =", result
endReading the lines from top to bottom shows the order of the calls; the indentation you would draw by hand is the length of each stack. All of it goes to standard error, like the last line, which this example prints with printerrln.
Time parts of a program
StartTimer starts a named timer and StopTimer returns the milliseconds since it started, measured with the monotonic clock, so a change of the system time does not disturb it. Starting a timer that already exists restarts it. StopTimer does not remove the timer: calling it again later gives a larger number, which is handy for lap times. A name that was never started gives 0.
import debug
func busy(n: int): int:
mut total := 0
repeat n in i:
total = (total + i * i) % 1000003
end
ret total
end
func main:
debug.StartTimer("all")
debug.StartTimer("step")
a := busy(200000)
first := debug.StopTimer("step")
debug.StartTimer("step")
b := busy(200000)
second := debug.StopTimer("step")
total := debug.StopTimer("all")
later := debug.StopTimer("all")
println a == b
println "both steps fit in the total:", first + second <= total
println "a timer keeps running after StopTimer:", later >= total
println "unknown timer:", debug.StopTimer("never started")
endTimes differ from run to run and from machine to machine, so the example only prints comparisons. In your own program print the numbers themselves, for instance with log at the debug level. Measure a part several times, or over many iterations, before deciding it is slow; the first run often includes one time costs.
Assertions guard your own promises
Assert is for conditions that must hold if the code is correct, such as a balance that never goes below zero after a checked withdrawal. It is not for bad input from users or files: those are expected, and the program should answer them with an error value, as withdraw does with false when the balance is too small.
import debug
struct Account:
pub owner: str = ""
pub balance: int = 0
end
func withdraw(a &: Account, amount: int): bool:
debug.Assert(amount > 0, "withdraw needs a positive amount")
if amount > a.balance:
ret false
end
a.balance -= amount
debug.Assert(a.balance >= 0, "a balance never goes below zero")
ret true
end
func main:
mut acc := Account { owner = "Sara", balance = 100 }
println withdraw(acc, 30), acc.balance
println withdraw(acc, 500), acc.balance
println withdraw(acc, 70), acc.balance
endWhen an assertion fails, the program prints the message to standard error and stops at once with abort, so the exit status is 134 on Linux and no deferred code runs. With the first assertion broken, the run ends like this:
assertion failed: withdraw needs a positive amount
Aborted (core dumped)
Under a debugger (salam debug file.salam) the abort stops in the failing function, so you can look at its variables. Break stops there on purpose, without a failed condition. Do not leave it in code that runs without a debugger: with nothing attached, the program is stopped by the signal.
Find a leak with MemStats
MemStats returns one line with the number of allocations and frees, the bytes still in use (live) and the most that was ever in use (peak). The counting is compiled in only when you ask for it, so build or run with -DSALAM_MEM_DEBUG (or --asan). Print the line before and after a piece of work that should leave nothing behind: if live keeps growing every time it runs, that work leaks.
import debug
func average_score(n: int, free_it: bool): int:
mut scores := Vector {} as Vector<int>
repeat n in i:
scores.Push(60 + i % 40)
end
mut total := 0
each s in scores: total += s end
if free_it: scores.Free() end
ret total / n
end
func main:
println "start: ", debug.MemStats()
repeat 100 in _:
average_score(500, true)
end
println "freed: ", debug.MemStats()
repeat 100 in _:
average_score(500, false)
end
println "leaked:", debug.MemStats()
endThe example is not run on this page because it needs the flag. With salam run -DSALAM_MEM_DEBUG leak.salam it prints:
start: allocs=1 frees=0 live=64 peak=64
freed: allocs=103 frees=101 live=97 peak=2081
leaked: allocs=205 frees=102 live=204936 peak=204936
After the first loop live is back near where it started; after the second it has grown by about 2 KB per call, the 500 numbers each forgotten vector held. salam memcheck file.salam goes further and runs the program under AddressSanitizer, which reports where each leaked block was allocated.
Functions
Assert
func Assert(cond: bool, msg: str)assertion failed: and the message to standard error and stops the program with abort. It also runs in release builds.import debug
func child():
debug.Enter("child")
println debug.Depth()
println debug.Stack()
debug.Exit()
end
func main:
debug.Enter("root")
child()
debug.Exit()
println debug.Depth()
debug.Assert(1 + 1 == 2, "the arithmetic holds")
debug.AssertNotNil(debug.MemStats() as void*, "the memory statistics")
debug.EnableTrace(true)
println debug.TraceEnabled()
debug.Trace("a trace message")
debug.StartTimer("loop")
mut total := 0
repeat 1000 in i:
total += i
end
println total, debug.StopTimer("loop") >= 0.0
if total < 0:
debug.Break()
end
endAssertNotNil
func AssertNotNil(p: void*, msg: str)Assert.The example for this item is shown with the ones above: debug-Enter.salam
Enter
func Enter(frame: str)enter line when tracing is on. Pair it with defer debug.Exit().The example for this item is shown with the ones above: debug-Enter.salam
Exit
func Exit()exit line when tracing is on. On an empty stack it does nothing.The example for this item is shown with the ones above: debug-Enter.salam
Stack
func Stack(): strroot > child; an empty string when it is empty.The example for this item is shown with the ones above: debug-Enter.salam
Depth
func Depth(): intThe example for this item is shown with the ones above: debug-Enter.salam
EnableTrace
func EnableTrace(enabled: bool)The example for this item is shown with the ones above: debug-Enter.salam
TraceEnabled
func TraceEnabled(): boolThe example for this item is shown with the ones above: debug-Enter.salam
Trace
func Trace(msg: str)[TRACE], the stack and the message to standard error. When it is off it does nothing, though the message is still built.The example for this item is shown with the ones above: debug-Enter.salam
StartTimer
func StartTimer(name: str)The example for this item is shown with the ones above: debug-Enter.salam
StopTimer
func StopTimer(name: str): f64The example for this item is shown with the ones above: debug-Enter.salam
Break
func Break()SIGTRAP, or calls DebugBreak on Windows). Without a debugger attached the signal ends the program.The example for this item is shown with the ones above: debug-Enter.salam
MemStats
func MemStats(): strallocs, frees, live and peak bytes. Only in a build with -DSALAM_MEM_DEBUG or --asan; otherwise a line saying the numbers are unavailable.The example for this item is shown with the ones above: debug-Enter.salam