|
| 1 | +# Debugging |
| 2 | + |
| 3 | +## Memory Management Issues |
| 4 | + |
| 5 | +When working with JNI, you might encounter memory management errors such as |
| 6 | +`DoubleReleaseError` or `UseAfterReleaseError`. These occur when you try to |
| 7 | +release an object that has already been released, or use an object after it has |
| 8 | +been released. |
| 9 | + |
| 10 | +By default, these errors might not provide enough context to identify where the |
| 11 | +object was originally released. To help with debugging, `package:jni` provides a |
| 12 | +flag to capture the stack trace when an object is released. |
| 13 | + |
| 14 | +### `Jni.captureStackTraceOnRelease` |
| 15 | + |
| 16 | +You can enable stack trace capturing by setting |
| 17 | +`Jni.captureStackTraceOnRelease = true`. |
| 18 | + |
| 19 | +```dart |
| 20 | +import 'package:jni/jni.dart'; |
| 21 | +
|
| 22 | +void main() { |
| 23 | + // ... Initialization code ... |
| 24 | + // Enable stack trace capturing for debugging |
| 25 | + Jni.captureStackTraceOnRelease = true; |
| 26 | +
|
| 27 | + final s = 'hello'.toJString(); |
| 28 | + s.release(); // The stack trace is captured here. |
| 29 | +
|
| 30 | + // ... |
| 31 | +
|
| 32 | + s.release(); // Throws DoubleReleaseError |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +When this flag is enabled, the `DoubleReleaseError` or `UseAfterReleaseError` |
| 37 | +will include the stack trace of the call that originally released the object. |
| 38 | + |
| 39 | +**Example Output:** |
| 40 | + |
| 41 | +``` |
| 42 | +Bad state: Double release error |
| 43 | +Object was released at: |
| 44 | +#0 ... |
| 45 | +... |
| 46 | +``` |
| 47 | + |
| 48 | +> [!NOTE] Capturing stack traces has a performance cost and is implemented using |
| 49 | +> `assert`. Therefore, it **only works in debug mode** (when assertions are |
| 50 | +> enabled). It defaults to `false`. |
| 51 | +
|
| 52 | +### Arena Stack Traces |
| 53 | + |
| 54 | +If you use `using` (from `package:ffi`) and `releasedBy`, the stack trace will |
| 55 | +also include where the object was registered to be released. |
| 56 | + |
| 57 | +```dart |
| 58 | +using((arena) { |
| 59 | + final s = 'hello'.toJString()..releasedBy(arena); |
| 60 | + // ... |
| 61 | +}); |
| 62 | +``` |
| 63 | + |
| 64 | +If `DoubleReleaseError` or `UseAfterReleaseError` occurs, the output will show |
| 65 | +both where it was released and where it was registered in the arena. |
0 commit comments