# Recipes

Scripts for real tasks. Each one was run on the binary its usage line names,
and the output under it is that run's, trimmed. Copy one, change the lines at
the top, and run it.

The binaries are Windows' own `notepad.exe`, `ntdll.dll` and `curl.exe` (all
in `C:\Windows\System32`) and a 64-bit SQLite 3.49.1 `sqlite3.dll`. On another
build the addresses differ.

### Name functions by what they log

Many programs pass the name of the function they are in to a logger or an
assert: `__FUNCTION__`, a hand-written tag, a trace event. The script from
[Your first script](/docs/plugins/your-first-script.md), step 6, finds the logger by its format
string and names each unnamed caller after the one identifier it passes.

```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	0x18000e090	winWrite
```

To adapt it, pass text from your program's logger format as the argument:
`borer script app.exe name_by_log.rhai "assert failed in %s"`. If your
program's tags are not plain identifiers (`Class::Method`), change `ident`.

### Label a handler table

A table of function pointers (a vtable, a driver's dispatch table, an
interface's methods) names its functions by position. Start from one function
you already know, read the table around it, and name every slot by its field.

This names SQLite's `sqlite3_io_methods` table, starting from `winRead`, which
the names pack from [step 7](/docs/plugins/your-first-script.md) found:

```rhai
// Names the functions in a table of function pointers by the table's
// field names, starting from one function you already know.
//
//   borer --pack winvfs.borer script sqlite3.dll label_table.rhai
//
// Edit the four lines below for your table. Every table that holds KNOWN
// at slot AT is read; a table whose other slots are not all null or a
// function entry is skipped as not this layout. A field that two tables
// fill with different functions is left unnamed.

let FIELDS = ["iVersion", "xClose", "xRead", "xWrite", "xTruncate", "xSync",
  "xFileSize", "xLock", "xUnlock", "xCheckReservedLock", "xFileControl",
  "xSectorSize", "xDeviceCharacteristics", "xShmMap", "xShmLock",
  "xShmBarrier", "xShmUnmap", "xFetch", "xUnfetch"];
let KNOWN = "winRead";
let AT = 2;
let PREFIX = "win";

let known = function(KNOWN);
if known == () { print(`no function ${KNOWN}`); return; }
let claims = #{};
for x in xrefs(known.entry) {
  if x.kind != "table" { continue; }
  let base = x.from - 8 * AT;
  let slots = [];
  for i in 1..FIELDS.len { slots.push(read_u64(base + 8 * i)); }
  if slots.some(|v| v != 0 && function(v) == ()) {
    print(`${hex(base)}: not this layout, skipped`);
    continue;
  }
  print(`${hex(base)}: ${FIELDS.len} slots`);
  comment(base, `${PREFIX} table: ${FIELDS.len} slots, ${FIELDS[0]} ${read_u64(base)}`);
  for i in 1..FIELDS.len {
    let v = slots[i - 1];
    if v == 0 { continue; }
    let field = FIELDS[i];
    let want = PREFIX + field.sub_string(1);
    if want in claims { if !claims[want].contains(v) { claims[want].push(v); } } else { claims[want] = [v]; }
  }
}
for want in claims.keys() {
  let who = claims[want];
  if who.len > 1 { print(`skipped ${want}: ${who.len} functions fill it`); continue; }
  if name(who[0]).starts_with("sub_") { rename(who[0], want); }
}
```

```text
$ borer --pack winvfs.borer script sqlite3.dll label_table.rhai
0x18014bd70: 19 slots
0x18014c350: 19 slots
skipped winCheckReservedLock: 2 functions fill it
skipped winLock: 2 functions fill it
skipped winUnlock: 2 functions fill it
# script: 11 names and 2 comments proposed, 2498 operations
what	at	text
name	0x18000de40	winClose
name	0x18000edb0	winDeviceCharacteristics
name	0x18000ff40	winFetch
name	0x18000eab0	winFileControl
name	0x18000eda0	winSectorSize
name	0x18000f970	winShmBarrier
name	0x18000f730	winShmLock
name	0x18000f9b0	winShmMap
name	0x18000f600	winShmUnmap
name	0x18000e240	winTruncate
name	0x18000ffc0	winUnfetch
comment	0x18014bd70	win table: 19 slots, iVersion 3
comment	0x18014c350	win table: 19 slots, iVersion 3
```

Two tables hold `winRead`: SQLite's normal methods and its no-lock methods. They
differ in the three lock slots, so those three are left unnamed. The table also
settles `winClose`, which the logger script had to skip, and it agrees with the
logger script on every slot both name (`winRead`, `winWrite`, `winSync`,
`winFileSize`, `winUnlock`).

On a 32-bit program, read slots with `read_u32` and step by 4.

### Find a crypto routine and comment it

A crypto or checksum routine reads tables with well-known first bytes. Find the
tables with `find_bytes`, then the code that references them. borer also names
functions from an algorithm's constants itself (their `source` is `const`), so
the script adds those:

```rhai
// Comments the functions that use well-known crypto or checksum tables.
//
//   borer script ntdll.dll crypto_tables.rhai
//
// Two kinds of evidence, both named in the comment:
// - the function references a table's first byte (each pattern is the
//   table's first bytes as they sit in memory, little-endian);
// - borer named the function from an algorithm's constants (source "const").
// A table reached only through an offset (lea rax, [table-0x88]) has no
// reference at its first byte, so it shows 0 functions.

let tables = #{
  "CRC-32": "00 00 00 00 96 30 07 77 2c 61 0e ee",
  "SHA-256 K": "98 2f 8a 42 91 44 37 71 cf fb c0 b5",
  "MD5 T": "78 a4 6a d7 56 b7 c7 e8 db 70 20 24",
  "AES S-box": "63 7c 77 7b f2 6b 6f c5 30 01 67 2b",
};

// Evidence by function. Called as why.note(...), so `this` is the map
// itself; a plain argument would be a copy.
let why = #{};
fn note(f, text) {
  let k = hex(f);
  if k in this { this[k].push(text); } else { this[k] = [text]; }
}

for algo in tables.keys() {
  for at in find_bytes(tables[algo]) {
    let n = 0;
    for x in xrefs(at) {
      if x.function == () { continue; }
      why.note(x.function, `references the ${algo} table at ${hex(at)}`);
      n += 1;
    }
    print(`${algo} table at ${hex(at)}: ${n} references from code`);
  }
}
for f in functions() {
  if f.source == "const" { why.note(f.entry, `borer named it ${f.name} from its constants`); }
}
for k in why.keys() {
  let f = function(k);
  let text = "";
  for w in why[k] { text += if text == "" { w } else { "; " + w }; }
  print(`${k} ${f.name}`);
  comment(f.entry, text);
}
```

```text
$ borer script ntdll.dll crypto_tables.rhai
CRC-32 table at 0x180181ac0: 1 references from code
SHA-256 K table at 0x180187900: 0 references from code
0x1800edcd8 crc32_fn
0x18011c5a0 sha1_block
0x18011d770 sha1_or_ripemd160_fn
0x18011dbe8 sha256_fn
0x18011dcf8 sha256_or_blake2s_fn
0x18011dd20 sha256_block
0x18011eff0 md5_block
0x18011fdf0 md5_or_md4_fn_18011fdf0
0x180120000 md5_or_md4_fn_180120000
0x1801617a0 md5_or_md4_fn_1801617a0
0x1801617c0 md5_or_md4_fn_1801617c0
# script: 0 names and 11 comments proposed, 28988 operations
what	at	text
comment	0x1800edcd8	references the CRC-32 table at 0x180181ac0; borer named it crc32_fn from its constants
comment	0x18011c5a0	borer named it sha1_block from its constants
...
```

The SHA-256 round constants are in ntdll, but no instruction points at their
first byte: the code reaches them through an offset. Matching the start of a
table misses that case. borer's own `crypto` command (the
[`find_crypto_constants`](/docs/tools/find_crypto_constants.md) tool) reports
which functions read each table, offsets included.

