# Script API

Everything a script can call, as borer's engine defines it
(`crates/borer-engine/src/script.rs`). `print(help())` prints the same list in
short form, and `help("name")` prints one entry.

### Where a script runs

| Where        | How                                                         | `args()`                 | `query`, `rows`           | What happens to proposals                                       |
| ------------ | ----------------------------------------------------------- | ------------------------ | ------------------------- | --------------------------------------------------------------- |
| Command line | `borer script <binary> <file> [args...]`                    | the words after the file | not available             | printed; `--save <project>` writes them to a project file       |
| MCP tool     | [`script`](/docs/tools/script.md) with `code` and `dry_run` | always empty             | every `borer://` resource | printed; applied to the session with `dry_run=false`            |
| MCP resource | `borer://script/{path}`                                     | always empty             | not available             | printed, never applied                                          |
| Pack         | `[scripts] run <file>` in a `.borer` file                   | always empty             | not available             | names go on unnamed functions; comments are counted and dropped |

`--pack`, `--no-pdb` and the other global options work with `borer script`.
A script run from the command line sees borer's names and the packs' names. It
does not see the names a `--project` file gives; the MCP tool sees the
session's names.

On the command line a failing script exits with status 1 and prints only its
error. The MCP tool answers what the script printed and proposed before the
error, then `# script failed: ...`, and applies nothing.

### Values

- Integers are 64-bit and signed. An address is an integer; one above
  `0x7fffffffffffffff` reads as negative, and `hex` prints it right.
- `()` means nothing: no function there, nothing mapped there.
- Maps print with their keys in sorted order and integers in decimal. Use `hex`
  for addresses.
- A call marked *entry or name* takes an integer address or a text: an address
  written out (`"0x14000a630"`), a `sub_` name, or any function's name. The
  other calls take an integer.

### The program

