jonesy 0.4.0

Jonesy is here to help you not panic!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# Jonesy: "Don't Panic!"

Jonesy analyzes Rust binaries to find all code paths that can lead to a panic, helping developers understand where panics
can originate in their code.

Focus is currently on getting something useful working. I work on macOS and ARM64, so that's what implemented, but I
definitely want to make it
cross-platform and multi-architecture in the future, but will probably need help from others on Linux and Mac.

## Installation

```bash
cargo install --path jonesy
```

## Usage

### From a Crate Directory

Run jonesy from the root of any Rust crate (where `Cargo.toml` is located):

```bash
cd my-crate
cargo build
jonesy
```

Jonesy will parse `Cargo.toml` to find the package name and binary targets, then analyze all binaries found in
`target/debug/`.

### From a Workspace Root

When run from a workspace root, jonesy analyzes all workspace member binaries:

```bash
cd my-workspace
cargo build
jonesy
```

### Analyzing a Specific Binary

Use `--bin` to analyze a specific binary file:

```bash
jonesy --bin target/debug/my-binary
```

### Analyzing Libraries

Jonesy can analyze Rust libraries built as dynamic libraries (`.dylib`):

```bash
jonesy --lib target/debug/libmy_lib.dylib
```

**Library Setup Requirements:**

For jonesy to analyze a library, it must be built as a `cdylib` with exported symbols:

1. Add `cdylib` to your crate types in `Cargo.toml`:
   ```toml
   [lib]
   crate-type = ["rlib", "cdylib"]
   ```

2. Mark functions to export with `#[no_mangle]`:
   ```rust
   #[unsafe(no_mangle)]
   pub fn my_library_function() {
       // ...
   }
   ```

3. Build and create dSYM:
   ```bash
   cargo build
   dsymutil target/debug/libmy_lib.dylib -o target/debug/libmy_lib.dSYM
   ```

**Why `cdylib` + `#[no_mangle]`?**

There are two ways to build a Rust dynamic library:

| Type     | Size   | `pub fn` exported?        | Analysis speed |
|----------|--------|---------------------------|----------------|
| `cdylib` | ~16KB  | No (needs `#[no_mangle]`) | Fast           |
| `dylib`  | ~1.4MB | Yes (automatic)           | Very slow      |

- **`cdylib`** creates a minimal C-compatible library. Only explicitly marked functions are exported; others are removed
  by dead code elimination. Analysis is fast because only your code is included.

- **`dylib`** creates a full Rust dynamic library including the standard library runtime. All `pub fn` are exported
  automatically, but the ~90x larger binary makes analysis impractical (minutes vs seconds).

**Other notes:**

- `.rlib` files (Rust static library archives) have limited support because panic symbols are unlinked references in
  object files
- The dSYM bundle provides debug symbols for source location information

## Command Line Options

```
Usage:
  jonesy[OPTIONS]
  jonesy[OPTIONS] --bin <path_to_binary>
  jonesy[OPTIONS] --lib <path_to_lib_object>

Options:
  --tree             Show full call tree instead of just crate code points
  --summary-only     Only show summary, not detailed panic points
  --config <path>    Path to a TOML config file for allow/deny rules
  --max-threads N    Maximum threads for parallel analysis (default: CPU count)
  --no-hyperlinks    Disable terminal hyperlinks (use plain absolute paths)
  --bin              Analyze a specific binary file
  --lib              Analyze a specific library object file
```

### `--tree`

By default, jonesy shows only the panic code points in your crate's source code. Use `--tree` to see the full call tree
from `rust_panic` up to your code:

```bash
jonesy --tree
```

Example output with `--tree`:

```
Full call tree:
__rustc::rust_panic
Called from: 'panic_with_hook' (source: library/std/src/panicking.rs:796)
    Called from: '{closure#0}' (source: library/std/src/panicking.rs:698)
        ...
            Called from: 'panic_fmt' (source: library/core/src/panicking.rs:55)
                Called from: 'main' (source: src/main.rs:8)
```

### `--summary-only`

Show only the summary without detailed panic point locations. Useful for CI pipelines or quick checks:

```bash
jonesy --summary-only
```

Example output:

```text
Summary:
  Project: my-app
  Root: /path/to/project
  Panic points: 5 in 2 file(s)
```