### Tag network send and receive paths

Start at the socket imports, then walk up the callers, so every function on the
way to a send or a receive says so:

```rhai
// Tags the functions on the way to a program's socket sends and receives.
//
//   borer script curl.exe net_paths.rhai [depth]
//
// A function that calls send, sendto or WSASend (or one of the recv
// family) is tagged first; then its callers, and theirs, up to depth
// levels above it (default 2). Each comment names the import reached
// and the function that leads to it.

let depth = if args().len > 0 { parse_int(args()[0]) } else { 2 };
let families = #{ "send": ["send", "sendto", "WSASend", "WSASendTo"],
                  "recv": ["recv", "recvfrom", "WSARecv", "WSARecvFrom"] };

for fam in families.keys() {
  let tag = #{};       // hex(entry) -> its comment
  let reach = #{};     // hex(entry) -> the import it reaches
  let level = [];
  for imp in imports() {
    let fname = imp.name.split("!")[-1];
    if !families[fam].contains(fname) { continue; }
    for x in xrefs(imp.at) {
      let f = x.function;
      if f == () || hex(f) in tag { continue; }
      tag[hex(f)] = `calls ${fname}`;
      reach[hex(f)] = fname;
      level.push(f);
    }
  }
  for d in 1..=depth {
    let next = [];
    for f in level {
      for c in callers(f) {
        if hex(c) in tag { continue; }
        reach[hex(c)] = reach[hex(f)];
        tag[hex(c)] = `reaches ${reach[hex(f)]} in ${d + 1} calls, through ${name(f)}`;
        next.push(c);
      }
    }
    level = next;
  }
  print(`${fam}: ${tag.len()} functions within ${depth + 1} calls`);
  for k in tag.keys() {
    let entry = function(k).entry;
    print(`  ${k} ${name(entry)}: ${tag[k]}`);
    comment(entry, `${fam} path: ${tag[k]}`);
  }
}
```

```text
$ borer script curl.exe net_paths.rhai
recv: 7 functions within 3 calls
  0x14000a5a0 sub_14000a5a0: calls recv
  0x140044720 sub_140044720: calls recv
  0x1400449b0 sub_1400449b0: calls recv
  0x1400559d0 sub_1400559d0: reaches recvfrom in 3 calls, through sub_140055b70
  0x140055ac0 sub_140055ac0: reaches recvfrom in 3 calls, through sub_140055b70
  0x140055b70 sub_140055b70: reaches recvfrom in 2 calls, through sub_1400560b8
  0x1400560b8 sub_1400560b8: calls recvfrom
send: 24 functions within 3 calls
  0x14000c3b0 sub_14000c3b0: calls send
  0x140015e10 sub_140015e10: reaches send in 3 calls, through sub_14002f418
  ...
# script: 0 names and 31 comments proposed, ...
```

The walk follows direct calls. The three functions that call `recv` have no
callers at all: curl calls them through function pointers, and a function
reached only through a pointer has no callers, so the walk stops there. To go
further, find the tables that hold those functions with `xrefs(entry)` and a
`kind` of `table`, as the handler table recipe does.

### Find the vtables of a class

MSVC's run-time type information ties a class's name to its vtables. This
script follows the x64 layout from the decorated name to every vtable:

```rhai
// Finds the vtables of a C++ class from its MSVC x64 RTTI, and names any
// of their functions borer left unnamed Class::vfunc_N.
//
//   borer script notepad.exe vtables.rhai exception@std
//
// The argument is the class as MSVC decorates it, without ".?AV" and the
// final "@@": `exception@std` is std::exception. The walk is the x64
// layout: the type descriptor holds the name 16 bytes in; a complete
// object locator (signature 1) holds the descriptor's RVA 12 bytes in;
// a vtable's slot -1 points at its locator.

if args().len == 0 { print("usage: vtables.rhai <decorated class, e.g. exception@std>"); return; }
let want = args()[0];
let base = program().base;
let parts = want.split("@");
parts.reverse();
let pretty = parts.reduce(|a, b| if a == () { b } else { a + "::" + b });

fn le32(v) {
  let out = "";
  for i in 0..4 { let b = (v >> (8 * i)) & 0xff; out += (if b < 16 { "0" } else { "" }) + hex(b).sub_string(2) + " "; }
  out
}

for s in find_text(`.?AV${want}@@`) {
  let td = s - 16;
  for hit in find_bytes(le32(td - base)) {
    let col = hit - 12;
    if read_u32(col) != 1 || read_u32(col + 20) != col - base { continue; }
    for x in xrefs(col) {
      let vt = x.from + 8;
      let n = 0;
      while n < 64 {
        let slot = read_u64(vt + 8 * n);
        if slot == () || function(slot) == () { break; }
        if name(slot).starts_with("sub_") { rename(slot, `${pretty}::vfunc_${n}`); }
        n += 1;
      }
      print(`${pretty}: vtable ${hex(vt)}, ${n} slots, locator ${hex(col)} at offset ${read_u32(col + 4)}`);
      for i in 0..n { print(`  [${i}] ${hex(read_u64(vt + 8 * i))} ${name(read_u64(vt + 8 * i))}`); }
      comment(vt, `vtable of ${pretty} (${n} slots)`);
    }
  }
}
```

```text
$ borer script notepad.exe vtables.rhai exception@std
std::exception: vtable 0x140029018, 2 slots, locator 0x14002e380 at offset 0
  [0] 0x140002760 std::bad_array_new_length::`scalar deleting destructor'
  [1] 0x140002800 std::exception::what
# script: 0 names and 1 comments proposed, 392 operations
what	at	text
comment	0x140029018	vtable of std::exception (2 slots)
```

Slot 0 carries another class's name: the PDB names that address after
`std::bad_array_new_length`, most likely because the linker folded identical
destructors into one function. A class with several bases has one vtable per
base, each with its own locator; `at offset` is where that base sits in the
object. borer already names a recovered class's virtual functions by slot when
there is no PDB (`source` is `slot`), so on a stripped build this script mostly
lists and comments.

### Map a game's manager objects

Game engines keep their managers (world, player, inventory) in one global or
thread-local slot each. `borer://singletons` finds those slots; this script
then collects every field offset reached through each one, from the code that
loads the slot and from the class's own methods. It reads resources, so run it
with the MCP [`script`](/docs/tools/script.md) tool:

```rhai
// Maps the fields of each global manager object: the singletons borer
// found, the functions that read each one's slot, and the offsets they
// reach through it. Run it with the MCP script tool: it reads resources.
//
// Each field lists who touches it and how:
// - "global": a function loads the slot and dereferences what it holds
//   (borer://fields names that base after the global);
// - "this": a method named Class::... touches it through its first argument.

for s in rows("borer://singletons") {
  // The global's own name, as borer://why reports it.
  let label = ();
  for line in query(`borer://why/${hex(s.slot)}`).split("\n") {
    if line.starts_with("# name: ") { label = line.split(": ")[-1]; }
  }
  print(`${s.class}: ${s.kind} slot ${hex(s.slot)} (${label})`);
  let fields = #{};
  let users = [];
  for x in xrefs(s.slot) {
    if x.function != () && !users.contains(x.function) { users.push(x.function); }
  }
  for f in users {
    for r in rows(`borer://fields/${hex(f)}`) {
      if r.base != label { continue; }
      let k = hex(r.offset);
      let row = `global ${r.dir}${r.widths} ${name(f)}`;
      if k in fields { fields[k].push(row); } else { fields[k] = [row]; }
    }
  }
  for m in functions(`${s.class}::`) {
    for fl in layout(m.entry) {
      let k = hex(fl.offset);
      let row = `this ${if fl.addressed { "&" } else { fl.size }} ${m.name}`;
      if k in fields { fields[k].push(row); } else { fields[k] = [row]; }
    }
  }
  let offsets = fields.keys();
  offsets.sort(|a, b| parse_int(a.sub_string(2), 16) - parse_int(b.sub_string(2), 16));
  for k in offsets { print(`  +${k}: ${fields[k]}`); }
}
```

On notepad, after `load_binary`, the `script` tool answers:

```text
RestartHandler: global slot 0x140036680 (restartHandler)
  +0x0: ["this 8 RestartHandler::RestartHandler", "this 8 RestartHandler::~RestartHandler", "this & RestartHandler::`vector deleting destructor'"]
  +0x8: ["this 8 RestartHandler::RestartHandler", "this 8 RestartHandler::~RestartHandler", "this 8 RestartHandler::ShouldSupportRestartManager", "this 8 RestartHandler::TryAutosaveOpenedDocument"]
  +0x10: ["global r8 BannerWndProc", "this 8 RestartHandler::RestartHandler", "this 8 RestartHandler::~RestartHandler", "this 8 RestartHandler::TryAutosaveOpenedDocument", "this 8 RestartHandler::TryRestoreAutosavedDocument"]
  +0x18: ["global w1 BannerWndProc", "global w1 NPWndProc", "this 1 RestartHandler::RestartHandler"]
