HeadlinesBriefing favicon HeadlinesBriefing.com

Bytecode to Source Line Mapping

Hacker News •
×

Mapping bytecode offsets back to source code lines is crucial for debugging. Initially, a simple O(n) memory solution stores line numbers for each byte, offering O(1) lookup. However, this is memory-intensive.

Run-length encoding reduces memory to O(r) (where r is the number of line runs) by storing line numbers and their byte counts. A linear scan for lookups takes O(r) time, leading to O(n²) disassembly. A cursor-based approach improves disassembly to O(n).

A more efficient method uses "starting offsets," storing pairs of (bytecode offset, source line). This allows for O(log r) lookups via binary search or O(n) sequential traversal using a cursor. This "starting offsets" structure offers flexibility for both random access and ordered processing.

Similar approaches are used in the JVM (using sorted starting offsets, though HotSpot may use linear search) and Lua (employing line number deltas with checkpoints). The problem is formally known as the static predecessor problem.