Mirror from SNAPKITTYWEST: docs/BINARY_IR.md
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627# Binary IR Specification
**Normalized Intermediate Representation for BEAM Binary Analysis**
## Overview
The Binary IR (Intermediate Representation) is a stable, normalized format for representing BEAM binary structures. It provides a consistent way to analyze, compare, and reason about BEAM files across different OTP versions and compiler implementations.
## Design Principles
### 1. Offset PreservationEvery decoded field retains its original byte offset from the start of the file. This allows traceability and provenance tracking.
### 2. State DistinctionThe IR clearly distinguishes between four states:- **RAW**: Direct binary bytes, uninterpreted- **DECODED**: Structurally parsed with known formats- **NORMALIZED**: Implementation-independent representation- **SEMANTIC**: Inferred higher-level meaning
### 3. Provenance TrackingEvery object in the IR can be traced back to:- Original source code- AST nodes- Compiler artifacts- BEAM structures- Binary offsets
### 4. Version AwarenessThe IR handles different BEAM versions explicitly and rejects unsupported formats.
### 5. Fail-Closed DesignUnknown structures produce structured errors rather than guesses.
## IR Structure
```elixir%Forge.BinaryIR{ module: atom() | nil, # Module name version: String.t() | nil, # BEAM version sections: list(section()), # Parsed sections constants: list(constant()), # Constant pool functions: list(function()), # Function definitions metadata: map(), # Additional metadata hashes: %{atom() => binary()}, # Cryptographic hashes provenance: map(), # Provenance information warnings: list(String.t()) # Parsing warnings}```
## Section Representation
Each section contains parsed fields:
```elixir%{ name: atom(), # Section identifier offset: integer(), # Byte offset from file start length: integer(), # Section length in bytes fields: list(Field.t()), # Parsed fields in this section metadata: map() # Section-specific metadata}```
### Section Types
| Section | Description | Always Present ||---------|-------------|----------------|| `:code` | BEAM instructions | ✅ Yes || `:atoms` | Atom table | ✅ Yes || `:literals` | Literal constants | ✅ Yes || `:functions` | Function metadata | ✅ Yes || `:exports` | Exported functions | ✅ Yes || `:imports` | Imported functions | ✅ Yes || `:attribute` | Module attributes | ❌ No || `:debug_info` | Debug information | ❌ No || `:line` | Line numbers | ❌ No |
## Field Representation
Each field in a section is represented by `Forge.Binary.Field`:
```elixir%Forge.Binary.Field{ section: atom(), # Parent section offset: integer(), # Byte offset from file start length: integer(), # Field length in bytes bytes: binary(), # Raw binary data decoded: any(), # Decoded value normalized: any(), # Normalized representation semantic: any(), # Semantic interpretation state: state(), # Current state confidence: confidence(), # Confidence level endianness: endianness(), # Byte order encoding: atom() # Encoding type}```
### State Types
```elixir@type state :: :raw | :decoded | :normalized | :semantic```
### Confidence Levels
```elixir@type confidence :: :low | :medium | :high```
### Endianness
```elixir@type endianness :: :big | :little | :unknown```
## Constant Pool
Constants are extracted from the literals and atoms sections:
```elixir%{ type: atom(), # :atom, :integer, :float, :binary, :list, :tuple, :map value: any(), # The actual value offset: integer(), # Offset in the section index: integer(), # Index in the constant pool state: state(), # Current state confidence: confidence() # Confidence level}```
## Function Representation
Functions are represented in a normalized form:
```elixir%{ name: atom(), # Function name arity: integer(), # Function arity index: integer(), # Function index labels: list(atom()), # Label names instructions: list(instruction()), # Normalized instructions offsets: list(integer()), # Instruction offsets state: state(), # Current state confidence: confidence(), # Confidence level complexity: number(), # Cyclomatic complexity patterns: list(atom()) # Detected patterns}```
### Instruction Representation
Each instruction is normalized to a consistent format:
```elixir%{ opcode: atom(), # Opcode name args: list(any()), # Raw arguments normalized_args: list(map()), # Normalized operands offset: integer(), # Byte offset in code section label: String.t() | nil, # Label name (if any) comments: list(String.t()), # Analysis comments state: state(), # Current state confidence: confidence() # Confidence level}```
### Normalized Operand
```elixir%{ type: atom(), # :atom, :integer, :float, :label, :register, :literal, :unknown value: any(), # Operand value raw: any() # Original raw value}```
## Metadata
Additional metadata stored in the IR:
```elixir%{ compiler: String.t() | nil, # Compiler version source: String.t() | nil, # Source file md5: String.t() | nil, # MD5 checksum debug_info: boolean(), # Has debug info line_info: boolean(), # Has line info beam_size: integer(), # BEAM file size beam_path: String.t() | nil # Path to BEAM file}```
## Hashes
Cryptographic hashes for integrity verification:
```elixir%{ :beam_file => binary(), # SHA-256 of the entire BEAM file :source => binary(), # SHA-256 of the source code (if available) :ast => binary(), # SHA-256 of the AST :forms => binary(), # SHA-256 of the Erlang forms :ir => binary() # SHA-256 of this IR itself}```
## Provenance
Provenance chain information:
```elixir%{ artifact_id: String.t(), # Unique artifact identifier beam_path: String.t(), # Path to BEAM file timestamp: DateTime.t(), # Creation timestamp beam_size: integer(), # File size stages: %{ # Hashes for each stage :source => binary(), :ast => binary(), :quoted => binary(), :erlang_forms => binary(), :beam => binary(), :binary_ir => binary() }, chain_hash: binary() # Combined hash of all stages}```
## Example IR
```elixir%Forge.BinaryIR{ module: :elixir_forge_example, version: "C", sections: [ %{ name: :code, offset: 56, length: 256, fields: [ %Forge.Binary.Field{ section: :code, offset: 56, length: 4, bytes: <<0, 1, 0, 0>>, decoded: {:allocate, 1, 0}, normalized: %{opcode: :allocate, arity: 1, live: 0}, semantic: %{type: :stack_operation, operation: :allocate}, state: :normalized, confidence: :high, endianness: :big, encoding: :instruction } ], metadata: %{instruction_count: 64} }, %{ name: :atoms, offset: 312, length: 32, fields: [ %Forge.Binary.Field{ section: :atoms, offset: 312, length: 4, bytes: <<"solve\0">>, decoded: :solve, normalized: %{type: :atom, value: :solve, index: 0}, semantic: %{type: :function_name, name: :solve}, state: :normalized, confidence: :high, endianness: :big, encoding: :atom } ], metadata: %{atom_count: 8} } ], constants: [ %{type: :atom, value: :solve, offset: 312, index: 0, state: :decoded, confidence: :high}, %{type: :integer, value: 42, offset: 400, index: 1, state: :decoded, confidence: :high} ], functions: [ %{ name: :solve, arity: 1, index: 0, labels: [:start], instructions: [ %{ opcode: :allocate, args: [1, 0], normalized_args: [ %{type: :integer, value: 1, raw: 1}, %{type: :integer, value: 0, raw: 0} ], offset: 56, label: nil, comments: ["Allocate stack frame for 1 argument"], state: :normalized, confidence: :high } ], offsets: [56, 60, 64, 68, 72], state: :normalized, confidence: :high, complexity: 1.0, patterns: [:function_call, :stack_operation] } ], metadata: %{ compiler: "Elixir 1.14.0", source: "example.ex", md5: "abc123...", debug_info: false, line_info: false, beam_size: 1024 }, hashes: %{ :beam_file => <<...>>, :ir => <<...>> }, provenance: %{ artifact_id: "abc123-2024-01-01-123456", beam_path: "example.beam", timestamp: ~U[2024-01-01 12:00:00Z], beam_size: 1024, stages: %{ :source => <<...>>, :beam => <<...>> }, chain_hash: <<...>> }, warnings: []}```
## IR Generation Process
### Step 1: Parse BEAM File
```elixir# Read the BEAM file{:ok, metadata} = Forge.Beam.read("module.beam")```
### Step 2: Create IR Skeleton
```elixirir = %{ module: metadata.module, version: metadata.version, sections: [], constants: [], functions: [], metadata: %{ compiler: metadata.compiler, source: metadata.source, md5: metadata.md5, debug_info: metadata.debug_info, line_info: metadata.line_info, beam_size: metadata.raw_size }, hashes: %{}, provenance: %{}, warnings: []}```
### Step 3: Add Sections
For each section in the BEAM file:
```elixirir = add_section(ir, :code, metadata.section_offsets[:code], metadata)ir = add_section(ir, :atoms, metadata.section_offsets[:atoms], metadata)ir = add_section(ir, :literals, metadata.section_offsets[:literals], metadata)```
### Step 4: Add Constants
Extract constants from atoms and literals:
```elixirir = add_atoms_as_constants(ir, metadata.atoms || [], metadata.section_offsets[:atoms])ir = add_literals_as_constants(ir, metadata.literals || [], metadata.section_offsets[:literals])```
### Step 5: Add Functions
Normalize function definitions:
```elixirir = add_functions(ir, metadata.functions || [])```
### Step 6: Add Hashes
Compute cryptographic hashes:
```elixirir = add_beam_hash(ir, "module.beam")ir = add_source_hash(ir, "module.ex") # If available```
### Step 7: Add Provenance
Build the provenance chain:
```elixirir = add_provenance(ir, "module.ex", "module.beam")```
## IR Normalization
### Opcode Normalization
BEAM opcodes are normalized to a consistent naming scheme:
```elixir# OTP 24 uses :call, OTP 25 might use :call_local# Both are normalized to :call
defp normalize_opcode(:call), do: :calldefp normalize_opcode(:call_local), do: :call```
### Operand Normalization
Operands are normalized to a consistent format:
```elixir# Atom operandsdefp normalize_operand(atom) when is_atom(atom), do: %{type: :atom, value: atom, raw: atom}
# Integer operandsdefp normalize_operand(int) when is_integer(int), do: %{type: :integer, value: int, raw: int}
# Label operandsdefp normalize_operand(label) when is_binary(label), do: %{type: :label, value: label, raw: label}```
### Instruction Normalization
Instructions are normalized to include:- Consistent opcode names- Normalized operands- Preserved offsets- Confidence levels
## IR Comparison
Two IRs can be compared to determine structural similarity:
```elixir# Exact comparisonir1 == ir2
# Structural comparison (ignoring offsets)Forge.BinaryIR.structurally_equal?(ir1, ir2)
# Semantic comparison (ignoring implementation details)Forge.BinaryIR.semantically_equal?(ir1, ir2)```
### Structural Comparison
Compares:- Module name- Function names and arities- Instruction opcodes and operands- Constant values
Ignores:- Byte offsets- Label names- Function order
### Semantic Comparison
Compares:- Function semantics- Pattern usage- Control flow structure
Ignores:- Exact opcode sequences- Register allocations- Stack operations
## IR Serialization
The IR can be serialized to multiple formats:
### JSON
```elixirForge.BinaryIR.to_json(ir)```
### JSONL (JSON Lines)
```elixirForge.BinaryIR.to_jsonl(ir)```
### Markdown
```elixirForge.BinaryIR.to_markdown(ir)```
### Binary
```elixirForge.BinaryIR.to_binary(ir)```
## IR Versioning
The IR format is versioned to handle changes in BEAM formats:
```elixir@ir_version "1.0"```
Version history:
| Version | Date | Description ||---------|------|-------------|| 1.0 | 2024-01 | Initial version |
## IR Validation
The IR can be validated for correctness:
```elixir# Validate IR structureForge.BinaryIR.validate(ir)
# Validate IR against BEAM fileForge.BinaryIR.validate_against_beam(ir, "module.beam")
# Check for missing informationForge.BinaryIR.check_completeness(ir)```
## IR Transformations
The IR can be transformed for various purposes:
### Filter by Confidence
```elixir# Get only high-confidence elementsForge.BinaryIR.filter_by_confidence(ir, :high)```
### Filter by State
```elixir# Get only decoded elementsForge.BinaryIR.filter_by_state(ir, :decoded)```
### Extract Subset
```elixir# Extract a specific functionForge.BinaryIR.extract_function(ir, :solve, 1)
# Extract a specific sectionForge.BinaryIR.extract_section(ir, :code)```
## IR Optimization
The IR can be optimized for storage or transmission:
```elixir# Remove raw bytes (retain only decoded information)Forge.BinaryIR.strip_bytes(ir)
# Remove debug informationForge.BinaryIR.strip_debug(ir)
# Compress IRForge.BinaryIR.compress(ir)```
## Performance
### IR Generation Time
| BEAM Size | IR Generation Time ||-----------|---------------------|| < 1KB | < 1ms || 1-10KB | 1-10ms || 10-100KB | 10-100ms || > 100KB | > 100ms |
### IR Size
| BEAM Size | IR Size ||-----------|---------|| 1KB | ~2-3KB || 10KB | ~20-30KB || 100KB | ~200-300KB |
## Best Practices
1. **Always preserve offsets** for traceability2. **Use normalized opcodes** for cross-version compatibility3. **Mark confidence levels** for all inferred information4. **Validate IRs** after generation5. **Hash IRs** for integrity verification6. **Store provenance** for all artifacts
## References
- [BEAM File Format Documentation](https://erlang.org/doc/apps/erts/erl_ext_dist.html)- [BEAM Instruction Set](https://erlang.org/doc/tutorial/c_port.html)- [Erlang System Documentation](https://erlang.org/doc)docs/BINARY_IR.mdAdded+627