Skip to content

Adding and managing fields and methods

hydrophobis edited this page Mar 25, 2025 · 1 revision

Overview

These functions manage the fields and methods sections of the Java class file. The fields section contains information about the variables, while the methods section contains details about the functions of the class.


1. Fields Section Management

  • void fields_start()
    Initializes the fields section. Reserves space for the fields_count and starts the counter at 0.

  • void fields_end()
    Finalizes the fields section by patching the total entry count at the reserved location.


2. Field Entry Functions

  • void field_info(uint16_t access_flags, uint16_t name_index, uint16_t descriptor_index)
    Adds a field entry with the specified access flags, name, and descriptor index. Increments the counter and starts the attributes section for the field.

  • void end_field_info()
    Finalizes the attributes for the current field.


3. Methods Section Management

  • void methods_start()
    Initializes the methods section. Reserves space for the methods_count and starts the counter at 0.

  • void methods_end()
    Finalizes the methods section by patching the total entry count at the reserved location.


4. Method Entry Functions

  • void method_info(uint16_t access_flags, uint16_t name_index, uint16_t descriptor_index)
    Adds a method entry with the specified access flags, name, and descriptor index. Increments the counter and starts the attributes section for the method.

  • void end_method_info()
    Finalizes the attributes for the current method.


5. Utility Functions

  • void patch_u2(size_t pos, uint16_t v)
    Updates a 2-byte value in the buffer (used to finalize fields_count and methods_count).

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


Usage Example

fields_start();
field_info(1 /* ACC_PUBLIC */, 5, 10); // Adds a field with access flags, name index, and descriptor index
end_field_info(); // Finalizes the field's attributes
fields_end();

methods_start();
method_info(ACC_PUBLIC | ACC_STATIC, 5, 10); // Adds a method with access flags, name index, and descriptor index
end_method_info(); // Finalizes the method's attributes
methods_end();

This will generate a class file with one field and one method entry.


Clone this wiki locally