IndexCoreasmjit::CodeHolder

asmjit::CodeHolder Class Reference [¶]

Holds assembled code and data (including sections, labels, and relocation information).

CodeHolder connects emitters with their targets. It provides them interface that can be used to query information about the target environment (architecture, etc...) and API to create labels, sections, relocations, and to write data to a CodeBuffer, which is always part of Section. More than one emitter can be attached to a single CodeHolder instance at a time, which is used in practice

CodeHolder provides interface for all emitter types. Assemblers use CodeHolder to write into CodeBuffer, and higher level emitters like Builder and Compiler use CodeHolder to manage labels and sections so higher level code can be serialized to Assembler by BaseEmitter::finalize() and BaseBuilder::serializeTo().

In order to use CodeHolder, it must be first initialized by init(). After the CodeHolder has been successfully initialized it can be used to hold assembled code, sections, labels, relocations, and to attach / detach code emitters. After the end of code generation it can be used to query physical locations of labels and to relocate the assembled code into the right address.

CodeHolder Reusability

If you intend to generate a lot of code, or tiny code, it's advised to reuse CodeHolder and emitter instances. There are currently two ways of reusing CodeHolder and emitters - one is using CodeHolder::init() followed by CodeHolder::reset(), and another is initializing once by CodeHolder::init() and then reinitializing by CodeHolder::reinit(). The first strategy is shown below:

// All of them will be reused for code generation by using an 'init()/reset()' strategy.
Environment env = ...; // Environment to use, for example from JitRuntime.
CodeHolder code; // CodeHolder to reuse (all allocated memory will be held by it until it's destroyed).
x86::Compiler cc; // Emitter to reuse (for example x86::Compiler).
for (size_t i = 0; i < ...; i++) {
// Initialize the CodeHolder first.
code.init(env);
code.attach(&emitter);
[[code generation as usual]]
code.reset();
}

While this approach is good for many use-cases, there is even a faster strategy called reinitialization, which is provided by CodeHolder::reinit(). The idea of reinit is to reinitialize the CodeHolder into a state, which was achieved by initializing it by CodeHolder::init(), by optionally attaching Logger, ErrorHandler, and emitters of any kind. See an example below:

// All of them will be reused for code generation by using a 'reinit()' strategy.
Environment env = ...; // Environment to use, for example from JitRuntime.
CodeHolder code; // CodeHolder to reuse (all allocated memory will be held by it until it's destroyed).
x86::Compiler cc; // Emitter to reuse (for example x86::Compiler).
// Initialize the CodeHolder and attach emitters to it (attaching ErrorHandler is advised!)
code.init(env);
code.attach(&emitter);
for (size_t i = 0; i < ...; i++) {
[[code generation as usual]]
// Optionally you can start the loop with 'code.reinit()', but this is cleaner as it wipes out all intermediate
// states of CodeHolder and the attached emitters. It won't detach Logger, ErrorHandler, nor attached emitters.
code.reinit();
}
Note
CodeHolder has an ability to attach an ErrorHandler, however, the error handler is not triggered by CodeHolder itself, it's instead propagated to all emitters that attach to it.

Classes

Member Functions

Construction & Destruction
Attach & Detach
Memory Allocators
Code & Architecture
Attached Emitters
Logging
Error Handling
Code Buffer
Sections
Labels & Symbols
Relocations
Utilities

CodeHolder::CodeHolder(
const Support::Temporary* temporary = nullptr
)explicitnoexcept[1/2][¶]

Creates an uninitialized CodeHolder (you must init() it before it can be used).

An optional temporary argument can be used to initialize the first block of Zone that the CodeHolder uses into a temporary memory provided by the user.