# script: 0 names and 0 comments proposed, 2263 operations
```

`r8` is an 8-byte read, `w1` a 1-byte write. `+0x18` is a one-byte flag that
two window procedures set, a good place to start for a mod. The `this` rows
need the class's methods to carry its name (`RestartHandler::...`), which a PDB,
RTTI or a pack gives. For an engine whose singleton accessor has its own name,
set it with a pack's [`[naming] singleton`](/docs/plugins/packs.md) line.

### Rename functions from a symbol list

Names from another tool, a leaked map file or a teammate come as a list of
addresses and names. A script reads no files, so paste the list into it, or
pass entries on the command line:

```rhai
// Renames functions from a symbol list: one "address name" per line.
//
//   borer script app.exe rename_list.rhai
//   borer script app.exe rename_list.rhai 0x14000a630=BannerWndProc
//
// A script reads no files, so paste the list below, or pass entries on
// the command line as address=name. An address inside a function, or one
// no function starts at, is reported and skipped.

let LIST = `
0x14000a630 BannerWndProc
0x14000e950 NPWndProc
0x140013154 NPInit
0x140013160 NotAnEntry
`;

let entries = [];
for line in LIST.split("\n") {
  line.trim();
  if line == "" || line.starts_with("#") { continue; }
  let w = line.split(" ");
  entries.push([w[0], w[w.len - 1]]);
}
for a in args() { let w = a.split("="); if w.len == 2 { entries.push(w); } }

let done = 0;
for e in entries {
  let f = function(e[0]);
  if f == () || hex(f.entry) != e[0].to_lower() { print(`skipped ${e[0]} ${e[1]}: no function starts there`); continue; }
  if f.name != e[1] { rename(f.entry, e[1]); done += 1; }
}
print(`${done} of ${entries.len} names proposed`);
```

```text
$ borer --no-pdb script notepad.exe rename_list.rhai 0x140001008=FirstFunction
skipped 0x140013160 NotAnEntry: no function starts there
4 of 5 names proposed
# script: 4 names and 0 comments proposed, 402 operations
what	at	text
name	0x14000a630	BannerWndProc
name	0x14000e950	NPWndProc
name	0x140013154	NPInit
name	0x140001008	FirstFunction
```

Add `--save names.json`, then `borer export-pack notepad.exe mine names.json`,
and the names become a pack that finds the same functions in the next build.

### List every caller of an API

The first question about most binaries: who calls this import?

```rhai
// Comments every function that calls an import, and lists each with the
// number of functions that call it.
//
//   borer script notepad.exe api_callers.rhai CreateFileW
//
// The argument is part of the import's name, case ignored.

if args().len == 0 { print("usage: api_callers.rhai <part of an import's name>"); return; }
let want = args()[0].to_lower();
for imp in imports() {
  if !imp.name.to_lower().contains(want) { continue; }
  let api = imp.name.split("!")[-1];
  print(`${imp.name} at ${hex(imp.at)}`);
  let seen = [];
  for x in xrefs(imp.at) {
    let f = x.function;
    if f == () || seen.contains(f) { continue; }
    seen.push(f);
    print(`  ${hex(f)} ${name(f)}, callers ${callers(f).len}`);
    comment(f, `calls ${api}`);
  }
}
```

```text
$ borer script notepad.exe api_callers.rhai CreateFileW
api-ms-win-core-file-l1-1-0.dll!CreateFileW at 0x140029de8
  0x14000ca10 DetermineFileTypeEncoding, callers 2
  0x14000da7c NPCommand, callers 1
  0x14001008c doDrop, callers 1
  0x140011af8 SaveFile, callers 3
  0x140013154 NPInit, callers 1
  0x14001e370 ProcessSetupOption, callers 1
  0x14001e5ac ProcessShellOptions, callers 1
  0x140022440 RestartHandler::ShouldSupportRestartManager, callers 1
  0x1400229e8 RestartHandler::TryRestoreAutosavedDocument, callers 1
# script: 0 names and 9 comments proposed, ...
```

`imp.at` is the import's slot, so `xrefs` finds every `call [slot]`. A program
that calls through a thunk instead has its calls on the thunk: follow
`callers` of the thunk's entry.
