Machine Code Generation for C++
Error handler can be used to override the default behavior of error handling.
It's available to all classes that inherit
BaseEmitter. Override ErrorHandler::handleError() to implement your own error handler.
The following use-cases are supported:
longjmp(). Asmjit always puts Assembler, Builder and Compiler to a consistent state before calling handleError(), so
longjmp()can be used without issues to cancel the code-generation if an error occurred. This method can be used if exception handling in your project is turned off and you still want some comfort. In most cases it should be safe as AsmJit uses Zone memory and the ownership of memory it allocates always ends with the instance that allocated it. If using this approach please never jump outside the life-time of CodeHolder and BaseEmitter.
If error happens during instruction emitting / encoding the assembler behaves transactionally - the output buffer won't advance if encoding failed, thus either a fully encoded instruction or nothing is emitted. The error handling shown above is useful, but it's still not the best way of dealing with errors in AsmJit. The following example shows how to use exception handling to handle errors in a more C++ way:
If C++ exceptions are not what you like or your project turns off them completely there is still a way of reducing the error handling to a minimum by using a standard setjmp/longjmp approach. AsmJit is exception-safe and cleans up everything before calling the ErrorHandler, so any approach is safe. You can simply jump from the error handler without causing any side-effects or memory leaks. The following example demonstrates how it could be done:
Creates a new
Error handler (must be reimplemented).
Error handler is called after an error happened and before it's propagated to the caller. There are multiple ways how the error handler can be used:
longjmp(). This is for users that don't use exceptions and want customized error handling.
longjmp(). Asmjit always puts
BaseEmitterto a consistent state before calling
longjmp()can be used without any issues to cancel the code generation if an error occurred. There is no difference between exceptions and
longjmp()from AsmJit's perspective, however, never jump outside of
BaseEmitterscope as you would leak memory.