CodeHolder::CodeHolder(
const Support::Temporary& temporary
)explicitnoexcept[2/2][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

CodeHolder::~CodeHolder()noexcept[¶]

Destroys the CodeHolder and frees all resources it has allocated.

bool CodeHolder::isInitialized() constnoexcept[¶]

Tests whether the CodeHolder has been initialized.

Emitters can be only attached to initialized CodeHolder instances.

Error CodeHolder::init(
const Environment& environment,
uint64_t baseAddress = Globals::kNoBaseAddress
)noexcept[1/2][¶]

Initializes CodeHolder to hold code described by the given environment and baseAddress.

Error CodeHolder::init(
const Environment& environment,
const CpuFeatures& cpuFeatures,
uint64_t baseAddress = Globals::kNoBaseAddress
)noexcept[2/2][¶]

Initializes CodeHolder to hold code described by the given environment, cpuFeatures, and baseAddress.

Error CodeHolder::reinit()noexcept[¶]

Reinitializes CodeHolder with the same environment, cpu features, and base address as it had, and notifies all attached emitters of reinitialization.

If the CodeHolder was not initialized, kErrorNotInitialized is returned.

Reinitialization is designed to be a faster alternative compared to reset() followed by init() chain. The purpose of reinitialization is a very quick reuse of CodeHolder and all attached emitters (most likely Assembler or Compiler) without paying the cost of complete initialization and then assignment of all the loggers, error handlers, and emitters.

Note
Semantically reinit() is the same as using reset() with ResetPolicy::kSoft parameter followed by init(), and then by attaching loggers, error handlers, and emitters that were attached previously. This means that after reinitialization you will get a clean and ready for use CodeHolder, which was initialized the same way as before.

void CodeHolder::reset()noexcept[¶]

Detaches all code-generators attached and resets the CodeHolder.

Error CodeHolder::attach(
BaseEmitter* emitter
)noexcept[¶]

Attaches an emitter to this CodeHolder.

Error CodeHolder::detach(
BaseEmitter* emitter
)noexcept[¶]

Detaches an emitter from this CodeHolder.

ZoneAllocator* CodeHolder::allocator() constnoexcept[¶]

Returns the allocator that the CodeHolder uses.

Note
This should be only used for AsmJit's purposes. Code holder uses arena allocator to allocate everything, so anything allocated through this allocator will be invalidated by CodeHolder::reset() or by CodeHolder's destructor.

const Environment& CodeHolder::environment() constnoexcept[¶]

Returns the target environment information.

Arch CodeHolder::arch() constnoexcept[¶]

Returns the target architecture.

SubArch CodeHolder::subArch() constnoexcept[¶]

Returns the target sub-architecture.

const CpuFeatures& CodeHolder::cpuFeatures() constnoexcept[¶]

Returns the minimum CPU features of the target architecture.

bool CodeHolder::hasBaseAddress() constnoexcept[¶]

Tests whether a static base-address is set.

uint64_t CodeHolder::baseAddress() constnoexcept[¶]

Returns a static base-address or Globals::kNoBaseAddress, if not set.

BaseEmitter* CodeHolder::attachedFirst()noexcept[¶]

Returns a vector of attached emitters.

Logger* CodeHolder::logger() constnoexcept[¶]

Returns the attached logger.

void CodeHolder::setLogger(
Logger* logger
)noexcept[¶]

Attaches a logger to CodeHolder and propagates it to all attached emitters.

void CodeHolder::resetLogger()noexcept[¶]

Resets the logger to none.

bool CodeHolder::hasErrorHandler() constnoexcept[¶]

Tests whether the CodeHolder has an attached error handler, see ErrorHandler.

ErrorHandler* CodeHolder::errorHandler() constnoexcept[¶]

Returns the attached error handler.

void CodeHolder::setErrorHandler(
ErrorHandler* errorHandler
)noexcept[¶]

Attach an error handler to this CodeHolder.

void CodeHolder::resetErrorHandler()noexcept[¶]

Resets the error handler to none.

Error CodeHolder::growBuffer(
size_t n
)noexcept[¶]

Makes sure that at least n bytes can be added to CodeHolder's buffer cb.

Note
The buffer cb must be managed by CodeHolder - otherwise the behavior of the function is undefined.

Error CodeHolder::reserveBuffer(
size_t n
)noexcept[¶]

Reserves the size of cb to at least n bytes.

Note
The buffer cb must be managed by CodeHolder - otherwise the behavior of the function is undefined.

const ZoneVector<Section*>& CodeHolder::sections() constnoexcept[¶]

Returns an array of Section* records.

const ZoneVector<Section*>& CodeHolder::sectionsByOrder() constnoexcept[¶]

Returns an array of Section* records sorted according to section order first, then section id.

uint32_t CodeHolder::sectionCount() constnoexcept[¶]

Returns the number of sections.

bool CodeHolder::isSectionValid(
uint32_t sectionId
) constnoexcept[¶]

Tests whether the given sectionId is valid.

Error CodeHolder::newSection(
Section** sectionOut,
const char* name,
size_t nameSize = SIZE_MAX,
uint32_t alignment = 1,
int32_t order = 0
)noexcept[¶]

Creates a new section and return its pointer in sectionOut.

Returns Error, does not report a possible error to ErrorHandler.

Section* CodeHolder::sectionById(
uint32_t sectionId
) constnoexcept[¶]

Returns a section entry of the given index.

Section* CodeHolder::sectionByName(
const char* name,
size_t nameSize = SIZE_MAX
) constnoexcept[¶]

Returns section-id that matches the given name.

If there is no such section Section::kInvalidId is returned.

Section* CodeHolder::textSection() constnoexcept[¶]

Returns '.text' section (section that commonly represents code).

Note
Text section is always the first section in CodeHolder::sections() array.

bool CodeHolder::hasAddressTable() constnoexcept[¶]

Tests whether '.addrtab' section exists.

Section* CodeHolder::addressTableSection() constnoexcept[¶]

Returns '.addrtab' section.

This section is used exclusively by AsmJit to store absolute 64-bit addresses that cannot be encoded in instructions like 'jmp' or 'call'.

Note
This section is created on demand, the returned pointer can be null.

Section* CodeHolder::ensureAddressTableSection()noexcept[¶]

Ensures that '.addrtab' section exists (creates it if it doesn't) and returns it.

Can return nullptr on out of memory condition.

Error CodeHolder::addAddressToAddressTable(
uint64_t address
)noexcept[¶]

Used to add an address to an address table.

This implicitly calls ensureAddressTableSection() and then creates AddressTableEntry that is inserted to _addressTableEntries. If the address already exists this operation does nothing as the same addresses use the same slot.

This function should be considered internal as it's used by assemblers to insert an absolute address into the address table. Inserting address into address table without creating a particular relocation entry makes no sense.

const ZoneVector<LabelEntry>& CodeHolder::labelEntries() constnoexcept[¶]

Returns array of LabelEntry records.

uint32_t CodeHolder::labelCount() constnoexcept[¶]

Returns number of labels created.

bool CodeHolder::isLabelValid(
uint32_t labelId
) constnoexcept[1/2][¶]

Tests whether the label having labelId is valid (i.e. created by newLabelId()).

bool CodeHolder::isLabelValid(
const Label& label
) constnoexcept[2/2][¶]

Tests whether the label is valid (i.e. created by newLabelId()).

bool CodeHolder::isLabelBound(
uint32_t labelId
) constnoexcept[1/2][¶]

Tests whether a label having labelId is already bound.

Returns false if the labelId is not valid.

bool CodeHolder::isLabelBound(
const Label& label
) constnoexcept[2/2][¶]

Tests whether the label is already bound.

Returns false if the label is not valid.

LabelEntry& CodeHolder::labelEntry(
uint32_t labelId
)noexcept[1/4][¶]

Returns LabelEntry of the given label identifier labelId (or label if you are using overloads).

Attention
The passed labelId must be valid as it's used as an index to _labelEntries[] array. In debug builds the array access uses an assertion, but such assertion is not present in release builds. To get whether a label is valid, check out CodeHolder::isLabelValid() function.

const LabelEntry& CodeHolder::labelEntry(
uint32_t labelId
) constnoexcept[2/4][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

LabelEntry& CodeHolder::labelEntry(
const Label& label
)noexcept[3/4][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

const LabelEntry& CodeHolder::labelEntry(
const Label& label
) constnoexcept[4/4][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

uint64_t CodeHolder::labelOffset(
uint32_t labelId
) constnoexcept[1/2][¶]

Returns offset of a Label by its labelId.

The offset returned is relative to the start of the section where the label is bound. Zero offset is returned for unbound labels, which is their initial offset value.

Attention
The passed labelId must be valid as it's used as an index to _labelEntries[] array. In debug builds the array access uses an assertion, but such assertion is not present in release builds. To get whether a label is valid, check out CodeHolder::isLabelValid() function.

uint64_t CodeHolder::labelOffset(
const Label& label
) constnoexcept[2/2][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

uint64_t CodeHolder::labelOffsetFromBase(
uint32_t labelId
) constnoexcept[1/2][¶]

Returns offset of a label by it's labelId relative to the base offset.

Attention
The passed labelId must be valid as it's used as an index to _labelEntries[] array. In debug builds the array access uses an assertion, but such assertion is not present in release builds. To get whether a label is valid, check out CodeHolder::isLabelValid() function.
Note
The offset of the section where the label is bound must be valid in order to use this function, otherwise the value returned will not be reliable. Typically, sections have offsets when they are flattened, see CodeHolder::flatten() function for more details.

uint64_t CodeHolder::labelOffsetFromBase(
const Label& label
) constnoexcept[2/2][¶]

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Error CodeHolder::newLabelId(
uint32_t* labelIdOut
)noexcept[¶]

Creates a new anonymous label and return its id in labelIdOut.

Returns Error, does not report error to ErrorHandler.

Error CodeHolder::newNamedLabelId(
uint32_t* labelIdOut,
const char* name,
size_t nameSize,
LabelType type,
uint32_t parentId = Globals::kInvalidId
)noexcept[¶]

Creates a new named LabelEntry of the given label type.

Parameters
labelIdOutWhere to store the created Label id.
nameThe name of the label.
nameSizeThe length of name argument, or SIZE_MAX if name is a null terminated string, which means that the CodeHolder will use strlen() to determine the length.
typeThe type of the label to create, see LabelType.
parentIdParent id of a local label, otherwise it must be Globals::kInvalidId.
Return values
Alwaysreturns Error, does not report a possible error to the attached ErrorHandler.

AsmJit has a support for local labels (LabelType::kLocal) which require a parent label id (parentId). The names of local labels can conflict with names of other local labels that have a different parent. In addition, AsmJit supports named anonymous labels, which are useful only for debugging purposes as the anonymous name will have a name, which will be formatted, but the label itself cannot be queried by such name.

Label CodeHolder::labelByName(
const char* name,
size_t nameSize = SIZE_MAX,
uint32_t parentId = Globals::kInvalidId
)noexcept[¶]

Returns a label by name.

If the named label doesn't a default constructed Label is returned, which has its id set to Globals::kInvalidId.

uint32_t CodeHolder::labelIdByName(
const char* name,
size_t nameSize = SIZE_MAX,
uint32_t parentId = Globals::kInvalidId
)noexcept[¶]

Returns a label id by name.

If the named label doesn't exist Globals::kInvalidId is returned.

bool CodeHolder::hasUnresolvedFixups() constnoexcept[¶]

Tests whether there are any unresolved fixups related to unbound labels.

size_t CodeHolder::unresolvedFixupCount() constnoexcept[¶]

Returns the number of unresolved fixups.

Fixup* CodeHolder::newFixup(
uint32_t sectionId,
size_t offset,
intptr_t rel,
const OffsetFormat& format
)noexcept[¶]

Creates a new label-link used to store information about yet unbound labels.

Returns null if the allocation failed.

Error CodeHolder::resolveCrossSectionFixups()noexcept[¶]

Resolves cross-section fixups associated with each label that was used as a destination in code of a different section.

It's only useful to people that use multiple sections as it will do nothing if the code only contains a single section in which cross-section fixups are not possible.

Error CodeHolder::bindLabel(
const Label& label,
uint32_t sectionId,
uint64_t offset
)noexcept[¶]

Binds a label to a given sectionId and offset (relative to start of the section).

This function is generally used by BaseAssembler::bind() to do the heavy lifting.

bool CodeHolder::hasRelocEntries() constnoexcept[¶]

Tests whether the code contains relocation entries.

const ZoneVector<RelocEntry*>& CodeHolder::relocEntries() constnoexcept[¶]

Returns array of RelocEntry* records.

RelocEntry* CodeHolder::relocEntry(
uint32_t id
) constnoexcept[¶]

Returns a RelocEntry of the given id.

Error CodeHolder::newRelocEntry(
RelocEntry** dst,
RelocType relocType
)noexcept[¶]

Creates a new relocation entry of type relocType.

Additional fields can be set after the relocation entry was created.

Error CodeHolder::flatten()noexcept[¶]

Flattens all sections by recalculating their offsets, starting at 0.

Note
This should never be called more than once.

size_t CodeHolder::codeSize() constnoexcept[¶]

Returns computed the size of code & data of all sections.

Note
All sections will be iterated over and the code size returned would represent the minimum code size of all combined sections after applying minimum alignment. Code size may decrease after calling flatten() and relocateToBase().

Error CodeHolder::relocateToBase(
uint64_t baseAddress,
RelocationSummary* summaryOut = nullptr
)noexcept[¶]

Relocates the code to the given baseAddress.

Parameters
baseAddressAbsolute base address where the code will be relocated to. Please note that nothing is copied to such base address, it's just an absolute value used by the relocation code to resolve all stored relocations.
summaryOutOptional argument that can be used to get back information about the relocation.
Note
This should never be called more than once.

Error CodeHolder::copySectionData(
void* dst,
size_t dstSize,
uint32_t sectionId,
)noexcept[¶]

Copies a single section into dst.

Error CodeHolder::copyFlattenedData(
void* dst,
size_t dstSize,
)noexcept[¶]

Copies all sections into dst.

This should only be used if the data was flattened and there are no gaps between the sections. The dstSize is always checked and the copy will never write anything outside the provided buffer.

Environment CodeHolder::_environment[¶]

Environment information.

CpuFeatures CodeHolder::_cpuFeatures[¶]

CPU features of the target architecture.

uint64_t CodeHolder::_baseAddress[¶]

Base address or Globals::kNoBaseAddress.

Logger* CodeHolder::_logger[¶]

Attached Logger, used by all consumers.

ErrorHandler* CodeHolder::_errorHandler[¶]

Attached ErrorHandler.

Zone CodeHolder::_zone[¶]

Code zone (used to allocate core structures).

ZoneAllocator CodeHolder::_allocator[¶]

Zone allocator, used to manage internal containers.

BaseEmitter* CodeHolder::_attachedFirst[¶]

First emitter attached to this CodeHolder (double-linked list).

BaseEmitter* CodeHolder::_attachedLast[¶]

Last emitter attached to this CodeHolder (double-linked list).

ZoneVector<Section*>CodeHolder::_sections[¶]

Section entries.

ZoneVector<Section*>CodeHolder::_sectionsByOrder[¶]

Section entries sorted by section order and then section id.

ZoneVector<LabelEntry>CodeHolder::_labelEntries[¶]

Label entries.

ZoneVector<RelocEntry*>CodeHolder::_relocations[¶]

Relocation entries.

ZoneHash<NamedLabelExtraData>CodeHolder::_namedLabels[¶]

Label name -> LabelEntry::ExtraData (only used by labels that have a name and are not anonymous).

Fixup* CodeHolder::_fixups[¶]

Unresolved fixups that are most likely references across sections.

ZonePool<Fixup>CodeHolder::_fixupDataPool[¶]

Pool containing Fixup instances for quickly recycling them.

size_t CodeHolder::_unresolvedFixupCount[¶]

Count of unresolved fixups of unbound labels (at the end of assembling this should be zero).

Section CodeHolder::_textSection[¶]

Text section - always one part of a CodeHolder itself.

Section* CodeHolder::_addressTableSection[¶]

Pointer to an address table section (or null if this section doesn't exist).

ZoneTree<AddressTableEntry>CodeHolder::_addressTableEntries[¶]

Address table entries.