| Call         | Returns                                                                              |
| ------------ | ------------------------------------------------------------------------------------ |
| `program()`  | map: `path`, `format`, `arch`, `bits`, `base`, `entry` (`()` when the file has none) |
| `sections()` | array of maps: `name`, `at`, `size`, `r`, `w`, `x`                                   |
| `imports()`  | array of maps: `name` (as `module!function`), `at` (the import's slot)               |
| `exports()`  | array of maps: `name`, `at`                                                          |

```rhai
print(program());
print(sections()[0]);
print(imports()[0]);
```

```text
#{"arch": "x86-64", "base": 5368709120, "bits": 64, "entry": 5368715712, "format": "Pe", "path": "notepad.exe"}
#{"at": 5368713216, "name": ".text", "r": true, "size": 157666, "w": false, "x": true}
#{"at": 5368879416, "name": "GDI32.dll!SetMapMode"}
```

### Functions

| Call                               | Returns                                                                                                                                                             |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `functions()`                      | array of maps, one per function in address order: `entry`, `name`, `size` (bytes), `instrs`, `blocks`, `source`. Import thunks and exception funclets are included. |
| `functions(filter)`                | the same, for names that contain `filter`, case ignored                                                                                                             |
| `function(entry or name)`          | one function's map with `callers` and `callees` added (arrays of entries), or `()`                                                                                  |
| `callers(entry)`, `callees(entry)` | arrays of entries; empty for no function                                                                                                                            |
| `name(entry)`                      | the name in force: a symbol, borer's name, a pack's, or `sub_<address>`                                                                                             |

`source` says where the name came from: `-` none, `sym` the symbol table or a
PDB, `hlp` a compiler helper recognized by its shape, `sig` a signature string
the function carries, `hnd` a command handler's message, `slot` a vtable slot,
`qt` Qt metadata, `fnl` an exception funclet, `pack` a pack, `lib` a library
signature, `objc` Objective-C metadata, `const` an algorithm's constants.

A map from `functions()` has no `callers` or `callees`; reading them gives `()`.
Call `function(f.entry)` or `callers(f.entry)` for those.

```rhai
print(functions("WndProc").map(|f| f.name));
let f = function("BannerWndProc");
print(`${name(f.entry)}: ${callers(f.entry).len} callers, ${callees(f.entry).len} callees`);
```

```text
["BannerWndProc", "DismissButtonWndProc", "NPWndProc"]
BannerWndProc: 0 callers, 9 callees
```

`name(addr)` answers `sub_<addr>` for an address no function starts at, data
included.

### References

| Call             | Returns                                                                                                                                                         |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `strings(entry)` | array of maps: `at`, `text`, for each address the function references that holds a printable ASCII run of 4 or more bytes (cut at 512 characters, ending `...`) |
| `xrefs(addr)`    | array of maps: `from` (the referencing instruction or data), `kind`, `function` (the entry it sits in, or `()`)                                                 |

`kind` is one of `call`, `jmp`, `imm/mem` (a load, store or address in an
instruction), `index` (the base of a table an index scales into), `table` (a
pointer to a function stored in data: a vtable, a callback table) or `ptr` (a
pointer to data stored in data).

Two things to know about `strings`:

- It reads every address the function references, its callees included, so a
  callee's first instructions can show up as text such as `@SUVWH`. Keep the
  `at` values that fall in a section whose `x` is false.
- It reads single-byte text only. A UTF-16 literal (most of the text in a
  Windows GUI program) is not listed. `borer fstrings` and the
  `function_strings` tool list both kinds.

```rhai
print(strings(function("NPInit").entry)[0]);
print(xrefs(function("BannerWndProc").entry)[0]);
```

```text
#{"at": 5368887912, "text": "shell\\osshell\\accesory\\notepad\\nprestart.cpp"}
#{"from": 5368751009, "function": 5368750644, "kind": "imm/mem"}
```

### Bytes

| Call                                                | Returns                                                                                                    |
| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
| `read_u8(addr)`, `read_u16`, `read_u32`, `read_u64` | the little-endian integer at a virtual address, or `()` when it is not mapped                              |
| `bytes(addr, n)`                                    | a blob of up to `n` bytes (at most 1 MiB), shorter at the end of the mapping, empty when nothing is mapped |
| `cstr(addr)`                                        | the printable ASCII run that starts there (cut at 512 characters), or `()`                                 |
| `find_bytes(pattern)`                               | array of addresses where a hex pattern matches; `??` is any byte: `"48 8b ?? ff"`                          |
| `find_text(text)`                                   | array of addresses where the text is stored, as ASCII or as UTF-16                                         |

`find_bytes` and `find_text` return the first 500 matches inside sections.
A pattern that does not parse returns an empty array.

```rhai
print(hex(read_u16(program().base)));
print(bytes(function("BannerWndProc").entry, 4));
print(read_u32(0x10));
print(find_text("ms-windows-store").map(|a| hex(a)));
print(cstr(0x14002ad90));
```

```text
0x5a4d
[40555356]

["0x14002ad60", "0x14002ad90"]
m
```

`read_u32(0x10)` printed an empty line: nothing is mapped there. The last line
shows the UTF-16 limit: `0x14002ad90` holds `L"ms-windows-store://..."`, and
`cstr` stops after the first character.

### Code

| Call                                                  | Returns                                                                                                                                                                                 |
| ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `disasm(addr, n)`                                     | array of up to `n` instructions (at most 4,096): maps of `at`, `bytes` (hex), `text`                                                                                                    |
| `decompile(entry or name)`                            | the function's pseudo-C as text, or `()`                                                                                                                                                |
| `scenario(entry or name, spec)`                       | the pseudo-C with parameters fixed, `"a2=5"` or `"a2=5,a3=0"`: branches on them fold and only the code that can run is written; `()` for a spec that does not parse                     |
| `layout(entry or name)`, `layout(entry or name, reg)` | the fields the function reaches through a pointer, its first argument or the register `reg`: maps of `offset`, `size` (the widest access, 0 for a field only passed on) and `addressed` |

`decompile` and `scenario` share a budget of 2,000 calls a run. `layout`
counts against the 200-call query budget.

```rhai
let f = function("BannerWndProc");
print(disasm(f.entry, 2));
print(layout("RestartHandler::TryAutosaveOpenedDocument"));
print(scenario(f.entry, "a2=5"));
```

```text
[#{"at": 5368751664, "bytes": "4055", "text": "push rbp"}, #{"at": 5368751666, "bytes": "53", "text": "push rbx"}]
[#{"addressed": false, "offset": 8, "size": 8}, #{"addressed": false, "offset": 16, "size": 8}]
// scenario: a2 = 5; 45 of 50 blocks cannot run
// BannerWndProc @ 0x14000a630: 175 instructions, 50 blocks
// signature: uint64_t BannerWndProc(uint64_t a1, uint64_t a2, uint64_t a3, uint64_t a4)
...
LayoutBanner();
return 0;
```

### Resources

These need a front end that answers resources: the MCP `script` tool. Anywhere
else they throw `query is not available here: no front end answers resources`.

| Call            | Returns                                                                                                                                                                                          |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `query(uri)`    | the text of any `borer://` resource; `!offset=N!limit=N` pages a listing                                                                                                                         |
| `rows(uri)`     | the same resource as a table: one map per row, keyed by the column headers; a cell that reads as a number (decimal or `0x` hex) is an integer; a text with no table is one row with a `text` key |
| `help("query")` | every resource, one line each, with an example URI                                                                                                                                               |

`query`, `rows`, `layout` and `help("query")` share a budget of 200 calls a
run. A script cannot query `borer://script/...`, so scripts do not run scripts,
and a URI holding `dry_run=false` is refused: a script only proposes.

```rhai
print(rows("borer://singletons"));
```

```text
[#{"class": "RestartHandler", "instance": "-", "kind": "global", "slot": 5368931968}]
```

### Proposals

| Call                  | Does                                                                                    |
| --------------------- | --------------------------------------------------------------------------------------- |
| `rename(entry, name)` | proposes a function name; an empty name, or one holding a tab or line break, is ignored |
| `comment(addr, text)` | proposes a comment at any address; tabs and line breaks become spaces                   |

A run keeps up to 100,000 proposals of up to 1,024 characters each. Past that
they are counted as dropped. When the MCP tool applies them, a name given to an
address inside a function goes on that function's entry, the last proposal for
an address wins, and one at an address no section holds is skipped.

### Everything else

| Call                   | Does                                                                      |
| ---------------------- | ------------------------------------------------------------------------- |
| `print(x)`, `debug(x)` | prints a value; each line of a multi-line text counts as one printed line |
| `hex(n)`               | `n` as `0x...` hex text                                                   |
| `args()`               | the words after the script file on the command line                       |
| `help()`, `help(name)` | the call list, or one call's line                                         |

Rhai's own functions all work: strings (`split`, `contains`, `starts_with`,
`sub_string`, `to_lower`, `trim`), arrays (`push`, `map`, `filter`, `some`,
`reduce`, `sort`, `contains`), maps (`keys`, `values`, `in`), `parse_int` and
the rest of the [Rhai book](https://rhai.rs/book/). Modules (`import`), `eval`,
and the time functions are not built in.

### Budgets and caps

| Limit                                      | Value                                                    | Past it                                                 |
| ------------------------------------------ | -------------------------------------------------------- | ------------------------------------------------------- |
| Operations                                 | 200,000,000 a run                                        | `Too many operations`                                   |
| Call nesting                               | 64 levels                                                | `Stack overflow`                                        |
| `decompile` and `scenario`                 | 2,000 calls a run                                        | `decompile budget spent: 2000 calls per run`            |
| `query`, `rows`, `layout`, `help("query")` | 200 calls a run together                                 | `query budget spent: 200 calls per run`                 |
| A string                                   | 64 MiB, the strings in one array or map counted together | `Length of string too large`                            |
| An array, map or blob                      | 2,097,152 items                                          | `Size of array/BLOB too large`                          |
| `bytes`                                    | 1 MiB a call                                             | the read is cut                                         |
| `disasm`                                   | 4,096 instructions a call                                | the list is cut                                         |
| `find_bytes`, `find_text`                  | 500 matches                                              | the rest are left out                                   |
| Printed lines                              | the first 500 kept, each cut at 4,096 characters         | `# showing 500 of N printed lines`                      |
| Proposals                                  | 100,000 kept, 1,024 characters each; 500 shown           | `# N proposals dropped`, `# showing 500 of N proposals` |

Native calls such as `functions()` do not count as operations, which is why the
costly ones have budgets of their own.

The size caps have a cost: every `push` re-measures the whole array. Pushing
80,000 items one at a time takes about a second, and the time grows with the
square of the count. Arrays that borer returns, and `map` and `filter` over
them, are measured once. A map is cheap to grow.

### Errors

An error names its line and position. These are the ones you will meet:

```text
Error: budget.rhai: Runtime error: decompile budget spent: 2000 calls per run (line 1, position 56)
Error: parse.rhai: Syntax error: Expecting ';' to terminate this statement (line 2, position 1)
Error: q.rhai: Runtime error: query is not available here: no front end answers resources (line 1, position 7)
```

The one you will meet most is calling a function with `()`. This script lists
who references an address in `ntdll.dll`:

```rhai
for x in xrefs(0x180187868) {
  print(`${hex(x.from)} ${x.kind} ${name(x.function)}`);
}
```

```text
$ borer script ntdll.dll probe.rhai
Error: probe.rhai: Function not found: name (()) (line 2, position 37)
```

The third reference is a pointer stored in data, so its `function` is `()`,
and `name(())` matches no call. Check for `()` before you pass a value on:
`if x.function == () { continue; }`. The two lines the script printed before
the error are not shown: the command line prints only the error. The MCP tool
keeps them.

### Rhai notes

A few things about Rhai trip up newcomers:

- **A function gets copies.** A `fn` cannot change a variable outside it, and
  an array or map passed to it is a copy. Call it as a method instead,
  `why.note(f, text)`, and change `this` inside it:

  ```rhai
  let why = #{};
  fn note(f, text) {
    let k = hex(f);
    if k in this { this[k].push(text); } else { this[k] = [text]; }
  }
  why.note(0x1000, "reads the CRC-32 table");
  ```

- **A map's length is `len()`.** On a map, `m.len` reads the key `len`, which
  is `()`. Arrays and strings have the `.len` property.

- **Map keys are text.** Use `hex(entry)` as the key for an address, and
  `function(key)` or `parse_int(key.sub_string(2), 16)` to turn it back.

- **Negative indexes count from the end.** `name.split("!")[-1]` is the last
  part.

- **`return` ends the script** at the top level, which suits a usage line.
