Skip to content

Bytecode emission and Buffer management

hydrophobis edited this page Mar 25, 2025 · 1 revision

Overview

These functions provide utilities for handling bytecode emission. They define macros and functions for emitting byte values and 1-4 byte-sized integers, as well as managing the output buffer for the bytecode.


1. Macros for Emitting Data

  • #define u1(v)
    Macro to represent a 1-byte value as a uint8_t.

  • #define u2(v)
    Macro to represent a 2-byte value as an array of uint8_ts. It extracts the high and low bytes of the 16-bit value.

  • #define u4(v)
    Macro to represent a 4-byte value as an array of uint8_ts. It breaks the 32-bit value into four bytes.


2. Emission Functions

  • static void emit_byte(uint8_t b)
    Adds a single byte to the output buffer. If the buffer exceeds its size, it triggers an error.

  • static void emit_u1(uint8_t v)
    Emits a 1-byte value to the buffer.

  • static void emit_u2(uint16_t v)
    Emits a 2-byte value to the buffer.

  • static void emit_u4(uint32_t v)
    Emits a 4-byte value to the buffer.


3. Buffer Management

  • static size_t current_offset()
    Returns the current position in the output buffer.

  • static void patch_u2(size_t pos, uint16_t v)
    Updates a 2-byte value at a specific position in the buffer.

  • static void patch_u4(size_t pos, uint32_t v)
    Updates a 4-byte value at a specific position in the buffer.


Usage Example

emit_u1(0x01);  // Emits a 1-byte value
emit_u2(0x1234); // Emits a 2-byte value
emit_u4(0x12345678); // Emits a 4-byte value

size_t offset = current_offset(); // Get the current position in the buffer

patch_u2(offset, 0x5678); // Patches a 2-byte value at the specified offset

Clone this wiki locally