Skip to content

Constant pool management

hydrophobis edited this page Mar 25, 2025 · 1 revision

Overview

These functions generate the constant pool for the Java class file.


1. Initialization & Finalization

  • void constant_pool_start()
    Initializes the constant pool. Reserves space for the constant_pool_count and starts indexing at 1.

  • void constant_pool_end()
    Finalizes the constant pool by patching the total entry count at the reserved location.


2. Constant Pool Entry Functions

Each function adds an entry and increments the counter.

  • UTF-8 Stringconstant_utf8(const char *string)
    Stores a UTF-8 encoded string.

  • Integerconstant_integer(uint32_t value)
    Stores a 4-byte integer.

  • Floatconstant_float(uint32_t value)
    Stores a 4-byte floating-point number.

  • Longconstant_long(uint64_t value)
    Stores an 8-byte long integer (split into two 4-byte chunks).

  • Doubleconstant_double(uint64_t value)
    Stores an 8-byte double-precision float (split into two 4-byte chunks).

  • Class Referenceconstant_class(uint16_t name_index)
    Stores a reference to a class (index to a UTF-8 string in the pool).

  • String Referenceconstant_string(uint16_t string_index)
    Stores a reference to a string (index to a UTF-8 string in the pool).

  • Field Referenceconstant_fieldref(uint16_t class_index, uint16_t name_and_type_index)
    Stores a reference to a field (links a class to a name-and-type pair).

  • Method Referenceconstant_methodref(uint16_t class_index, uint16_t name_and_type_index)
    Stores a reference to a method (links a class to a name-and-type pair).

  • Interface Method Referenceconstant_interfacemethodref(uint16_t class_index, uint16_t name_and_type_index)
    Stores a reference to an interface method.

  • Name and Type Descriptorconstant_nameandtype(uint16_t name_index, uint16_t descriptor_index)
    Stores a name and type pair (used in method/field references).


3. Utility Functions

  • void increment_cp_counter()
    Increases the constant pool counter.

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

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


Usage Example

constant_pool_start();
constant_utf8("System");
constant_integer(42);
constant_class(1); // Refers to first UTF-8 entry
constant_pool_end();

This will create a constant pool with a UTF-8 string, an integer, and a class reference.

Clone this wiki locally