# Your first script

This walkthrough takes about ten minutes. It starts with a script that prints
one line and ends with one that names a library's functions after the strings
they log, then runs the same script from an agent.

You need [borer installed](/docs/install.md), a text editor, and two Windows
binaries in one folder:

- `notepad.exe`, copied from `C:\Windows\System32`.
- `sqlite3.dll`, any 64-bit Windows build of [SQLite](https://sqlite.org/download.html).
  The output below is from SQLite 3.49.1. Another build has other addresses.

Every command runs from that folder.

### 1. Hello, program

Save this as `hello.rhai`:

```rhai
let p = program();
print(`${p.format} ${p.arch} ${p.bits}-bit, entry ${hex(p.entry)}`);
print(`${functions().len} functions, ${imports().len} imports`);
```

Run it:

```text
$ borer script notepad.exe hello.rhai
Pe x86-64 64-bit, entry 0x1400019c0
523 functions, 340 imports
# script: 0 names and 0 comments proposed, 36 operations
```

`program()` returns a map. Backtick strings fill in `${...}`. `hex` prints an
integer as an address. The last line is borer's own: what the script proposed
and how many operations it ran.

### 2. Ask what you can call

`help()` lists every function a script can call, one line each. `help(name)`
prints one of them. Save `print(help("strings"));` as `help.rhai`:

```text
$ borer script notepad.exe help.rhai
strings(e): strings a function references, maps of at, text
# script: 0 names and 0 comments proposed, 5 operations
```

The [Script API](/docs/plugins/script-api.md) page has the full list.

### 3. Walk the functions

`functions()` returns one map per function: `entry`, `name`, `size`, `instrs`,
`blocks` and `source`, where its name came from. Save this as `sources.rhai`:

```rhai
// How many functions got their name from where.
let by = #{};
for f in functions() {
  if f.source in by { by[f.source] += 1; } else { by[f.source] = 1; }
}
print(by);
```

```text
$ borer script notepad.exe sources.rhai
#{"-": 9, "sym": 514}

$ borer --no-pdb script notepad.exe sources.rhai
#{"-": 448, "fnl": 3, "hlp": 2, "lib": 2, "slot": 29, "sym": 39}

$ borer script sqlite3.dll sources.rhai
#{"-": 2278, "fnl": 12, "hlp": 2, "sym": 387}
```

With its PDB, notepad names almost every function (`sym`). Without it, 448 are
unnamed (`-`, shown as `sub_<address>`). SQLite exports its API, so 387 have
symbols, and 2,278 have no name at all. Those are what a script can name.

### 4. Look at what they reference

`strings(entry)` lists the strings a function references. Save this as
`strings.rhai`, to print the unnamed functions that reference a string
starting with `win`:

```rhai
for f in functions("sub_") {
  let texts = strings(f.entry).map(|s| s.text);
  if texts.some(|t| t.starts_with("win")) { print(`${hex(f.entry)} ${texts}`); }
}
```

```text
$ borer script sqlite3.dll strings.rhai
0x18000de40 ["winClose", "@SUVWH"]
0x18000def0 ["winRead", "@SUVWH", "delayed %dms for lock/sharing conflict at line %d"]
0x18000e090 ["delayed %dms for lock/sharing conflict at line %d", "winWrite2", "@SUVWH", "winWrite1", "@SUVWH"]
0x18000e240 ["winSeekFile", "@SUVWH", "winTruncate1", "winTruncate2", "@SUVWH"]
0x18000e390 ["winSync1", "winSync2", "@SUVWH"]
0x18000e420 ["winFileSize", "@SUVWH"]
0x18000e520 ["winUnlockReadLock", "@SUVWH"]
0x18000e920 ["winUnlock", "@SUVWH"]
...
```

SQLite's Windows layer (`os_win.c`) passes the name of the function it is in to
its error logger: `winRead` logs `"winRead"`. A function that logs `winWrite1`
and `winWrite2` from two places is `winWrite`.

`@SUVWH` is not a string. `strings` reads text at every address a function
references, the functions it calls included, and the logger's first
instructions (`push rbx; push rbp; push rsi; ...`) happen to be printable. A
script that wants real strings keeps only those in sections that are not code.

### 5. Find the logger

The logger's format string names its source file. `find_text` finds the
string, and `xrefs` finds who reads it. Save as `logger.rhai`:

```rhai
for at in find_text("os_win.c:%d:") {
  print(`format string at ${hex(at)}`);
  for x in xrefs(at) {
    let f = function(x.function);
    print(`  read by ${f.name} at ${hex(x.from)}, ${f.callers.len} callers`);
  }
}
```

```text
$ borer script sqlite3.dll logger.rhai
format string at 0x18013eb70
  read by sub_18000dd20 at 0x18000ddb0, 19 callers
# script: 0 names and 0 comments proposed, 42 operations
```

### 6. Name the callers

Now put it together. For each unnamed caller of the logger, keep the strings
that sit in data and look like a C identifier, drop trailing digits, and
propose the name when exactly one is left. If two callers log the same name,
name neither: a missed name beats a wrong one. Save as `name_by_log.rhai`:

```rhai
// Names each unnamed caller of a logger after the function name it logs.
//
//   borer script sqlite3.dll name_by_log.rhai ["os_win.c:%d:"]
//
// The argument is text from the logger's format string (default: SQLite's
// Windows VFS). Every unnamed function that calls the logger and references
// exactly one identifier-shaped string is proposed that name, digits at the
// end dropped ("winWrite2" is "winWrite"), unless another caller logs the
// same name.

let needle = if args().len > 0 { args()[0] } else { "os_win.c:%d:" };

// Sections that hold data, not code: strings(e) also reads text at the
// functions a function calls, and a callee's first bytes are not a name.
let data = sections().filter(|s| !s.x);
fn in_data(at, data) {
  data.some(|s| at >= s.at && at < s.at + s.size)
}

// The text as a C identifier with its trailing digits dropped, else ().
fn ident(text) {
  if text.len < 4 || (text[0] >= '0' && text[0] <= '9') { return (); }
  for c in text.chars() {
    if !(c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) {
      return ();
    }
  }
  while text[-1] >= '0' && text[-1] <= '9' { text.pop(); }
  text
}

// The logger: whatever function reads the format string.
let loggers = [];
for at in find_text(needle) {
  for x in xrefs(at) {
    if x.function != () && !loggers.contains(x.function) { loggers.push(x.function); }
  }
}
print(`loggers: ${loggers.map(|e| hex(e))}`);

// Each caller's one identifier, and who claims each name.
let claims = #{};
for lg in loggers {
  for c in callers(lg) {
    if !name(c).starts_with("sub_") { continue; }
    let found = [];
    for s in strings(c) {
      let id = if in_data(s.at, data) { ident(s.text) } else { () };
      if id != () && !found.contains(id) { found.push(id); }
    }
    if found.len != 1 { continue; }
    let id = found[0];
    if id in claims { claims[id].push(c); } else { claims[id] = [c]; }
  }
}
for id in claims.keys() {
  let who = claims[id];
  if who.len == 1 { rename(who[0], id); } else { print(`skipped ${id}: ${who.len} functions log it`); }
}
```

```text
$ borer script sqlite3.dll name_by_log.rhai
loggers: ["0x18000dd20"]
skipped winClose: 2 functions log it
# script: 11 names and 0 comments proposed, 12573 operations
what	at	text
name	0x180010df0	winAccess
name	0x180010c40	winDelete
name	0x18000e420	winFileSize
name	0x180011030	winFullPathname
name	0x18000f020	winLockSharedMemory
name	0x18000def0	winRead
name	0x18000e390	winSync
name	0x18000e920	winUnlock
name	0x18000e520	winUnlockReadLock
name	0x18000fcc0	winUnmapfile
name	0x18000e090	winWrite
```

Eleven names, each backed by the string the function logs. `winClose` was
skipped because a second function logs it too. The [handler table recipe](/docs/plugins/recipes.md) names it from another
piece of evidence.

### 7. Keep the names

Proposals are not applied. To keep them, save them as a project file, then
turn the project into a pack that finds the same functions by their first
bytes:

```text
$ borer script sqlite3.dll name_by_log.rhai --save names.json
borer: saved 11 names and 0 comments to names.json

$ borer export-pack sqlite3.dll winvfs names.json > winvfs.borer

$ borer --pack winvfs.borer functions sqlite3.dll winRe
# showing 1 of 1 functions; 104 import thunks left out, filter=thunk lists them; 12 exception funclets left out, filter=funclet lists them
# entry size blocks instrs callers callees src name
0x18000def0 405 27 111 0 4 pack winRead
```

`src` is `pack`: the name came from `winvfs.borer`. The [Packs](/docs/plugins/packs.md) page
shows how to make a pack load by itself and run the script on every load.

### 8. Run it from an agent

An agent sends the same script as the `code` of the `script` tool. After
`load_binary` with `sqlite3.dll`:

```json
{ "name": "script", "arguments": { "code": "<the text of name_by_log.rhai>" } }
```

The answer is the same table, and it ends with a line saying nothing changed:

```text
loggers: ["0x18000dd20"]
skipped winClose: 2 functions log it
# script: 11 names and 0 comments proposed, 12573 operations
what	at	text
name	0x180010df0	winAccess
...
name	0x18000e090	winWrite
# dry-run: pass dry_run=false to apply these
```

With `"dry_run": false` the names are applied to the session:

```text
...
# applied names at 11 addresses and comments at 0, the last proposal for an address winning; 0 skipped (empty, unprintable, or in no section)
```

`functions` then lists `0x18000def0 ... usr winRead`, and `save_project` keeps
the names for the next session.

Over MCP, `args()` is always empty, since the tool takes no arguments. That is
why the script falls back to a default needle.
