Skip to content

Class creation

hydrophobis edited this page Mar 25, 2025 · 2 revisions

Creating a class file

emit_class_header()

  • Called first
  • Emits the Java class file magic number (0xCAFEBABE).
  • Sets the class file version to Java 8 (minor_version = 0, major_version = 52).


Fields Section Management

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

  • 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.

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


Methods Section Management

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

  • 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.

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


Bytecode

  • void bytecode_start()
    Initializes the bytecode section. Reserves space for the bytecode_length and sets the offset for the bytecode.

  • void ldc(1) Loads the first constant onto the stack

  • void bytecode_end()
    Finalizes the bytecode section by patching the bytecode_length at the reserved location.


Code Attribute Handling

code_attribute_start(uint16_t name_index, uint16_t max_stack, uint16_t max_locals)

  • Starts a code attribute with the method's name and stack/locals limits.
  • Begins bytecode emission with bytecode_start().

code_attribute_end()

  • Ends bytecode emission with bytecode_end().
  • Emits 0 for exception table length and attributes count.
  • Ends the attribute with attribute_end().

emit_class_footer(uint16_t this_class, uint8_t this_class_flags, uint16_t super_class)

  • Called last
  • Sets the access flags to the given flag integer.
  • References the class and its superclass (this_class and super_class).

Clone this wiki locally