### `--no-hyperlinks`

When stdout is a terminal, jonesy outputs source file locations
as [OSC 8 terminal hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda), making paths
clickable in supported terminals (iTerm2, Kitty, WezTerm, VS Code terminal, and others). The link points to the full
file path while displaying a shorter relative path.

When output is piped or redirected (e.g., `jonesy> file.txt`), plain absolute paths are used automatically to avoid
escape sequences in logs or files.

If your terminal doesn't support OSC 8 hyperlinks (e.g. macOS Terminal.app), the escape sequences will be invisible and
the output will still be readable. However, if you prefer plain absolute paths even in an interactive terminal, use this
flag:

```bash
jonesy --no-hyperlinks
```

This outputs paths like `/Users/me/project/src/main.rs:42:1` instead of clickable hyperlinks.

### `--config`

Specify a custom TOML configuration file for allow/deny rules:

```bash
jonesy --config my-config.toml
```

See the [Configuration](#configuration) section for details on the config file format.

## Configuration

Jonesy supports configuring which panic causes to report (deny) or suppress (allow). This is useful for:

- Suppressing known-acceptable panics in your codebase
- Enforcing stricter rules (e.g. reporting drop panics)
- Per-project customization

### Configuration Cascade

Configuration is loaded in order of precedence (later overrides earlier):

1. **Code defaults** - `drop` and `unwind` panics are allowed; all others are denied
2. **Cargo.toml** - `[package.metadata.jonesy]` section
3. **jonesy.toml** - Project root config file
4. **`--config`** - Command-line override

### Panic Cause Identifiers

| ID              | Description                               | Default     | Clippy Lint |
|-----------------|-------------------------------------------|-------------|-------------|
| `panic`         | Explicit `panic!()` calls                 | denied      | `clippy::panic` |
| `bounds`        | Array/slice index out of bounds           | denied      | `clippy::indexing_slicing` |
| `overflow`      | Arithmetic overflow (add, sub, mul, etc.) | denied      | `clippy::arithmetic_side_effects` |
| `div_zero`      | Division by zero                          | denied      | `clippy::arithmetic_side_effects` |
| `unwrap`        | `unwrap()` on `None` or `Err`             | denied      | `clippy::unwrap_used` |
| `expect`        | `expect()` on `None` or `Err`             | denied      | `clippy::expect_used` |
| `assert`        | `assert!()` failures                      | denied      ||
| `debug_assert`  | `debug_assert!()` failures                | denied      ||
| `unreachable`   | `unreachable!()` reached                  | denied      | `clippy::unreachable` |
| `unimplemented` | `unimplemented!()` reached                | denied      | `clippy::unimplemented` |
| `todo`          | `todo!()` reached                         | denied      | `clippy::todo` |
| `drop`          | Panic during drop/cleanup                 | **allowed** ||
| `unwind`        | Panic in no-unwind context                | **allowed** ||
| `unknown`       | Unknown panic cause                       | denied      ||

Clippy lints are "restriction" lints (off by default). Enable in `Cargo.toml`:

```toml
[lints.clippy]
unwrap_used = "warn"
expect_used = "warn"
indexing_slicing = "warn"
panic = "warn"
```

Clippy's static analysis may produce false positives, while jonesy only reports actual panic paths in the compiled binary.

### jones.toml Format

Create a `jones.toml` file in your project root:

```toml
# Allow specific panic causes (suppress from output)
allow = ["drop", "unwind", "debug_assert"]

# Deny specific panic causes (report in output)
deny = ["todo", "unimplemented"]
```

### Cargo.toml Format

Add configuration to your `Cargo.toml` under `[package.metadata.jonesy]`:

```toml
[package]
name = "my-crate"
version = "0.1.0"

[package.metadata.jonesy]
allow = ["drop", "unwind"]
deny = ["todo"]
```

### Example: Strict Mode

To report all panic causes including drops:

```toml
# jonesy.toml
deny = ["drop", "unwind"]
```

### Example: Lenient Development Mode

To allow common development panics:

```toml
# jonesy.toml
allow = ["todo", "unimplemented", "debug_assert"]
```

## Exit Status

Jonesy exits with the number of panic code points found:

- `0` - No panics found (code "passed")
- `N` - N panic code points found

This makes it easy to use jonesy in CI pipelines:

```bash
jonesy || echo "Found potential panics!"
```

## Example Output

For a crate with multiple panic paths:

```text
Processing /path/to/target/debug/my-app
Using .dSYM bundle for debug info

Panic code points in crate:
 --> /path/to/src/main.rs:9:1 [explicit panic!() call]
     = help: Review if panic is intentional or add error handling
 --> /path/to/src/main.rs:13:1
     └──  --> /path/to/src/module/mod.rs:3:1
 --> /path/to/src/main.rs:16:1
     └──  --> /path/to/src/module/mod.rs:7:1 [unwrap() on None]
          = help: Use if let, match, unwrap_or, or ? operator instead

Summary:
  Project: my-app
  Root: /path/to
  Panic points: 5 in 2 file(s)
```

For a panic-free crate:

```text
Processing /path/to/target/debug/perfect
Using .dSYM bundle for debug info

No panics in crate

Summary:
  Project: perfect
  Root: /path/to
  Panic points: 0 in 0 file(s)
```

## Requirements

- macOS with ARM64 (Apple Silicon)—currently the only supported platform
- Debug symbols (build with `cargo build`, not release mode without debug info)

## Using on macOS

Jonesy needs DWARF debug information to map code addresses to source file locations. On macOS, Jonesy automatically
handles this for you:

### Automatic dSYM Generation

When no `.dSYM` bundle exists, Jonesy automatically runs `dsymutil` (if it is present) to generate one, if not it will
attempt (on macOS) to fall back to the "Debug Map" method.

in your project run:

```bash
cargo build
jonesy
```

Jonesy will output "Generated .dSYM bundle for debug info" when it creates one.

### Why is this needed?

By default, macOS Rust builds use Apple's "lazy" DWARF scheme:

- Debug info stays in object files (`target/debug/deps/*.o`)
- The final binary only contains a "debug map" pointing to those files
- `dsymutil` combines everything into a `.dSYM` bundle

Jonesy automatically runs `dsymutil` when needed, so you don't have to.

### Optional: Pre-generate dSYM in Cargo

If you want Cargo to create dSYM bundles during build (avoiding Jonesy's auto-generation), add to `Cargo.toml`:

```toml
[profile.dev]
split-debuginfo = "packed"
```

**Trade-off:** This slightly slows incremental builds because `dsymutil` runs on every build.

See [description.md](description.md) for detailed technical documentation.

## Limitations

1. **ARM64 only**: Currently only supports ARM64 binaries (uses `bl` instruction detection)
2. **Direct calls only**: Only detects direct function calls, not indirect calls through function pointers
3. **macOS/Mach-O**: Currently only supports Mach-O binaries with dSYM or embedded DWARF
4. **Debug builds recommended**: Optimized builds may inline functions, affecting accuracy

### Library-Only Analysis Limitations

When analyzing library-only crates (rlib) without binary entry points using `--lib`:

1. **Relocation-based detection**: Uses ARM64 branch relocations to find panic callers, which works differently from binary call tree analysis

2. **`todo!()` macro**: May not be detected due to compiler generating local symbol indirection instead of direct panic calls

3. **Conditional panics**: Panics inside conditional branches (e.g., `if condition { panic!() }`) may not be reliably detected if the code path isn't compiled into the object file

4. **Static libraries (`.a`)**: Have aggressive dead code elimination (DCE) that removes unreferenced functions. Library functions must be exported with `#[no_mangle]` to be analyzed

5. **Line number precision**: For calls to standard library functions (like `Option::unwrap`), the reported line number is the function definition rather than the exact call site within the function

### Detected Panic Types in Library Mode

The following panic patterns are detected in library-only analysis:
- `panic!()`, `assert!()`, `assert_eq!()`, `assert_ne!()`
- `debug_assert!()`, `debug_assert_eq!()`, `debug_assert_ne!()`
- `unreachable!()`, `unimplemented!()`
- `Option::unwrap()`, `Option::expect()`
- `Result::unwrap()`, `Result::expect()`, `Result::unwrap_err()`, `Result::expect_err()`
- Division by zero, arithmetic overflow, shift overflow
- Slice index out of bounds

See [SCENARIOS.md](SCENARIOS.md) for detailed documentation of all analysis scenarios, supported panic types, and implementation status.