Skip to content

Instantly share code, notes, and snippets.

@mistymntncop
Last active October 12, 2023 11:51
Show Gist options
  • Save mistymntncop/47354fdcc0a34b55ca968498760707fe to your computer and use it in GitHub Desktop.
Save mistymntncop/47354fdcc0a34b55ca968498760707fe to your computer and use it in GitHub Desktop.
DWARF has a clever (too clever?) VM representation for source line to asm mapping.
VM has state which represents virtual program and source line counters.
The DW_LNS_advance_pc instruction advances the program counter while the DW_LNS_advance_line instruction
advances the line counter. Both these instructions encode the "advance amount" value as a variably sized immediate operand.
The DW_LNS_copy instructions tells us that current VM pc and source counter states correspond together
both counter values can be copied to a array of line numbers and assembly addresses. When the VM reads a byte from the
instruction stream it compares this value with a VM specified "opcode base" variable. If the value is below the "opcode base"
then it represents an opcode for an instruction. If the value is above the "opcode base" then it represents the operand for
an implicit "instruction". This special implicit "instruction" advances both the program and source line counters at once
using this single byte value. But how can you represent both advancement values in one byte ?
Simplified - Imagine a 16x16 (sqrt(256) = 16) square grid where each cell unqiuely contains a value from 0-255 (left to right then down - like a book).
You can think of this value as a coordinate in the grid. Using this value you can find the position of the x and y axis
in grid for this value. E.g. x = (value % 16), y = (value / 16). These "x and y" values are the advancement amounts for
the program and source line counters. By using this special "instruction" for the majority of cases it can save alot of
space as we encode the operation of the DW_LNS_advance_line, DW_LNS_advance_pc and DW_LNS_copy instructions in a single
byte. For cases where the advancement amount does not fit within a byte you can always use the explicit instructions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment