Standard library · System and tools

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:

  • Assert is 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 Enter and Exit calls. Always pair them with defer debug.Exit().
  • MemStats only 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.

debug-stack-errors.salam
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()
end
Outputerror in load_catalogue > load_item cake > parse_price: empty price 2 items loaded, depth now 0

After 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.

debug-trace-calls.salam
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
end
Output[TRACE] fib 3: enter [TRACE] fib 3 > fib 2: enter [TRACE] fib 3 > fib 2 > fib 1: enter [TRACE] fib 3 > fib 2 > fib 1: base case [TRACE] fib 3 > fib 2 > fib 1: exit [TRACE] fib 3 > fib 2 > fib 0: enter [TRACE] fib 3 > fib 2 > fib 0: base case [TRACE] fib 3 > fib 2 > fib 0: exit [TRACE] fib 3 > fib 2: exit [TRACE] fib 3 > fib 1: enter [TRACE] fib 3 > fib 1: base case [TRACE] fib 3 > fib 1: exit [TRACE] fib 3: exit fib(3) = 2

Reading 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.

debug-timers.salam
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")
end
Outputtrue both steps fit in the total: true a timer keeps running after StopTimer: true unknown timer: 0

Times 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.

debug-assert.salam
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
end
Outputtrue 70 false 70 true 0

When 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.

debug-memstats.salam
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()
end

The 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)
If the condition is false, prints assertion failed: and the message to standard error and stops the program with abort. It also runs in release builds.
debug-Enter.salam
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
end
Output2 root > child 0 true [TRACE] a trace message 499500 true

AssertNotNil

func AssertNotNil(p: void*, msg: str)
If the pointer is null, stops the program like a failed Assert.

The example for this item is shown with the ones above: debug-Enter.salam

Enter

func Enter(frame: str)
Adds a frame to the hand-kept stack, usually at the start of a function, and prints an 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()
Takes the last frame off the stack, printing an 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(): str
The current stack from the outermost frame in, as root > 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(): int
The depth of the hand-kept stack.

The example for this item is shown with the ones above: debug-Enter.salam

EnableTrace

func EnableTrace(enabled: bool)
Turns trace messages on or off.

The example for this item is shown with the ones above: debug-Enter.salam

TraceEnabled

func TraceEnabled(): bool
True when tracing is on.

The example for this item is shown with the ones above: debug-Enter.salam

Trace

func Trace(msg: str)
When tracing is on, prints [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)
Starts a timer under the given name on the monotonic clock; a name that is already running starts again from zero.

The example for this item is shown with the ones above: debug-Enter.salam

StopTimer

func StopTimer(name: str): f64
The milliseconds since the timer started, with fractions. The timer keeps running, so a later call gives a larger number; an unknown name gives 0.

The example for this item is shown with the ones above: debug-Enter.salam

Break

func Break()
Stops in the debugger at this line (it raises 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(): str
One line with allocs, 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