# Debugging

`giz debug` is the one debugger of every client: a person at a terminal, an editor, and an agent or a script. Each one
drives the same session over the [Debug Adapter Protocol](https://microsoft.github.io/debug-adapter-protocol/), with
gdb 14 or later (or lldb-dap) as the engine and the program's DWARF from the compiler. Values are shown as Gizlang
writes them.

- [Choose a tool](#choose-a-tool) for the question.
- [Start a session](#start-a-session) at a terminal, as JSON for an agent, or in an editor.
- [What a stop shows](#what-a-stop-shows), and [stops at faults](#stops-at-faults).

## Choose a tool

| Question | Tool |
| --- | --- |
| Why does it fail here, with these values? | `giz debug` with a breakpoint, or with no breakpoint: [it stops at the fault](#stops-at-faults) |
| Where did a fault come from, after the fact? | The fault report on standard error: each frame, its line and the innermost frame's arguments |
| A run that fails only sometimes | `giz run --record LOG`, then `giz run --replay LOG` replays the same inputs ([command line](command-line.md#record-and-replay)) |
| Why is it slow? | [`giz profile`](performance.md); `resource SESSION gpu` for GPU timing, `resource SESSION gpu --kernels` for kernel code, and `top SESSION --measure device` for device buffer allocations |
| Is a GPU kernel's answer wrong? | `GIZLANG_TILE_CHECK=1e-4` runs each Tile kernel on the CPU too and stops at the first that differs, with its IR and layouts ([settings](../reference/settings.md)) |
| What did a GPU kernel compile to? | `GIZLANG_GPU_SOURCES=FOLDER` keeps each kernel's source; an edited copy there runs instead ([settings](../reference/settings.md)) |

## Start a session

`giz debug FILE [ARGS...]` builds FILE for a debugger (`giz build --debug`: unoptimized, with DWARF for its lines,
functions, arguments and locals) and runs it in a session. `giz debug --attach PID` debugs a program that already runs
([attach](#attach-to-a-running-program)). These examples use this program:

```gizlang title="main.giz"
type Point = { x: i64; y: f64; };
function total(n: i64, p: Point, names: Vec<string>): i64 {
    const twice = n * 2;
    return twice + p.x + names.length;
}
export function main(): void {
    const p: Point = { x: 4, y: 1.5 };
    let sum: i64 = 0;
    for (const k of range(0, 3)) { sum += total(k, p, ["ab", "cd"]); }
    console.log(`${sum}`);
}
```

### At a terminal

`giz debug main.giz` prompts with `(giz)`. Set breakpoints, then `run`:

| Command | Does |
| --- | --- |
| `break FILE:LINE`, `break FILE:LINE if CONDITION`, `break FUNCTION` | Stops there (`b`) |
| `run`, `continue` | Starts the program, or goes on to the next stop (`r`, `c`) |
| `next`, `step`, `finish` | One source line, into a call, out of the function (`n`, `s`) |
| `print EXPRESSION` | Its value in the top frame (`p`) |
| `bt` | The frames |
| `quit` | Ends the program (`q`); so does the end of the input |
| Any other line | The engine's own command, such as `watch p.x` (a data watchpoint) or `info threads` |

```text
$ giz debug main.giz
(giz) break main.giz:4
(giz) run
stopped (breakpoint)
  total /src/main.giz:4
  main /src/main.giz:9
  n = 0
  p = {x: 4, y: 1.5}
  names = ["ab", "cd"]
  twice = 0
(giz) continue
```

### For an agent or a script

`giz debug --json FILE` is the same session as JSON lines. Each line it reads on standard input is a DAP request,
`{"command":NAME,"arguments":{...}}`: `setBreakpoints`, `setFunctionBreakpoints`, `configurationDone` (starts the
program), `continue`, `next`, `stepIn`, `stepOut`, `stackTrace`, `scopes`, `variables`, `evaluate` (with
`"context":"repl"`, the engine's own command) and `disconnect`. Each line it writes is a DAP message: the response to
each request, the program's `output` events, and for each stop the `stopped` event, then the `stackTrace` and
`variables` responses of the top frame. The last line is `{"exit":CODE}`.

```text
$ giz debug --json main.giz
{"command":"setBreakpoints","arguments":{"source":{"path":"/src/main.giz"},"breakpoints":[{"line":4,"condition":"n == 2"}]}}
{"type":"response","command":"setBreakpoints","success":true,...}
{"command":"configurationDone"}
{"type":"event","event":"stopped","body":{"reason":"breakpoint","threadId":1}}
{"type":"response","command":"stackTrace","body":{"stackFrames":[{"id":1,"name":"total","source":{"path":"/src/main.giz"},"line":4},...]}}
{"type":"response","command":"variables","body":{"variables":[{"name":"n","value":"2","type":"i64"},{"name":"p","value":"{x: 4, y: 1.5}","type":"Point"},...]}}
{"command":"disconnect"}
{"exit":-1}
```

A scripted run needs no input: `--break PLACE` (any number; `FILE:LINE`, `FILE:LINE if CONDITION` or `FUNCTION`)
stops at each place, reports the stop, the value of each `--eval EXPRESSION`, and goes on.

```sh
giz debug --json --break main.giz:4 --eval twice main.giz
```

Every session ends: after 100 stops it ends the program, and `--timeout SECONDS` ends it after that time. With `--attach`
it detaches instead, and the program goes on. The exit status is 0 when the program exits with 0.

### Attach to a running program

`giz debug --attach PID` debugs a program that already runs, instead of building FILE. The debugger reads the binary
from `/proc/PID/exe`, so build the program with `giz build --debug` first. Without `--break` it stops each thread once,
reports its frames and values as a stop does, and detaches: the program goes on. With `--break` it is a scripted run,
as above. On Linux, Yama `ptrace_scope` 1 (a common default) lets a debugger attach only to its own child. Then run the
program under `giz debug FILE`, or allow attaching until the next boot with `sudo sysctl kernel.yama.ptrace_scope=0`.

### In an editor

`giz debug --dap` speaks the protocol on standard input and output. A `launch` whose `program` is a `.giz` file builds
it first; a failed build fails the launch with its message, and `giz check FILE` shows the errors. The variables of
each frame show their values as a [stop](#what-a-stop-shows) does.

In VS Code, press F5 in a `.giz` file, click **Debug** above `main` or beside a test, or run **Gizlang: Debug File**.
A `launch.json` entry:

```json
{ "type": "gizlang", "request": "launch", "name": "Debug Gizlang file", "program": "${file}", "args": [] }
```

| Attribute | Meaning |
| --- | --- |
| `program` | The `.giz` file to debug |
| `args` | The program's arguments |
| `cwd` | Its working folder (default: the workspace folder) |
| `debugger` | `gdb` (the default; `lldb-dap` on macOS) or `lldb-dap` |
| `debuggerPath` | The debugger command, when it is not on `PATH` |

[Editors](editors.md#set-up-an-editor) has the setup of Neovim and other editors.

## What a stop shows

The frames of the program (the runtime's own frames are left out), and each argument and local of the top frame:

- a record by its fields, `{x: 4, y: 1.5}`, three levels deep;
- a `string` as its text, `"ab"`, and `bytes` as `b"..."`, the first 256 bytes and then the length;
- a `Vec` by its first 8 items, `[1, 2, 3, … 40 items]`, each shown the same way;
- a union (`Option`, `Result` and your own) by its case, `{kind: "square", side: 3}`.

To keep the binary, build it yourself: `giz build --debug main.giz -o app`. `giz build --debug --release` builds it
optimized with the same DWARF, so `giz profile` names the source line of each sample.

## Stops at faults

A session stops where a fault happens, with no breakpoint: an index out of bounds, an overflow, a failed assertion, a
fault in a task. The stop's reason is `exception`; its top frame is the failing function, at the failing line, with its
values as they were. When the session goes on, the fault leaves as it would without a debugger: a task's join returns
it, or the program ends with its report.
