Functions
-
int atom_are_equals(AtomString a, AtomString b)
Check for equality two AtomStrings.
Returns 1 if two atom strings are equal, 0 otherwise. This function doesn’t behave like strcmp.
- Parameters:
a – first atom string to be compared.
b – second atom string to be compared.
- Returns:
1 if they are equals, 0 otherwise.
-
static inline const void *atom_string_data(AtomString atom_str)
Gets actual atom string data.
Returns actual atom string data, which is not a \0 terminated C string.
- Parameters:
atom_str – an AtomString pointer.
- Returns:
const pointer to string data (chars array).
-
static inline size_t atom_string_len(AtomString atom_str)
Returns the length of an atom string in bytes.
Returns the length stored in the AtomString (which means that length is not computed).
- Parameters:
atom_str – the atom string.
- Returns:
the specified atom string length.
-
void atom_string_to_c(AtomString atom_string, char *buf, size_t bufsize)
Gets a C string from an AtomString.
Copies the atom string data to a buffer and makes it null terminated.
- Parameters:
atom_string – that will be converted to a C string.
buf – the buffer where the C string will be written.
bufsize – available buf size.
-
void atom_write_mfa(char *buf, size_t buf_size, AtomString module, AtomString function, unsigned int arity)
Write module:function/arity to the supplied buffer.
Write module:function/arity to the supplied buffer. This function will abort if the written module, function, and arity are longer than the supplied buffer size.
- Parameters:
buf – the buffer to write into
buf_size – the amount of room in the buffer
module – the module name
function – the function name
arity – the function arity
-
int avmpack_find_section_by_flag(const void *avmpack_binary, uint32_t flags_mask, const void **ptr, uint32_t *size, const char **name)
Finds an AVM Pack section that has certain flags set.
Finds an AVM Pack section that has certain flags set and returns a pointer to it, its size and its name.
- Parameters:
avmpack_binary – a pointer to valid AVM Pack file data.
flags_mask – that will be matched against file sections.
ptr – will point to the found file section.
size – will be set to the file section size that has been found, if the section has not been found it will not be updated.
name – the section name, as defined in the module header.
- Returns:
1 if the file section has been found, 0 otherwise.
-
int avmpack_find_section_by_name(const void *avmpack_binary, const char *name, const void **ptr, uint32_t *size)
Finds an AVM Pack section that has certain name.
Finds an AVM Pack section with a certain name and returns a pointer to it and its size.
- Parameters:
avmpack_binary – a pointer to valid AVM Pack file data.
name – the file section name that will be searched.
ptr – will point to the found file section, if the section has not been found it will not be updated.
size – will be set to the file section size that has been found, if the section has not been found it will not be updated.
- Returns:
1 if the file section has been found, 0 otherwise.
-
void *avmpack_fold(void *accum, const void *avmpack_binary, avmpack_fold_fun fold_fun)
Fold over all the sections in an AVM Pack.
This function will call the callback on each section of the AVM Pack, passing in the current section of each module in the AVM binary to the supplied fold function.
- Parameters:
accum – The accumulator supplied by the application.
avmpack_binary – a pointer to an AVM Pack binary.
fold_fun – function that will be called for each AVM section.
-
int avmpack_is_valid(const void *avmpack_binary, uint32_t size)
Returns 1 if the pointed binary is a valid AVM Pack.
Returns if the pointed binary is a valid AVM Pack binary or not.
- Parameters:
avmpack_binary – a pointer to an AVM Pack binary.
size – the size of AVM Pack binary.
- Returns:
1 if it is a valid AVM Pack binary, 0 otherwise.
-
static inline void bitstring_copy_bits(uint8_t *dst, size_t bits_offset, const uint8_t *src, size_t bits_count)
Copy bits_count bits from src to dst[bits_offset..].
- Parameters:
dst – destination buffer
bits_offset – offset in bits in destination buffer
src – source buffer
bits_count – number of bits
-
void bitstring_copy_bits_incomplete_bytes(uint8_t *dst, size_t bits_offset, const uint8_t *src, size_t bits_count)
Copy bits_count bits from src to dst[bits_offset..].
Called by bitstring_copy_bits when bytes are not complete.
- Parameters:
dst – destination buffer
bits_offset – offset in bits in destination buffer
src – source buffer
bits_count – number of bits
-
static inline bool bitstring_insert_utf16(term dst_bin, size_t offset, uint32_t c, enum BitstringFlags bs_flags, size_t *out_size)
Insert a character in UTF-&§ format.
- Parameters:
dst_bin – binary to insert to
offset – offset, in bits, to where to insert the character
c – character to encode
bs_flags – flags to encode the character (undefined/little/big/native)
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline bool bitstring_insert_utf32(term dst_bin, size_t offset, uint32_t c, enum BitstringFlags bs_flags)
Insert a character in UTF-32 format.
- Parameters:
dst_bin – binary to insert to
offset – offset, in bits, to where to insert the character
c – character to encode
bs_flags – flags to encode the character (undefined/little/big/native)
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline bool bitstring_insert_utf8(term dst_bin, size_t offset, uint32_t c, size_t *out_size)
Insert a character in UTF-8 format.
- Parameters:
dst_bin – binary to insert to
offset – offset, in bits, to where to insert the character
c – character to encode
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline bool bitstring_match_utf16(term src_bin, size_t offset, int32_t *c, size_t *out_size, enum BitstringFlags bs_flags)
Match a character in UTF-16 format.
- Parameters:
src_bin – binary to match against
offset – offset, in bits, to where to start to match the character
c – int to decode to
bs_flags – flags to decode the character (undefined/little/big/native)
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if src_bin at offset is not a valid unicode character
-
static inline bool bitstring_match_utf32(term src_bin, size_t offset, int32_t *c, enum BitstringFlags bs_flags)
Match a character in UTF-32 format.
- Parameters:
src_bin – binary to match against
offset – offset, in bits, to where to start to match the character
c – int to decode to
bs_flags – flags to decode the character (undefined/little/big/native)
- Returns:
true
if encoding was successful,false
if src_bin at offset is not a valid unicode character
-
static inline bool bitstring_match_utf8(term src_bin, size_t offset, uint32_t *c, size_t *out_size)
Match a character in UTF-8 format.
- Parameters:
src_bin – binary to match against
offset – offset, in bits, to where to start to match the character
c – int to decode to
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if src_bin at offset is not a valid unicode character
-
bool bitstring_utf16_decode(const uint8_t *buf, size_t len, int32_t *c, size_t *out_size, enum BitstringFlags bs_flags)
Decode a character from UTF-16.
- Parameters:
c – int value to decode to
buf – the buffer froom which to decode the sring to or NULL to only compute the size.
len – the length (in bytes) of the bytes in buf
bs_flags – flags to decode the character (undefined/little/big/native)
out_size – the size in bytes, on output (if not NULL)
- Returns:
true
if decoding was successful,false
if character starting at buf is not a valid unicode character
-
bool bitstring_utf16_encode(uint32_t c, uint8_t *buf, enum BitstringFlags bs_flags, size_t *out_size)
Encode a character to UTF-16.
- Parameters:
c – character to encode
buf – the buffer to encode the character to or NULL to only compute the size.
bs_flags – flags to encode the character (undefined/little/big/native)
out_size – the size in bytes, on output (if not NULL)
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline bool bitstring_utf16_size(uint32_t c, size_t *out_size)
Compute the size of a unicode character when UTF-16 encoded.
- Parameters:
c – character to encode
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
bool bitstring_utf32_decode(const uint8_t *buf, size_t len, int32_t *c, enum BitstringFlags bs_flags)
Decode a character from UTF-32.
- Parameters:
c – int value to decode to
buf – the buffer froom which to decode the sring to or NULL to only compute the size.
len – the length (in bytes) of the bytes in buf
bs_flags – flags to decode the character (undefined/little/big/native)
- Returns:
true
if decoding was successful,false
if character starting at buf is not a valid unicode character
-
bool bitstring_utf32_encode(uint32_t c, uint8_t *buf, enum BitstringFlags bs_flags)
Encode a character to UTF-32.
- Parameters:
c – character to encode
buf – the buffer to encode the character
bs_flags – flags to encode the character (undefined/little/big/native)
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
enum UnicodeTransformDecodeResult bitstring_utf8_decode(const uint8_t *buf, size_t len, uint32_t *c, size_t *out_size)
Decode a character from UTF-8.
- Parameters:
buf – the buffer from which to decode the string
len – the length (in bytes) of the bytes in buf
c – int value to decode to or NULL to only compute the size.
out_size – the size in bytes, on output (if not NULL)
- Returns:
UnicodeTransformDecodeSuccess
if decoding was successful,UnicodeTransformDecodeFail
if character starting at buf is not a valid unicode character orUnicodeTransformDecodeIncomplete
if character starting at buf is a valid but incomplete transformation
-
bool bitstring_utf8_encode(uint32_t c, uint8_t *buf, size_t *out_size)
Encode a character to UTF-8.
- Parameters:
c – character to encode
buf – the buffer to encode the sring to or NULL to only compute the size.
out_size – the size in bytes, on output (if not NULL)
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline bool bitstring_utf8_size(uint32_t c, size_t *out_size)
Compute the size of a character when UTF-8 encoded.
- Parameters:
c – character to encode
out_size – the size in bytes, on output
- Returns:
true
if encoding was successful,false
if c is not a valid unicode character
-
static inline size_t context_avail_free_memory(const Context *ctx)
Returns available free memory in term units.
Returns the number of terms that can fit either on the heap.
- Parameters:
ctx – a valid context.
- Returns:
available free memory that is avail_size_in_bytes / sizeof(term).
-
static inline void context_clean_registers(Context *ctx, int live)
Cleans up unused registers.
Sets to NIL unused registers, x[0] - x[live - 1] will not be overwritten.
- Parameters:
ctx – a valid context
live – number of used registers
-
void context_destroy(Context *c)
Destroys a context.
Frees context resources and memory and removes it from the processes table. This should be called from the scheduler only. To actually delete a context that was created with context_new, use scheduler_terminate.
- Parameters:
c – the context that will be destroyed.
-
static inline void context_ensure_fpregs(Context *c)
Ensure we have FP registers, allocating them if necessary.
- Parameters:
c – context fo allocate FP registers for
-
int context_execute_loop(Context *ctx, Module *mod, const char *function_name, int arity)
Starts executing a function.
Start executing bytecode for the specified function, this function will block until it terminates. The outcome is saved to x[0] register.
- Parameters:
ctx – the context that will be used to run the specified functions, x registers must be set to function arguments.
mod – the module name C string.
function_name – the function name C string.
arity – the function arity (number of arguments that are required).
- Returns:
1 if an error occurred, otherwise 0 is always returned.
-
static inline int context_get_flags(Context *ctx, int mask)
Get flags on a given context.
- Parameters:
ctx – the context to get flags on.
mask – the mask to apply on flags
-
bool context_get_process_info(Context *ctx, term *out, term atom_key)
Get process information.
- Parameters:
ctx – the context being executed
out – the answer term
atom_key – the key representing the info to get
- Returns:
true
if successful,false
in case of an error in which case *out is filled with an exception atom
-
static inline int context_is_port_driver(const Context *ctx)
Returns 1 if the context is a port driver.
Checks if the given context has a native_handler or not.
- Parameters:
ctx – a valid context
- Returns:
1 if ctx is a port driver, otherwise 0 is returned.
-
static inline bool context_is_term_equal_to_atom_string(Context *ctx, term atom_a, AtomString atom_string_b)
Compares a term with an AtomString.
Checks if the given term and the given AtomString refers to the same atom. This function is just a shortcut that uses the corresponding funtion from globalcontext.
- Parameters:
ctx – the current Context.
atom_a – any term of any type, when it is not an atom false is always returned.
atom_string_b – an atom string, which is the atom length followed by atom characters.
- Returns:
true if they both refer to the same atom, otherwise false.
-
int context_link(Context *ctx, term monitor_pid)
Half-link process to another process.
Caller must hold the global process lock. This creates one half of the link.
- Parameters:
ctx – context to link
monitor_pid – process to link ctx to
- Returns:
0 on success
-
size_t context_message_queue_len(Context *ctx)
Returns number of messages in the process’s mailbox.
- Parameters:
ctx – a valid context.
- Returns:
the number of messages in the process’s mailbox
-
uint64_t context_monitor(Context *ctx, term monitor_pid)
Create a monitor on a process.
Caller must hold the global process lock.
- Parameters:
ctx – context to monitor
monitor_pid – monitoring process
- Returns:
the ref ticks
-
Context *context_new(GlobalContext *glb)
Creates a new context.
Allocates a new Context struct and initialize it. The newly created context is also inserted into the processes table, however it is not scheduled, allowing for further initialization.
- Parameters:
glb – The global context of this virtual machine instance.
- Returns:
created context.
-
void context_process_flush_monitor_signal(Context *ctx, uint64_t ref_ticks, bool info)
Process a flush monitor signal.
- Parameters:
ctx – the context being executed
ref_ticks – the monitor reference
info – whether to return FALSE_ATOM if no message was flushed.
-
void context_process_kill_signal(Context *ctx, struct TermSignal *signal)
Process a kill signal, setting the exit reason and changing the killed flag.
- Parameters:
ctx – the context being executed
signal – the kill message
-
void context_process_process_info_request_signal(Context *ctx, struct BuiltInAtomRequestSignal *signal)
Process a process info request signal.
- Parameters:
ctx – the context being executed
signal – the kill message
-
bool context_process_signal_trap_answer(Context *ctx, struct TermSignal *signal)
Process a trap answer signal.
- Parameters:
ctx – the context being executed
signal – the answer message
- Returns:
true
if successful,false
in case of memory error
-
struct ResourceMonitor *context_resource_monitor(Context *ctx, void *resource)
Create a resource monitor on a process.
Caller must hold the global process lock. The returned resource monitor is not added to the monitors list on the resource type.
- Parameters:
ctx – context to monitor
resource – resource object
- Returns:
the resource monitor
-
size_t context_size(Context *ctx)
Returns total amount of size (in byes) occupied by the process.
- Parameters:
ctx – a valid context.
- Returns:
total amount of size (in byes) occupied by the process
-
static inline term *context_stack_base(const Context *ctx)
Returns a context’s stack base.
Used for stack traces
- Parameters:
ctx – a valid context.
- Returns:
the stack base
-
static inline size_t context_stack_size(const Context *ctx)
Returns a context’s stack size.
Return the number of terms currently on the stack. Used for stack traces.
- Parameters:
ctx – a valid context.
- Returns:
stack size in terms
-
void context_unlink(Context *ctx, term monitor_pid)
Remove a half-link from a process.
Caller must hold the global process lock. This removes one half of the link.
- Parameters:
ctx – context to monitor
monitor_pid – process to unlink
-
void context_update_flags(Context *ctx, int mask, int value)
Set or clear a flag on another context.
atomically update flags <- (flags & mask) | value
- Parameters:
ctx – the context to set/clear flag on.
mask – the mask to apply on flags
value – the value to set
-
void debug_dump_context(Context *ctx)
Print a repreentation of the context to stderr.
Print heap, stack, and registers of the given context to stderr.
- Parameters:
ctx – the process context.
-
void debug_dump_heap(Context *ctx)
Print heap contents to stderr.
Print the dump of the heap of the given context to stderr.
- Parameters:
ctx – the process context.
-
void debug_dump_memory(Context *ctx, term *start, term *end, const char *region)
Print a region of (term) memory to stderr.
Print the dump of the memory the given context to stderr.
- Parameters:
ctx – the process context.
start – the start address.
end – the end address.
region – the name of the region to display.
-
void debug_dump_registers(Context *ctx)
Print register contents to stderr.
Print the dump of the registers of the given context to stderr.
- Parameters:
ctx – the process context.
-
void debug_dump_stack(Context *ctx)
Print stack contents to stderr.
Print the dump of the stack of the given context to stderr.
- Parameters:
ctx – the process context.
-
void debug_print_processes_list(struct ListHead *processes)
Prints a list of processes.
Prints to stderr a list of processes.
- Parameters:
processes – the list of processes that will be printed.
-
void destroy_resource_monitors(struct RefcBinary *resource, GlobalContext *global)
Destroy monitors associated with a resource.
- Parameters:
resource – resource to destroy monitors for
global – the global context
-
void *enif_alloc_resource(ErlNifResourceType *type, unsigned size)
Allocate a resource for given type for
size
bytes.- Parameters:
type – a trype created by
enif_init_resource_type
.size – the size in bytes.
- Returns:
a pointer or
NULL
on failure.
-
int enif_compare_monitors(const ErlNifMonitor *monitor1, const ErlNifMonitor *monitor2)
compare two monitors
- Parameters:
monitor1 – first monitor
monitor2 – second monitor
- Returns:
0 if equals, < 0 if
monitor1
<monitor2
, > 0 ifmonitor1
>monitor2
.
-
int enif_demonitor_process(ErlNifEnv *caller_env, void *obj, const ErlNifMonitor *mon)
Unmonitor a process.
- Parameters:
caller_env – current environment
obj – resource used by monitor
mon – monitor
- Returns:
0 on success
-
int enif_get_resource(ErlNifEnv *env, ERL_NIF_TERM t, ErlNifResourceType *type, void **objp)
Get a pointer to a resource from a term representing it.
- Parameters:
env – the current environment
t – the term
type – the resource type
objp – on output the pointer to the resource
- Returns:
true
on success,false
on failure, if term is not a resource of typetype
-
ErlNifResourceType *enif_init_resource_type(ErlNifEnv *env, const char *name, const ErlNifResourceTypeInit *init, ErlNifResourceFlags flags, ErlNifResourceFlags *tried)
Create or take over (code upgrade) a resource type.
- Parameters:
env – the current environment
init – a structure describing the callbacks. Callbacks can be NULL if not used.
name – name of the resource (copied)
flags –
ERL_NIF_RT_CREATE
orERL_NIF_RT_TAKEOVER
to create or take over.tried – on output, updated to
ERL_NIF_RT_CREATE
orERL_NIF_RT_TAKEOVER
depending on what has been done. On failure, updated to flags. Can be NULL.
- Returns:
the resource type or
NULL
on failure.
-
int enif_keep_resource(void *resource)
Increment reference count of a resource.
- Parameters:
resource – the resource to keep
- Returns:
true
.
-
ERL_NIF_TERM enif_make_resource(ErlNifEnv *env, void *obj)
create a term from a resource
the term can be later passed to
enif_get_resource
. The resource is typically released (by callingenif_release_resource
) just after calling this function to “transfer ownership” to Erlang code so that it will be destroyed when garbage collected.- Parameters:
env – current environment
obj – resource
- Returns:
a new term representing the resource
-
int enif_monitor_process(ErlNifEnv *env, void *obj, const ErlNifPid *target_pid, ErlNifMonitor *mon)
Monitor a process by using a resource object.
The monitor is automatically removed after being triggered or if the associated resource is deallocated.
- Parameters:
env – current environment
obj – resource to use for monitor
target_pid – process to monitor
mon – on output, monitor object (can be NULL)
- Returns:
0 on success, <0 if no down callback is provided with resource (badarg), >0 if the process is no longer alive
-
int enif_release_resource(void *resource)
Decrement reference count of a resource.
- Parameters:
resource – the resource to release
- Returns:
true
.
-
int enif_select(ErlNifEnv *env, ErlNifEvent event, enum ErlNifSelectFlags mode, void *obj, const ErlNifPid *pid, ERL_NIF_TERM ref)
Run a POSIX-like select on a given object (event) and send a message when the object is readable or writable.
Actual implementation is platform dependent and platforms may not implement this feature.
On
generic_unix
, this is currently implemented using whatsys_poll_events
uses, namelykqueue(2)
(if available) orpoll(2)
. Please note thatkqueue(2)
andpoll(2)
behave differently for some objects, for example for vnodes and EOF.On
esp32
, this is currently implemented usingpoll(2)
.- Parameters:
env – current environment
event – event object (typically a file descriptor)
mode – select mode (
ERL_NIF_SELECT_READ
and/orERL_NIF_SELECT_WRITE
) optionally withERL_NIF_SELECT_CANCEL
to cancel, orERL_NIF_SELECT_STOP
to stop.obj – resource object working as a container of the event object.
pid – process id to send a message to or NULL to use the current process (from
env
)ref – reference object used in sent messages or
undefined
atom.
- Returns:
a negative value on failure, 0 or flags on success.
-
static void event_listener_add_to_polling_set(struct EventListener *listener, GlobalContext *glb)
Add an event listener to the set of polled events.
This function must be implemented and will typically access the platform data from
glb
and add the event to the set. It is called byprocess_listener_handler
when a handler returns a new listener. It can be called bysys_register_listener
. It may just set a dirty flag.- Parameters:
listener – the listener to add to polling set
glb – the global context
-
static bool event_listener_is_event(EventListener *listener, listener_event_t event)
Determiner if an event is a listener’s event.
- Parameters:
listener – the listener to test
event – the event to test
- Returns:
true if event is the listener’s event
-
enum ExternalTermResult externalterm_from_binary(Context *ctx, term *dst, term binary, size_t *bytes_read)
Create a term from a binary.
Deserialize a binary term that stores term data in Erlang external term format, and instantiate the serialized terms. The heap from the context will be used to allocate the instantiated terms. This function is the complement of externalterm_to_binary. WARNING: This function may call the GC, which may render the input binary invalid.
- Parameters:
ctx – the context that owns the memory that will be allocated.
dst – a pointer to a term that will contain the binary encoded term.
binary – the binary.
bytes_read – the number of bytes read from the input binary.
- Returns:
the term deserialized from the input term, or an invalid term, if deserialization fails.
-
term externalterm_to_binary(Context *ctx, term t)
Create a binary from a term.
Serialize a term in Erlang external term format, and store the result in a binary term. The heap from the context will be used to allocate the hydrated terms. This function is the complement of externalterm_to_binary. WARNING: This function may call the GC, which may render the input binary invalid.
- Parameters:
ctx – the context that owns the memory that will be allocated.
t – the term to return as binary.
- Returns:
the term deserialized from the input term, or an invalid term, if deserialization fails.
-
term externalterm_to_term(const void *external_term, size_t size, Context *ctx, ExternalTermOpts opts)
Gets a term from external term data.
Deserialize an external term from external format and returns a term.
- Parameters:
external_term – the external term that will be deserialized.
size – to allocate for term.
ctx – the context that owns the memory that will be allocated.
opts – if non-zero, use a heap fragment to store the generated terms. Otherwise, use the heap in the provided context. Note that when using the context heap, this function may call the GC, if there is insufficient space to store the generated terms.
- Returns:
a term.
-
static term externalterm_to_term_internal(const void *external_term, size_t size, Context *ctx, ExternalTermOpts opts, size_t *bytes_read, bool copy)
Copy an external term to internal storage.
- Parameters:
external_term – buffer containing external term
size – size of the external_term
ctx – current context in which terms may be stored
opts – additional opts, such as ExternalTermToHeapFragment for storing parsed terms in a heap fragment, otherwise terms are stored in the context heap.
bytes_read – the number of bytes read off external_term in order to yield a term
copy – whether to copy binary data and atom strings (pass true, unless external_term is a const binary and will not be deallocated)
- Returns:
the parsed term
-
AtomString globalcontext_atomstring_from_term(GlobalContext *glb, term t)
Returns the AtomString value of a term.
This function fetches the AtomString value of the atom associated with the supplied term. The input term must be an atom type. If no such atom is registered in the global table, this function returns NULL. The caller should NOT free the data associated with the returned value.
- Parameters:
glb – the global context
t – the atom term
- Returns:
the AtomString associated with the supplied atom term.
-
bool globalcontext_demonitor(GlobalContext *global, uint64_t ref_ticks)
remove a monitor
iterate on the list of all processes and then on each monitor to find a given monitor, and remove it
- Parameters:
global – the global context
ref_ticks – the reference to the monitor
- Returns:
true if the monitor was found
-
void globalcontext_destroy(GlobalContext *glb)
Destoys an existing GlobalContext.
Frees global context resources and memory and removes it from the processes table.
- Parameters:
glb – the global context that will be destroyed.
-
term globalcontext_existing_term_from_atom_string(GlobalContext *glb, AtomString atom_string)
Returns the term for an existing atom.
This function allows to get an atom term associated to the given atom string, if and only if the given atom is already in the atom table, otherwise an invalid term is returned.
- Parameters:
glb – the global context.
atom_string – the atom string that will be looked into the atom table.
- Returns:
the term associated with the supplied atom string when already existing in the atom table, otherwise an invalid term.
-
Module *globalcontext_get_module(GlobalContext *global, AtomString module_name_atom)
Returns the module with the given name.
Tries to get the module with the given name from the modules table and eventually loads it.
- Parameters:
global – the global context.
module_name_atom – the module name.
- Returns:
a pointer to a Module struct.
-
Module *globalcontext_get_module_by_index(GlobalContext *global, int index)
Get a module by index.
Safely retrieve the module by index considering the table can be reallocated by globalcontext_insert_module.
- Parameters:
global – the global context.
index – the module index.
- Returns:
the module
-
Context *globalcontext_get_process_lock(GlobalContext *glb, int32_t process_id)
Gets a Context from the process table, acquiring a lock on the process table.
Retrieves from the process table the context with the given local process id. If the process can be found, the process table is locked.
- Parameters:
glb – the global context (that owns the process table).
process_id – the local process id.
- Returns:
a Context * with the requested local process id or NULL if not found.
-
Context *globalcontext_get_process_nolock(GlobalContext *glb, int32_t process_id)
Gets a Context from the process table, without acquiring a lock on the process table.
Retrieves from the process table the context with the given local process id. If the process can be found, without locking the process table. This is unsafe unless a lock on the process table has been obtained previously.
- Parameters:
glb – the global context (that owns the process table).
process_id – the local process id.
- Returns:
a Context * with the requested local process id or NULL if not found.
-
void globalcontext_get_process_unlock(GlobalContext *glb, Context *c)
Unlock the process table after c was gotten.
- Parameters:
glb – the global context (that owns the process table).
c – the result of
globalcontext_get_process_lock
. If NULL, does nothing, otherwise releases the lock on process table.
-
int globalcontext_get_registered_process(GlobalContext *glb, int atom_index)
Get a registered process.
Returns the local process id of a previously registered process.
- Parameters:
glb – the global context.
atom_index – the atom table index.
- Returns:
a previously registered process local id.
-
void globalcontext_init_process(GlobalContext *glb, Context *ctx)
Initialize a new process, providing it with a process id.
This function also inserts the process into the process and waiting tables.
- Parameters:
glb – the global context.
ctx – the process to initialize
-
static inline int globalcontext_insert_atom(GlobalContext *glb, AtomString atom_string)
equivalent to globalcontext_insert_atom_maybe_copy(glb, atom_string, 0);
-
static inline int globalcontext_insert_atom_maybe_copy(GlobalContext *glb, AtomString atom_string, int copy)
Inserts an atom into the global atoms table, making a copy of the supplied atom string, if copy is non-zero.
Inserts an atom into the global atoms table and returns its id.
- Parameters:
glb – the global context.
atom_string – the atom string that will be added to the global atoms table, it will not be copied so it must stay allocated and valid.
copy – if non-zero, make a copy of the input atom_string if the atom is not already in the table. The table assumes “ownership” of the allocated memory.
- Returns:
newly added atom id or -1 in case of failure.
-
int globalcontext_insert_module(GlobalContext *global, Module *module)
Inserts a module to the modules table.
Inserts an already loaded module to the modules table and assigns and index to it so it can be retrieved later by name or index. The module is then owned by the global context that will destroy it when globalcontext_destroy is invoked.
- Parameters:
global – the global context.
module – the module that will be added to the modules table.
- Returns:
the module index if successful, otherwise -1.
-
bool globalcontext_is_atom_index_equal_to_atom_string(GlobalContext *glb, int atom_index_a, AtomString atom_string_b)
Compares an atom table index with an AtomString.
Checks if the given atom table index and the given AtomString refers to the same atom.
- Parameters:
glb – the global context.
atom_index_a – an atom table index.
atom_string_b – an atom string, which is the atom length followed by atom characters.
- Returns:
true if they both refer to the same atom, otherwise false.
-
static inline bool globalcontext_is_term_equal_to_atom_string(GlobalContext *global, term atom_a, AtomString atom_string_b)
Compares a term with an AtomString.
Checks if the given term and the given AtomString refers to the same atom.
- Parameters:
global – the global context.
atom_a – any term of any type, when it is not an atom false is always returned.
atom_string_b – an atom string, which is the atom length followed by atom characters.
- Returns:
true if they both refer to the same atom, otherwise false.
-
static inline term globalcontext_make_atom(GlobalContext *glb, AtomString string)
Returns a term representing an atom, from the suppliend string.
Converts a string to an atom. Note that this function may have a side-effect on the global context.
- Parameters:
glb – pointer to the global context
string – an AtomString
- Returns:
an atom term formed from the supplied atom string.
-
void globalcontext_maybe_unregister_process_id(GlobalContext *glb, int process_id)
Remove entry(ies) from registered atoms by process id.
Unregister a process with a certain process id. This is used when a process dies to ensure the process is not registered and remove it from the registered atoms table if it is.
- Parameters:
glb – the global context, each registered process will be globally available for that context.
process_id – the process id of the entry to remove.
-
GlobalContext *globalcontext_new()
Creates a new GlobalContext.
Allocates a new GlobalContext struct and initialize it, the newly created global context is a new AtomVM instance.
- Returns:
A newly created GlobalContext.
-
bool globalcontext_process_exists(GlobalContext *glb, int32_t process_id)
Determine if a process exists.
- Parameters:
glb – the global context (that owns the process table).
process_id – the local process id.
- Returns:
true if a process exists with this id.
-
void globalcontext_process_task_driver_queues(GlobalContext *glb)
Process refc binaries and messages enqueued from task drivers.
This function is called from the scheduler.
- Parameters:
glb – the global context
-
void globalcontext_refc_decrement_refcount_from_task(GlobalContext *glb, struct RefcBinary *refc)
Enqueue a refc binary from a task driver, to be refc decremented later from the scheduler.
- Parameters:
glb – the global context
refc – the refc binary to enqueue
-
bool globalcontext_register_process(GlobalContext *glb, int atom_index, int local_process_id)
Register a process.
Register a process with a certain name (atom) so it can be easily retrieved later.
- Parameters:
glb – the global context, each registered process will be globally available for that context.
atom_index – the atom table index.
local_process_id – the process local id.
- Returns:
true
if the process was registered,false
if another process with the same name already existed
-
void globalcontext_send_message(GlobalContext *glb, int32_t process_id, term t)
Send a message to a process identified by its id.
Safely send a message to the process, doing nothing is the process cannot be found.
- Parameters:
glb – the global context (that owns the process table).
process_id – the local process id.
t – the message to send.
-
void globalcontext_send_message_from_task(GlobalContext *glb, int32_t process_id, enum MessageType type, term t)
Send a message to a process identified by its id. This variant is to be used from task drivers. It tries to acquire the necessary locks and if it fails, it enqueues the message which will be delivered on the next scheduler context switch.
Safely send a message to the process, doing nothing if the process cannot be found.
- Parameters:
glb – the global context (that owns the process table).
process_id – the target process id.
type – the type of message to send, can be NormalMessage or a signal
t – the message to send.
-
void globalcontext_send_message_nolock(GlobalContext *glb, int32_t process_id, term t)
Send a message to a process from another process. There should be a lock on the process table. This variant can be used by listener handlers as an optimization (instead of sending a message to the port context which should then forward it to the target context).
Safely send a message to the process, doing nothing if the process cannot be found.
- Parameters:
glb – the global context (that owns the process table).
process_id – the target process id.
t – the message to send.
-
bool globalcontext_unregister_process(GlobalContext *glb, int atom_index)
Unregister a process by name.
Unregister a process with a certain name (atom).
- Parameters:
glb – the global context, each registered process will be globally available for that context.
atom_index – the atom table index.
- Returns:
true
if the process was unregistered,false
otherwise
-
int iff_is_valid_beam(const void *beam_data)
Returns 1 if pointed binary is valid BEAM IFF.
Checks if the pointed binary has a valid BEAM IFF header.
- Parameters:
beam_data – a pointer to the beam_data binary
- Returns:
1 if beam_data points to a valid binary, otherwise 0 is returned.
-
uint32_t inet_addr4_to_uint32(term addr_tuple)
Parse an inet IPv4 address tuple.
- Parameters:
addr_tuple – the tuple to parse
- Returns:
the address as a uint32_t, in host order
-
enum inet_domain inet_atom_to_domain(term domain, GlobalContext *global)
Parse an inet domain atom.
- Parameters:
domain – the inet domain atom
global – the global context
- Returns:
InetDomain or InetInvalidDomain
-
enum inet_protocol inet_atom_to_protocol(term protocol, GlobalContext *global)
Parse an inet protocol.
- Parameters:
protocol – the inet protocol atom
global – the global context
- Returns:
the parsed protocol
-
enum inet_type inet_atom_to_type(term type, GlobalContext *global)
Parse an inet type.
- Parameters:
type – the inet type atom
global – the global context
- Returns:
the parsed type
-
term inet_make_addr4(uint32_t addr, Heap *heap)
Make an inet IPv4 address tuple.
this function requires that at least INET_ADDR4_TUPLE_SIZE terms are free on the heap.
- Parameters:
addr – the address to make as a tuple, as a uint32_t in host order
heap – the heap to build the tuple in
- Returns:
the tuple
-
term interop_atom_term_select_atom(const AtomStringIntPair *table, int value, GlobalContext *global)
Finds the first matching atom in an atoms table .
Allows to quickly translate integer constants to an atom in an atoms table. This function is the inverse of interop_atom_term_select_int.
- Parameters:
table – an array AtomStringIntPair structs, terminated with a default entry marked with SELECT_INT_DEFAULT macro.
value – the in value used for comparison.
global – the global context.
- Returns:
the found atom which corresponds to the given int value, or the invalid term, if there is no such value in the table.
-
int interop_atom_term_select_int(const AtomStringIntPair *table, term atom, GlobalContext *global)
Finds on a table the first matching atom string.
Allows to quickly translate atoms to any integer constant. This function is useful for creating switch statements for atom values. A linear search is performed, so table entries should be sorted by frequency.
- Parameters:
table – an array AtomStringIntPair structs, terminated with a default entry marked with SELECT_INT_DEFAULT macro.
atom – the atom used for comparison.
global – the global context.
- Returns:
the found int value which corresponds to the given atom.
-
static inline term interop_kv_get_value(term kv, AtomString key, GlobalContext *glb)
Get a value given a key (as AtomString) from any proplist or map.
This function allows to easily get values from proplists or maps, without poluting the atom table. This function returns the invalid term if there is no such entry in kv.
- Parameters:
kv – any proplist or map.
key – an AtomString, such as ATOM_STR(“\x3”, “key”).
glb – the global context.
- Returns:
the value term in case given key exists, otherwise the invalid term.
-
term interop_kv_get_value_default(term kv, AtomString key, term default_value, GlobalContext *glb)
Get a value given a key (as AtomString) from any proplist or map.
This function allows to easily get values from proplists or maps, without poluting the atom table.
- Parameters:
kv – any proplist or map.
key – an AtomString, such as ATOM_STR(“\x3”, “key”).
default_value – that is returned in case of missing item.
glb – the global context.
- Returns:
the value term in case given key exists, otherwise the default_value.
-
static void listener_event_remove_from_polling_set(listener_event_t event, GlobalContext *glb)
Remove an event from the set of polled events.
This function must be implemented and will typically access the platform data from
glb
and remove the event to the set. It is called byprocess_listener_handler
when a handler returns NULL or a new listener. It can be called bysys_unregister_listener
. It may just set a dirty flag.Compared to
event_listener_add_to_polling_set
, the event listener may no longer exist if it was freed by the handler.- Parameters:
event – the listener event to remove from polling set
glb – the global context
-
void mailbox_crashdump(Context *ctx)
Output mailbox to stderr for crashdump reporting.
- Parameters:
ctx – the owner of the mailbox to dump
-
void mailbox_destroy(Mailbox *mbox, Heap *heap)
Free memory associated with a mailbox.
All messages in the mailbox will be freed or appended to the heap.
- Parameters:
mbox – the mailbox to free.
heap – the heap to add messages to.
-
Message *mailbox_first(Mailbox *mbox)
Get first message from mailbox.
Get the first message and sets the receive pointer to it so it can be removed later. Used by ports & drivers. To be called from the process only.
- Parameters:
mbox – the mailbox to get the current message from.
- Returns:
first message or NULL.
-
static inline bool mailbox_has_next(Mailbox *mbox)
Determine if there is a next item in message list.
To be called from the process only.
- Parameters:
mbox – the mailbox to test
- Returns:
true
if peek would succeed.
-
void mailbox_init(Mailbox *mbox)
Initialize the mailbox.
- Parameters:
mbox – the mailbox to initialize.
-
size_t mailbox_len(Mailbox *mbox)
Compute the mailbox length, in messages.
To be called from the process only.
- Parameters:
mbox – the mailbox to get the length of.
-
MailboxMessage *mailbox_message_create_from_term(enum MessageType type, term t)
Allocate and serialize a term to a mailbox message.
Can be called from a task or even ISR (provided malloc works).
- Parameters:
type – the message type, can be NormalMessage or a signal type
t – the term that will be sent
-
void mailbox_message_dispose(MailboxMessage *m, Heap *heap)
Dispose a (processed) mailbox message. The message will be freed or appended to current heap and will be destroyed on garbage collect. This function is called by mailbox_remove and is only needed for signal messages.
- Parameters:
m – the message to free.
heap – heap to append the message to.
-
void mailbox_next(Mailbox *mbox)
Advance pointer to next message in a receive loop.
To be called from the process only.
- Parameters:
mbox – the mailbox to work with
-
bool mailbox_peek(Context *ctx, term *out)
Gets next message from a mailbox (without removing it).
Peek the mailbox and retrieve a term that has been previously queued on a certain process or driver mailbox. To be called from the process only.
- Parameters:
ctx – the calling context, owning the mailbox and where the message should be copied to.
out – the allocated term.
- Returns:
true if a term was available
-
MailboxMessage *mailbox_process_outer_list(Mailbox *mbox)
Process the outer list of messages.
To be called from the process only
- Parameters:
mbox – the mailbox to work with
- Returns:
the signal messages in received order.
-
static inline void mailbox_remove_message(Mailbox *mbox, Heap *heap)
Remove next message from mailbox.
Discard a term that has been previously queued on a certain process or driver mailbox. To be called from the process only. Term messages are actually added as fragments to the heap and will be gone at next GC.
- Parameters:
mbox – the mailbox to remove next message from.
heap – the heap to add messages to.
-
void mailbox_reset(Mailbox *mbox)
Reset mailbox receive pointer.
To be called from the process only.
- Parameters:
mbox – the mailbox to work with
-
void mailbox_send(Context *c, term t)
Sends a message to a certain mailbox.
Sends a term to a certain process or port mailbox. Can be called from another process. Cannot be called from a task or from ISR.
- Parameters:
c – the process context.
t – the term that will be sent.
-
void mailbox_send_built_in_atom_request_signal(Context *c, enum MessageType type, int32_t sender_pid, term atom)
Sends a built-in atom-based request signal to a certain mailbox.
- Parameters:
c – the process context.
type – the type of the signal
sender_pid – the sender of the signal (to get the answer)
atom – the built-in atom
-
void mailbox_send_built_in_atom_signal(Context *c, enum MessageType type, term atom)
Sends a built-in atom signal to a certain mailbox.
- Parameters:
c – the process context.
type – the type of the signal
atom – the built-in atom
-
void mailbox_send_empty_body_signal(Context *c, enum MessageType type)
Sends an empty body signal to a certain mailbox.
- Parameters:
c – the process context.
type – the type of the signal
-
void mailbox_send_ref_signal(Context *c, enum MessageType type, uint64_t ref_ticks)
Sends a ref signal to a certain mailbox.
- Parameters:
c – the process context.
type – the type of the signal
ref_ticks – the ref
-
void mailbox_send_term_signal(Context *c, enum MessageType type, term t)
Sends a term-based signal to a certain mailbox.
- Parameters:
c – the process context.
type – the type of the signal
t – the term added to the message
-
size_t mailbox_size(Mailbox *mbox)
Compute the mailbox size, in bytes.
To be called from the process only.
- Parameters:
mbox – the mailbox to get the size of.
-
MailboxMessage *mailbox_take_message(Mailbox *mbox)
Take next message from mailbox.
Remove the first message from the mailbox and return it. To be called from the process only. This function is intended for some corner cases, such as certain port drivers.
- Parameters:
mbox – the mailbox to take the next message from.
-
term memory_copy_term_tree(Heap *new_heap, term t)
copies a term to a destination heap
deep copies a term to a destination heap, once finished old memory can be freed.
- Parameters:
new_heap – the destination heap where terms will be copied.
t – term to copy
- Returns:
a new term that is stored on the new heap.
-
term memory_copy_term_tree_to_storage(term *storage, term **heap_end, term t)
copies a term to a storage, typically for mailbox messages
deep copies a term to a destination heap, once finished old memory can be freed.
- Parameters:
storage – storage for the copied data, should be large enough
heap_end – on output, pointer to the end of the term.
t – term to copy
- Returns:
a boxed term pointer to the new term content that is stored in the storage.
-
static inline void memory_destroy_heap(Heap *heap, GlobalContext *global)
Destroy a root heap. First sweep its mso list.
This function shall only be called from a scheduler thread (native handler or listener) because it decrements the reference count of refc binaries and may call resource destructors.
- Parameters:
heap – the heap to destroy
global – the global context
-
static inline void memory_destroy_heap_fragment(HeapFragment *fragment)
Destroy a chain of heap fragments.
- Parameters:
fragment – fragment to destroy.
-
static inline void memory_destroy_heap_from_task(Heap *heap, GlobalContext *global)
Destroy a root heap. First sweep its mso list.
This variant is safer and is meant for driver tasks.
- Parameters:
heap – the heap to destroy
global – the global context
-
static inline enum MemoryGCResult memory_ensure_free_opt(Context *ctx, size_t size, enum MemoryAllocMode alloc_mode)
makes sure that the given context has given free memory.
this function makes sure at least size terms are available. Optionally, it can shrink the heap to the specified size, depending on allocation strategy.
- Parameters:
ctx – the target context.
size – needed available memory.
alloc_mode – constraint on allocation of additional memory
-
enum MemoryGCResult memory_ensure_free_with_roots(Context *ctx, size_t size, size_t num_roots, term *roots, enum MemoryAllocMode alloc_mode)
makes sure that the given context has given free memory.
this function makes sure at least size terms are available. Optionally, it can allocate a fragment or shrink the heap to the specified size, depending on allocation strategy. The function can also be passed roots to update during any garbage collection.
- Parameters:
ctx – the target context.
size – needed available memory.
num_roots – number of roots
roots – roots to preserve
alloc_mode – constraint on allocation of additional memory
-
enum MemoryGCResult memory_erl_nif_env_ensure_free(ErlNifEnv *env, size_t size)
makes sure that the given nif environment has given free memory
this function makes sure that at least size terms are available. When not available, a new fragment will be allocated.
- Parameters:
env – the target environment.
size – needed available memory.
-
unsigned long memory_estimate_usage(term t)
calculates term memory usage
perform an used memory calculation using given term as root, shared memory (that is not part of the memory block) is not accounted.
- Parameters:
t – root term on which used memory calculation will be performed.
- Returns:
used memory terms count in term units output parameter.
-
static inline term *memory_heap_alloc(Heap *heap, size_t size)
allocates space for a certain amount of terms on the heap
allocates space for a certain amount of terms on the heap, GC will be performed when needed, any existing term might be invalid after this call.
- Parameters:
heap – heap to initialize.
size – the amount of terms that will be allocated.
- Returns:
a pointer to the newly allocated memory block.
-
void memory_heap_append_fragment(Heap *heap, HeapFragment *fragment, term mso_list)
append a fragment to a heap. The MSO list is merged. The fragment will then be owned by the heap.
- Parameters:
heap – the heap to append the fragment to
fragment – the fragment to add
mso_list – associated mso list or nil
-
static inline void memory_heap_append_heap(Heap *target, Heap *source)
append a heap to another heap. The MSO list is merged. The fragments of the source heap will be owned by the target heap.
- Parameters:
target – the heap to append the heap’s fragments to
source – the heap to add
-
static inline size_t memory_heap_fragment_memory_size(const HeapFragment *fragment)
return the total memory size of a heap fragment and its children.
- Parameters:
fragment – the root fragment to get the size of
- Returns:
the size in terms
-
static inline void memory_heap_trim(Heap *heap, size_t size)
shrinks the heap by size units
this function is used when resizing the last item allocated on the heap.
- Parameters:
heap – the heap that will be shrinked
size – the number of terms that will be removed
-
static inline size_t memory_heap_youngest_size(const Heap *heap)
return the size of the youngest generation of the heap.
in some condition, this function returns the size of a fragment where the stack is not.
- Parameters:
heap – the heap to get the youngest size of
- Returns:
the size in terms
-
static inline size_t memory_heap_memory_size(const Heap *heap)
return the total memory size of a heap, including fragments.
- Parameters:
heap – the heap to get the size of
- Returns:
the size in terms
-
enum MemoryGCResult memory_init_heap(Heap *heap, size_t size)
Initialize a root heap.
This function should be balanced with
memory_destroy_heap
ormemory_destroy_heap_from_task
if the heap is created by a driver task.- Parameters:
heap – heap to initialize.
size – capacity of the heap to create, not including the mso_list.
- Returns:
MEMORY_GC_OK or MEMORY_GC_ERROR_FAILED_ALLOCATION depending on the outcome.
-
void memory_init_heap_root_fragment(Heap *heap, HeapFragment *root, size_t size)
Setup heap from its root. Set the
mso_list
to NIL and initializeheap_ptr
.- Parameters:
heap – heap to initialize.
root – fragment root.
size – capacity of the heap to create, not including the mso_list.
-
void memory_sweep_mso_list(term mso_list, GlobalContext *global, bool from_task)
Sweep any unreferenced binaries in the “Mark Sweep Object” (MSO) list.
The MSO list is a list of term (references) in a heap. Currently, the elements of this list are referenced to reference-counted binaries or match binaries that themselves reference reference counted binaries. This function will iterate over the binaries in this list, and decrement the reference count of any elements that have not been marked for move (e.g., into a new heap). If the reference count reaches 0, then memory associated with the referenced binary will be freed.In a typical GC event, the terms in this list are within in the old heap or potentially in a heap fragment. However, this function may be called in a copy even, such as in a process spawn, or in the copy of a term to or from a process mailbox.
- Parameters:
mso_list – the list of mark-sweep object in a heap “space”
global – the global context
from_task – boolean, true if called from a task, false otherwise
-
static inline AtomString module_get_atom_string_by_id(const Module *mod, int local_atom_id, GlobalContext *glb)
Gets the AtomString for the given local atom id.
Gets an AtomString for the given local atom id from the global table.
- Parameters:
mod – the module that owns the atom.
local_atom_id – module atom table index.
glb – the global context.
- Returns:
the AtomString for the given module atom index.
-
static inline term module_get_atom_term_by_id(const Module *mod, int local_atom_id)
Gets a term for the given local atom id.
Gets the global atom id for the the given local atom id and casts it to a term.
- Parameters:
mod – the module that owns the atom.
local_atom_id – module atom table index.
- Returns:
a term for the given module atom index.
-
term module_get_exported_functions(Module *this_module, Heap *heap, GlobalContext *global)
Get the list of exported functions.
Create a list of exported functions of the form
{FunctionName, Arity}
To create this list, the heap must be grown bymodule_get_exported_functions_list_size
terms.- Parameters:
this_module – the module to count exported functions of
heap – heap to allocate tuples
global – global context to fetch atoms
- Returns:
a list of exported functions
-
size_t module_get_exported_functions_count(Module *this_module)
Count exported functions of a given module.
Get the number of exported functions. This function is used to compute the required heap size of the list of exported functions.
- Parameters:
this_module – the module to count exported functions of
- Returns:
the number of exported functions
-
static inline size_t module_get_exported_functions_list_size(Module *this_module)
Determine heap size of exported functions list.
- Parameters:
this_module – the module to count exported functions of
- Returns:
the size, in terms, of the exported function list
-
static inline term module_get_name(const Module *mod)
Get the module name, as an atom term.
- Parameters:
mod – the module to get the name of
- Returns:
a term for the given module atom index.
-
static inline bool module_has_line_chunk(Module *mod)
- Returns:
true if the module has line information, false, otherwise.
-
term module_load_literal(Module *mod, int index, Context *ctx)
Gets a literal stored on the literal table of the specified module.
Loads and deserialize a term stored in the literal table and returns a term.
- Parameters:
mod – The module that owns that is going to be loaded.
index – a valid literal index.
ctx – the target context.
-
Module *module_new_from_iff_binary(GlobalContext *global, const void *iff_binary, unsigned long size)
Parse a BEAM file and returns a Module.
Parse a BEAM file a returns a newly allocated and initialized Module struct.
- Parameters:
global – the global context.
iff_binary – the IFF file data.
size – the size of the buffer containing the IFF data.
-
static inline const struct ExportedFunction *module_resolve_function(Module *mod, int import_table_index, GlobalContext *glb)
Resolves an unresolved function reference.
Resolves an unresolved function reference and it replaces the unresolved reference with a ModuleFunction struct, also it loads the referenced module if it hasn’t been loaded yet.
- Parameters:
mod – the module containing the function to resolve.
import_table_index – the unresolved function index.
glb – the global context
-
uint32_t module_search_exported_function(Module *this_module, AtomString func_name, int func_arity, GlobalContext *glb)
Gets exported function index by searching it by function name and arity.
Gets exported function index by searching it by function name and arity
- Parameters:
this_module – the module on which the function will be searched.
func_name – function name atom string.
func_arity – function arity.
glb – the global context
-
void otp_socket_lwip_enqueue(struct LWIPEvent *event)
Enqueue an event to be processed in task context.
This function must be implemented in otp_socket_platform.c. Platforms using lwIP implementation may have lwIP callbacks coming from ISR and in such case need to implement a queue mechanism to process them in task context. GlobalContext is not always available in lwIP callbacks so platforms using a queue need a global variable. If lwIP callbacks are not called from ISR, calling handler with the event is sufficient.
- Parameters:
event – the event to enqueue
-
const struct Nif *platform_nifs_get_nif(const char *nifname)
Returns the Nif assocatiated with a nif name.
This function is used to locate platform-specific Nifs. Each platform must include an implementation of this function, even if it just returns NULL.
-
term posix_errno_to_term(int err, GlobalContext *glb)
Convenient function to return posix errors as atom.
POSIX does not define the values of errno errors, so this function makes sure Erlang code can interpret error codes whatever the platform.
- Parameters:
err – the error code, typically obtained from
errno(3)
glb – the global context
- Returns:
an atom representing the error or an integer if the error number is not known.
-
static inline bool process_listener_handler(GlobalContext *glb, listener_event_t current_event, struct ListHead *listeners, struct ListHead **item_ptr, struct ListHead **previous_ptr)
Process listener handlers, optionally in advancing order, especially useful with poll(2) which returns fd in the provided order.
- Parameters:
glb – the global context
current_event – the selected event
listeners – the list of listeners (locked for writing)
item_ptr – the current cursor or NULL to search in items
previous_ptr – the previous cursor (ignored and can be NULL if item_ptr is NULL).
- Returns:
true if the current_event was found
-
static inline struct RefcBinary *refc_binary_create_refc(size_t size)
Create a reference-counted binary outside of the process heap.
This function will create a reference-counted binary outside of the context heap. A blob will be allocated in the VM memory (e.g., via malloc). The allocated data will include an internal data structure that includes the data size and reference count.
- Parameters:
size – the size of the data to create
- Returns:
a pointer to the out-of-context data.
-
struct RefcBinary *refc_binary_create_resource(size_t size, struct ResourceType *resource_type)
Create a reference-counted resource object outside of the process heap.
This function will create a reference-counted resource object outside of the context heap. A blob will be allocated in the VM memory (e.g., via malloc). The allocated data will include an internal data structure that includes the data size and reference count.
- Parameters:
size – the size of the data to create
resource_type – the resource type,
NULL
for regular refc binaries.
- Returns:
a pointer to the out-of-context data.
-
bool refc_binary_decrement_refcount(struct RefcBinary *ptr, GlobalContext *global)
Decrement the reference count on the refc binary.
This function will call
refc_binary_destroy
if the reference count reaches 0.- Parameters:
ptr – the refc binary
global – the global context
- Returns:
true if the refc binary was free’d; false, otherwise
-
void refc_binary_destroy(struct RefcBinary *refc, struct GlobalContext *global)
Destroy a refc binary after its reference count reached 0.
This function will call the destructor if the refc binary is a resource and will free the refc binary.
- Parameters:
refc – the binary to destroy
global – the global context
-
struct RefcBinary *refc_binary_from_data(void *ptr)
get the refc binary from its pointer
This must only be passed the result of
refc_binary_get_data
.- Parameters:
ptr – pointer obtained from
refc_binary_get_data
-
const char *refc_binary_get_data(const struct RefcBinary *ptr)
get the data of the off-context binary
Return the data of the off-context binary
- Parameters:
ptr – Refc binary returned from memory_create_refc_binary
-
void refc_binary_increment_refcount(struct RefcBinary *ptr)
Increment the reference count on the refc binary.
- Parameters:
ptr – the refc binary
-
size_t refc_binary_total_size(Context *ctx)
Return the total size (in bytes) of all reference counted binaries.
- Returns:
the total size (in bytes) of all reference counted binaries
-
char reg_type_c(int reg_type)
Gets a printable char for a given register type.
Returns a printable char such as x or y for the given register type.
- Parameters:
reg_type – register type.
- Returns:
printable register type.
-
void scan_iff(const void *iff_binary, int file_size, unsigned long *offsets, unsigned long *sizes)
parse a BEAM/IFF file and build a sections offsets table
Read a buffer containing a BEAM module file and set all found IFF sections into offsets array.
- Parameters:
iff_binary – is BEAM module data.
file_size – is the BEAM module size in bytes.
offsets – all the relative offsets, each entry will be set to the offset of a different IFF section.
sizes – the computed sections sizes.
-
void scheduler_init_ready(Context *c)
Init a process in the ready state, moving it to the scheduler queue.
- Parameters:
c – the process context.
-
void scheduler_kill(Context *ctx)
Signal a process that it was killed.
- Parameters:
ctx – the process context.
-
Context *scheduler_next(GlobalContext *global, Context *c)
gets next runnable process from the ready queue.
gets next runnable process from the ready queue, it may return current process if there isn’t any other runnable process.
- Parameters:
global – the global context.
c – the current process.
- Returns:
runnable process.
-
Context *scheduler_run(GlobalContext *global)
run the scheduler and return a process to be executed.
- Parameters:
global – the global context.
-
void scheduler_set_timeout(Context *ctx, avm_int64_t timeout)
sets context timeout
set context timeout timestamp, move context to wait queue and update global next timeout timestamp.
- Parameters:
ctx – the context that will be put on sleep
timeout – amount of time to be waited in milliseconds.
-
void scheduler_signal_message(Context *c)
Signal a process that a message was inserted in the mailbox.
Cannot be called from a foreign task or from ISR.
- Parameters:
c – the process context.
-
void scheduler_stop_all(GlobalContext *global)
Terminate all schedulers. Every process is terminated gracefully at next scheduling point.
- Parameters:
global – the global context.
-
void scheduler_terminate(Context *c)
removes a process and terminates it from the scheduling queue
removes a process from the scheduling ready queue and destroys it if its not a leader process.
- Parameters:
c – the process that is going to be terminated.
-
Context *scheduler_wait(Context *c)
move a process to waiting queue and wait a ready one
move current process to the waiting queue, and schedule the next one or sleep until an event is received.
- Parameters:
c – the process context.
-
void select_event_count_and_destroy_closed(struct ListHead *select_events, size_t *read, size_t *write, size_t *either, GlobalContext *global)
Count events available for reading and/or writing and destroy the events marked for close.
Convenience function that can be called by
sys_poll_events
and iterates on events to be closed and count them.The function can also be called from a select task loop if
AVM_SELECT_IN_TASK
is defined.- Parameters:
select_events – list of events, with a write lock
read – on output number of events with read = 1, can be NULL
write – on output number of events with write = 1, can be NULL
either – on output number of events with either read = 1 or write = 1, can be NULL
global – the global context
-
term select_event_make_notification(void *rsrc_obj, uint64_t ref_ticks, bool is_write, Heap *heap)
Build a select event notification.
- Parameters:
rsrc_obj – the resource to build the notification for
ref_ticks – the reference or 0 if it’s undefined
is_write – if the notification is for a write or a read
heap – the heap to create the notification in, should have enough memory available (see SELECT_EVENT_NOTIFICATION_SIZE)
-
bool select_event_notify(ErlNifEvent event, bool is_read, bool is_write, GlobalContext *global)
Send a notification that an event was selected.
This function is called from sys_poll_events platform function if a select event was selected and the read or write flag was set. It modifies the select_event object so the notification is only sent once.
The function can also be called from a select task loop if
AVM_SELECT_IN_TASK
is defined.It is not an error to call this function with an event that is not in the list.
This function calls
sys_unregister_select_event
.- Parameters:
event – the event to notify
is_read – if the event was selected for reading
is_write – if the event was selected for writing
global – the global context
- Returns:
true if the event was found
-
CondVar *smp_condvar_create()
Create a new condition variable.
- Returns:
a pointer to a cv.
-
void smp_condvar_destroy(CondVar *cv)
Destroy a condition variable.
- Parameters:
cv – variable to destroy.
-
void smp_condvar_signal(CondVar *cv)
Signal a single thread waiting on a condition variable.
- Parameters:
cv – variable to signal.
-
void smp_condvar_wait(CondVar *cv, Mutex *mtx)
Wait on a condition variable, atomically unlocking the mutex.
- Parameters:
cv – variable to wait on.
mtx – mutex to unlock/lock.
-
int smp_get_online_processors()
Get the number of online processors to configure schedulers.
This value is one plus the maximum number of times smp_scheduler_start will be called by the scheduler.
- Returns:
the number of online processors.
-
bool smp_is_main_thread(GlobalContext *glb)
Determine if caller is in the main thread, i.e. thread that was not started with acmsmp_scheduler_start.
-
Mutex *smp_mutex_create()
Create a new mutex.
- Returns:
a pointer to a mutex.
-
void smp_mutex_destroy(Mutex *mtx)
Destroy a mutex.
- Parameters:
mtx – the mutex to destroy
-
void smp_mutex_lock(Mutex *mtx)
Lock a mutex.
- Parameters:
mtx – the mutex to lock
-
bool smp_mutex_trylock(Mutex *mtx)
Try and lock a mutex.
- Parameters:
mtx – the mutex to lock
- Returns:
true
if the mutex was acquired.
-
void smp_mutex_unlock(Mutex *mtx)
Unlock a mutex.
- Parameters:
mtx – the mutex to unlock
-
RWLock *smp_rwlock_create()
Create a new rwlock.
A RW Lock can be replaced by a mutex if RW Lock are not available on the platform.
- Returns:
a pointer to a lock.
-
void smp_rwlock_destroy(RWLock *lock)
Destroy a rwlock.
- Parameters:
lock – the lock to destroy
-
void smp_rwlock_rdlock(RWLock *lock)
Read lock a rwlock.
- Parameters:
lock – the lock to read lock
-
void smp_rwlock_unlock(RWLock *lock)
Unlock a rwlock.
- Parameters:
lock – the lock to unlock
-
void smp_rwlock_wrlock(RWLock *lock)
Write lock a rwlock.
- Parameters:
lock – the lock to write lock
-
void smp_scheduler_start(GlobalContext *glb)
Start a new scheduler, calling
scheduler_entry_point
with the given global context.- Parameters:
glb – the global context
-
static inline void smp_spinlock_init(SpinLock *lock)
Initialize a spinlock based on atomics.
- Parameters:
lock – the spin lock to initialize
-
static inline void smp_spinlock_lock(SpinLock *lock)
Lock a spinlock.
- Parameters:
lock – the spin lock to lock
-
static inline void smp_spinlock_unlock(SpinLock *lock)
Unlock a spinlock.
- Parameters:
lock – the spin lock to unlock
-
ssize_t socket_recv(struct SocketResource *socket, uint8_t *buf, size_t len, int flags, term *from, Heap *heap)
Read data from a socket.
- Parameters:
socket – the socket resource
buf – buffer to store data
len – number of bytes
flags – flags passed to recvfrom
from – filled with origin address using recvfrom (can be NULL)
heap – heap to build the origin address term (can be NULL if from is NULL)
- Returns:
the number of read bytes or a value from SocketErrors
-
ssize_t socket_send(struct SocketResource *socket, const uint8_t *buf, size_t len, term dest)
Send data to a socket (without blocking)
- Parameters:
socket – the socket resource
buf – buffer to send
len – number of bytes
dest – destination address or invalid term for sendto/send
- Returns:
the number of written bytes or a value from SocketErrors
-
Context *sys_create_port(GlobalContext *glb, const char *driver_name, term opts)
Create a port driver.
This function creates a port driver, encapsulated in a Context object. This function should create a Context object through the supplied global context, which will assume ownership of the new instance.
- Parameters:
glb – the global context.
driver_name – the name of the driver that will control the port.
opts – the term options passed into the port open command.
- Returns:
a new Context instance, or NULL, if a driver cannot be created from the inputs.
-
void sys_free_platform(GlobalContext *global)
Free the platform data structure.
Cleanup the platform data structure. Called by global_context_destroy.
-
term sys_get_info(Context *ctx, term key)
Get platform-dependent information for the specified key.
This function returns platform-dependent information specified by the supplied key. If not information is available for the specified key, this function should return the atom ‘undefined’
- Parameters:
ctx – the current context
key – an atom used to indicate the type of information requested.
- Returns:
a term containing the requested information, or the atom undefined, if there is no system information for the specified key.
-
void sys_init_platform(GlobalContext *global)
Initialize the platform, setting global->platform_data.
-
void sys_listener_destroy(struct ListHead *item)
Free a listener.
This function is called when the global context is destroyed on every remaining listener. An implementation is available in
listeners.h
.- Parameters:
item – list item
-
Module *sys_load_module(GlobalContext *global, const char *module_name)
Loads a BEAM module using platform dependent methods.
Loads a BEAM module into memory using platform dependent methods and returns a pointer to a Module struct.
- Parameters:
global – the global context.
module_name – the name of the BEAM file (e.g. “mymodule.beam”).
-
void sys_monotonic_time(struct timespec *t)
gets monotonic time
gets the time that is used by
erlang:monotonic_time/1
- Parameters:
t – the timespec that will be updated.
-
uint64_t sys_monotonic_time_ms_to_u64(uint64_t ms)
convert a number of milliseconds to system-chosen unit
- Parameters:
ms – the number of milliseconds to convert
- Returns:
the result of the conversion
-
uint64_t sys_monotonic_time_u64()
gets monotonic time for timers
This function must return a non-overflowing counter in the highest precision the platform permits to make sure that we don’t have truncation errors when compared with sys_time or sys_monotonic_time. Returning the number of microseconds or nanoseconds since boot would work.
- Returns:
a monotonic time in a system-chosen unit
-
uint64_t sys_monotonic_time_u64_to_ms(uint64_t t)
convert a number in system-chosen unit to milliseconds
- Parameters:
t – the number to convert
- Returns:
the result of the conversion
-
void sys_poll_events(GlobalContext *glb, int timeout_ms)
Poll events (from drivers and select events), with a timeout (in ms), or until
sys_signal
is called.Depending on platforms, check all open file descriptors/queues and call drivers that should send messages to contexts (which will unblock them). With SMP builds, this function can be called from any scheduler.
If selectable events are supported on the platform, this function should also:
call
select_event_destroy
on select events that have close set to 1include the set of ErlNifEvent that are marked for read or write in the select set, and if they are selected, call
select_event_notify
to send the notification.
select_event_count_and_destroy_closed
defined in resources.h can be used to process closed select events.- Parameters:
glb – the global context.
timeout_ms – the number of ms to wait,
SYS_POLL_EVENTS_WAIT_FOREVER
to wait forever.
-
void sys_register_listener(GlobalContext *global, EventListener *listener)
Register a listener.
This function is called by ports to register a listener which is a native alternative to select events. The actual definition of listeners is platform dependent.
- Parameters:
global – the global context.
listener – the listener to register
-
void sys_register_select_event(GlobalContext *glb, ErlNifEvent event, bool is_write)
Update the select set by adding an event for reading or writing.
This function probably should update set and call
sys_signal
so new set is taken into account.- Parameters:
glb – the global context.
event – the event (file descriptor) to add to the set
is_write – whether to add the event for writing (as opposed to reading)
-
void sys_signal(GlobalContext *glb)
Interrupt the wait in
sys_poll_events
.This function should signal the thread that is waiting in
sys_poll_events
so it returns before the timeout. It is mostly used for SMP builds, but also to abort sleep from driver callbacks on FreeRTOS.Please note that this function may be called while no thread is waiting in sys_poll_events and this should have no effect. This function is called in scheduler loop (internal function
scheduler_run0
) and when scheduling processes.- Parameters:
glb – the global context.
-
void sys_time(struct timespec *t)
gets wall clock time
gets system wall clock time, used by
erlang:system_time/1
- Parameters:
t – the timespec that will be updated.
-
void sys_unregister_listener(GlobalContext *global, EventListener *listener)
Unregister a listener.
This function is called by ports to unregister a listener which is a native alternative to select events. The actual definition of listeners is platform dependent.
- Parameters:
global – the global context.
listener – the listener to unregister.
-
void sys_unregister_select_event(GlobalContext *glb, ErlNifEvent event, bool is_write)
Update the select set by removing an event for reading or writing.
This function probably should update set and call
sys_signal
so new set is taken into account. After this function is called,sys_poll_events
must check for closed select events.- Parameters:
glb – the global context.
event – the event (file descriptor) to remove from the set
is_write – whether to remove the event for writing (as opposed to reading)
-
term term_alloc_refc_binary(size_t size, bool is_const, Heap *heap, GlobalContext *glb)
Create a reference-counted binary on the heap.
This function will create a reference-counted binary on the heap. If the data supplied is “const” (e.g., read from a literal in a BEAM file), then the returned term will point directly to the supplied data, and will not technically be reference-counted. Otherwise, a block of memory will be allocated to contain a copy of the data, in addition to a reference counter, so that the block can be free’d when no other terms reference the created object. (The reference count will be initialized to 1). If the data is non-NULL, it will be copied into the newly allocated block of memory.
- Parameters:
size – the size (in bytes) of the data to allocate
is_const – designates whether the data pointed to is “const”, such as a term literal
heap – the heap to allocate the binary in
glb – the global context as refc binaries are global
- Returns:
a term (reference) pointing to the newly allocated binary in the process heap.
-
term term_alloc_sub_binary(term binary, size_t offset, size_t len, Heap *heap)
Create a sub-binary.
This function will create a sub-binary on the heap, using the supplied binary, offset into the binary, and length of the sub-binary. This function assumes the length of the referenced binary is greater or equal to offset + len.
- Parameters:
binary – the referenced binary
offset – the offset into the referenced binary to start the sub-binary
len – the length (in bytes) of the sub-binary
heap – the heap to allocate the binary in
- Returns:
a term (reference) pointing to the newly allocated sub-binary in the process heap.
-
static inline term term_alloc_tuple(uint32_t size, Heap *heap)
Allocates a tuple on a context heap.
Allocates an uninitialized tuple on the heap with given arity.
- Parameters:
size – tuple arity (count of tuple elements).
heap – the heap to allocate memory in
- Returns:
a term pointing on an empty tuple allocated on the heap.
-
static inline const char *term_binary_data(term t)
Gets binary data.
Returns a pointer to stored binary data.
- Parameters:
t – a term pointing to binary data. Fails if t is not a binary term.
- Returns:
a const char * pointing to binary internal data.
-
static inline size_t term_binary_data_size_in_terms(size_t size)
The count of terms needed to store the given amount of bytes.
Returns the count of terms needed to store the given size in bytes.
- Parameters:
size – the size in bytes
- Returns:
the count of terms
-
static inline unsigned long term_binary_size(term t)
Gets binary size.
Returns binary size for a given binary term.
- Parameters:
t – a term pointing to binary data. Fails if t is not a binary term.
- Returns:
binary size in bytes.
-
static inline size_t term_binary_heap_size(size_t size)
The size (in terms) of a binary of size-many bytes in the heap.
Returns the number of terms needed in the heap to store a binary of a given size (in bytes)
- Parameters:
size – the size of the binary (in bytes)
- Returns:
the size (in terms) of a binary of size-many bytes in the heap
-
static inline bool term_binary_size_is_heap_binary(size_t size)
Determine whether a binary should be a heap binary or not.
Returns true if a binary of the specified size should be allocated in the process heap (as opposed to being a refc binary)
- Parameters:
size – the intended binary size
- Returns:
true if the binary should be allocated in the process heap; false, otherwise.
-
static inline size_t term_boxed_size(term t)
Returns size of a boxed term.
Returns the size of a boxed term in term units.
- Parameters:
t – the boxed term.
- Returns:
size of given term.
-
static inline int term_bs_insert_binary(term t, int offset, term src, int n)
Insert an binary into a binary (using bit syntax).
Insert the data from the input binary, starting at the bit position starting in offset.
- Parameters:
t – a term pointing to binary data. Fails if t is not a binary term.
offset – the bitwise offset in t at which to start writing the integer value
src – binary source to insert binary data into.
n – the number of low-order bits from value to write.
- Returns:
0 on success; non-zero value if: t is not a binary term n is greater than the number of bits in an integer there is insufficient capacity in the binary to write these bits In general, none of these conditions should apply, if this function is being called in the context of generated bit syntax instructions.
-
TermCompareResult term_compare(term t, term other, TermCompareOpts opts, GlobalContext *global)
Compares two terms.
Tells if first term is >, < or == to the second term.
- Parameters:
t – the first term.
other – the second term.
opts – a value of 1 will compare exact equality, 0 for less strict equality.
global – the global context.
- Returns:
any of TermEquals, TermLessThan, TermGreaterThan or TermCompareMemoryAllocFail error.
-
static inline term term_create_empty_binary(size_t size, Heap *heap, GlobalContext *glb)
Create an empty binary. All bytes in the binary are initialized to 0x00.
Allocates a binary on the heap, and returns a term pointing to it.
- Parameters:
size – size of binary data buffer.
heap – the heap to allocate memory in
glb – the global context as refc binaries are global
- Returns:
a term pointing to the boxed binary pointer.
-
static inline term term_create_uninitialized_binary(size_t size, Heap *heap, GlobalContext *glb)
Create an uninitialized binary.
Allocates a binary on the heap, and returns a term pointing to it. Note that the data in the binary is uninitialized and could contain any garbage. Make sure to initialize before use, if needed (e.g., via memset). The binary may be allocated as a refc if it is large enough.
- Parameters:
size – size of binary data buffer.
heap – the heap to allocate the binary in
glb – the global context as refc binaries are global
- Returns:
a term pointing to the boxed binary pointer.
-
void term_display(FILE *fd, term t, const Context *ctx)
Prints a term to stdout.
Print any term to the given file.
- Parameters:
fd – the file where the term will be printed.
t – the term that will be printed.
ctx – the context.
-
int term_fprint(FILE *fd, term t, const GlobalContext *global)
Prints a term to the given file.
Print any given term to the given file.
- Parameters:
fd – the file where the term will be printed.
t – the term that will be printed.
global – the
GlobalContext
.
- Returns:
the number of printed characters.
-
static inline term term_from_atom_index(int atom_index)
Term from global atom table index.
Returns a term from the given global atom table index.
- Parameters:
atom_index – global atoms table index.
- Returns:
a term that encapsulates the atom.
-
static inline term term_from_int11(int16_t value)
Term from int11.
Returns a term for a given 11 bits integer value.
- Parameters:
value – the value that will be converted to a term.
- Returns:
a term that encapsulates the integer value.
-
static inline term term_from_int32(int32_t value)
Term from int32.
Returns a term for a given 32 bits integer value.
- Parameters:
value – the value that will be converted to a term.
- Returns:
a term that encapsulates the integer value.
-
static inline term term_from_int4(int8_t value)
Term from int4.
Returns a term for a given 4 bits integer value.
- Parameters:
value – the value that will be converted to a term.
- Returns:
a term that encapsulates the integer value.
-
static inline term term_from_literal_binary(const void *data, size_t size, Heap *heap, GlobalContext *glb)
Term from binary data.
Allocates a binary on the heap, and returns a term pointing to it.
- Parameters:
data – binary data.
size – size of binary data buffer.
heap – the heap to allocate the binary in
glb – the global context as refc binaries are global
- Returns:
a term pointing to the boxed binary pointer.
-
static inline term term_from_local_process_id(uint32_t local_process_id)
Term from local process id.
Returns a term for a given local process table index.
- Parameters:
local_process_id – the local process table index that will be converted to a term.
- Returns:
a term that encapsulates a PID.
-
static inline term term_from_ref_ticks(uint64_t ref_ticks, Heap *heap)
Get a ref term from ref ticks.
- Parameters:
ref_ticks – an unique uint64 value that will be used to create ref term.
heap – the heap to allocate memory in
- Returns:
a ref term created using given ref ticks.
-
static inline term term_from_resource(void *resource, Heap *heap)
Create a resource on the heap.
This function creates a resource (obtained from
enif_alloc_resource
) on the heap which must haveTERM_BOXED_RESOURCE_SIZE
free terms.Unlike
enif_make_resource
, this function doesn’t increment the reference counter but instead makes the heap own the resource. It will be garbage collected when the heap is destroyed.- Parameters:
resource – resource obtained from
enif_alloc_resource
heap – the heap to allocate the resource in
- Returns:
a term pointing to the resource
-
int term_funprint(PrinterFun *pf, term t, const GlobalContext *global)
Prints a term using given printer fun.
Print any given term using a printer fun
- Parameters:
pf – function that will handle printing.
t – the term that will be printed.
global – the
GlobalContext
.
- Returns:
the number of printed characters.
-
static inline term term_get_list_head(term t)
Gets list head.
Returns given list head term
- Parameters:
t – a term pointing to a valid list (cons)
- Returns:
list head term
-
static inline term *term_get_list_ptr(term t)
Gets a term * pointing to a list.
Returns a term * pointer to a list (cons) from a given term.
- Parameters:
t – a term that points to a valid cons.
- Returns:
a term * pointing to the head of the first cell of a list.
-
static inline term term_get_list_tail(term t)
Gets list item tail.
Returns the tail, which is either a pointer to the next list item or nil, of the given list (that is not list tail).
- Returns:
list item tail term.
-
static inline size_t term_get_size_from_boxed_header(term header)
Returns size of a boxed term from its header.
Returns the size that is stored in boxed term header most significant bits.
- Parameters:
header – the boxed term header.
- Returns:
the size of the boxed term that follows the header. 0 is returned if the boxed term is just the header.
-
static inline term term_get_tuple_element(term t, int elem_index)
Returns the nth tuple element.
Returns the nth element for a given tuple pointed by a term.
- Parameters:
t – a term that points to a tuple, fails otherwise.
elem_index – index of the nth element that will be returned.
- Returns:
nth tuple term.
-
static inline term term_invalid_term()
Gets invalid term.
Returns always an invalid term.
- Returns:
invalid term.
-
static inline int term_is_atom(term t)
Checks if a term is an atom.
Returns 1 if a term is an atom, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_binary(term t)
Checks if a term is a binary.
Returns 1 if a term is a binary stored on the heap, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_boxed(term t)
Checks if a term is a boxed value.
Returns 1 if a term is a boxed value stored on the heap, such as a tuple, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_cp(term t)
Checks if a term is a saved CP.
Returns 1 if a term is a saved continuation pointer, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_function(term t)
Checks if a term is a fun.
Returns 1 if a term is a fun, otherwise 0.
- Deprecated:
renamed to term_is_fun.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_integer(term t)
Checks if a term is an integer value.
Returns 1 if a term is an integer value, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_invalid_term(term t)
Check if a term is an invalid term.
Returns 1 if a term is an invalid term, otherwise 0 is returned.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_list(term t)
Checks if a term is a list.
Returns 1 if a term is a list (cons) or an empty list (nil term), otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_movable_boxed(term t)
Checks if a term is a movable boxed value.
Returns 1 if a term is a boxed value that can be safely copied with memcpy.
- Parameters:
t – the term that will checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_nil(term t)
Checks if a term is nil.
Returns 1 if a term is nil, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_nonempty_list(term t)
Checks if a term is a non empty list.
Returns 1 if a term is a non empty list (cons), otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
bool term_is_otp_socket(term socket_term)
Determine if a term is a socket term.
- Parameters:
socket_term – the term to test
- Returns:
true if it is a term
-
static inline bool term_is_refc_binary(term t)
Checks if a term is a binary.
Returns 1 if a term is a binary stored on the heap, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline bool term_is_sub_binary(term t)
Checks if a term is a sub-binary.
Returns true if a term is a sub-binary; false, otherwise.
- Parameters:
t – the term that will be checked.
- Returns:
true if check succeeds; false, otherwise.
-
static inline int term_is_pid(term t)
Checks if a term is a pid.
Returns 1 if a term is a process id, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_reference(term t)
Checks if a term is a reference.
Returns 1 if a term is a reference, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_string(term t)
Checks if a term is a string (i.e., a list of characters)
Returns 1 if a term is a proper (nil-terminated) list of characters or an empty list (nil term), otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline int term_is_tuple(term t)
Checks if a term is a tuple.
Returns 1 if a term is a tuple, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline uint8_t term_is_uint8(term t)
Checks if a term is a uint8_t.
Returns 1 if a term is an integer value in the [0, 255] range, otherwise 0.
- Parameters:
t – the term that will be checked.
- Returns:
1 if check succeeds, 0 otherwise.
-
static inline term term_list_from_list_ptr(term *list_elem)
Gets list term from pointer.
Return given list term from a list element pointer.
- Parameters:
list_elem – a pointer to a list element.
- Returns:
a list term
-
static inline term term_list_init_prepend(term *list_elem, term head, term tail)
Prepends a term to an existing list.
Initializes a list item, set head to the given term and points tail to the given next item (that might be nil).
- Parameters:
head – term, the encapsulated list item value.
tail – either nil or next list item.
list_elem – the memory area that will be initialized.
- Returns:
a term pointing to the newly initialized list item.
-
static inline int term_list_length(term t, int *proper)
Returns list length.
Counts the number of list items
- Returns:
number of list items
-
static inline term term_list_prepend(term head, term tail, Heap *heap)
Prepends a term to an existing list.
Allocates a new list item, set head to the given term and points tail to the given next item (that might be nil).
- Parameters:
head – term, the encapsulated list item value.
tail – either nil or next list item.
heap – the heap to allocate memory in
- Returns:
a term pointing to the newly created list item.
-
static inline term term_maybe_create_sub_binary(term binary, size_t offset, size_t len, Heap *heap, GlobalContext *glb)
(Maybe) create a sub-binary — if not, create a heap binary.
Allocates a sub-binary if the source binary is reference-counted binary and if the length of the sub-binary is sufficiently large.
- Parameters:
binary – source binary
offset – offset into the source binary marking the start of the sub-binary
len – desired length of the sub-binary
heap – the heap to allocate memory in
glb – the global context as refc binaries are global
- Returns:
a term pointing to the boxed binary pointer.
-
static inline term term_nil()
Gets nil value.
Returns always the nil value.
- Returns:
nil value term.
-
static inline void term_put_tuple_element(term t, uint32_t elem_index, term put_value)
Replaces the content of a tuple element.
Destructively replaces the nth element of an existing tuple, it should be used only on newly allocated tuples.
- Parameters:
t – the term pointing to the target tuple, fails if not a tuple.
elem_index – the index of the element that will be replaced.
put_value – the term that will be put on the nth tuple element.
-
static inline void *term_refc_binary_ptr(term refc_binary)
Get the pointer off heap refc binary.
Returns address
- Returns:
offset (in words).
-
int term_snprint(char *buf, size_t size, term t, const GlobalContext *global)
Write a term to a string as text.
Print any given term to the given buffer.
- Parameters:
buf – the buffer where the term will be printed.
size – the buffer size.
t – the term that will be printed.
global – the
GlobalContext
.
- Returns:
the number of printed characters.
-
static inline size_t term_sub_binary_heap_size(term binary, size_t len)
Get the number of words in the heap to allocate for a sub-binary.
This function is used to compute the number of words needed on the heap to allocate for a sub-binary. This function is typically used in conjunction with term_maybe_create_sub_binary
- Parameters:
binary – source binary
len – desired length of the sub-binary
- Returns:
the number of words needed to allocate on the process heap for the desired sub-binary
-
static inline int term_to_atom_index(term t)
Gets global atom table index.
Returns atom table index for given atom term.
- Parameters:
t – the term that will be converted to atom table index. t must be a valid atom term.
- Returns:
a global atom table index.
-
static inline const term *term_to_const_term_ptr(term t)
Gets a const pointer to a term stored on the heap.
Casts a term to a const term * that points to a value stored on the heap.
- Parameters:
t – the term that will be casted, it must be valid.
- Returns:
a const pointer to a term.
-
static inline int32_t term_to_int32(term t)
Term to int32.
Returns an int32 for a given term. No overflow check is executed.
- Parameters:
t – the term that will be converted to int32, term type is checked.
- Returns:
a int32 value.
-
static inline int32_t term_to_local_process_id(term t)
Gets process table index.
Returns local process table index for given atom term.
- Parameters:
t – the term that will be converted to local process table index, term type is checked.
- Returns:
a local process table index.
-
bool term_to_otp_socket(term socket_term, struct SocketResource **otp_socket, Context *ctx)
Get the resource object associated with a socket term.
- Parameters:
socket_term – the term with the socket
otp_socket – on output, the socket resource
ctx – the current context
- Returns:
true in case of success
-
static inline term *term_to_term_ptr(term t)
Gets a pointer to a term stored on the heap.
Casts a term to a term * that points to a value stored on the heap. Be aware: terms are assumed to be immutable.
- Parameters:
t – the term that will be casted, it must be valid.
- Returns:
a pointer to a term.
-
static inline uint8_t term_to_uint8(term t)
Term to uint8.
Returns an uint8 for a given term. No overflow check is executed.
- Parameters:
t – the term that will be converted to uint8.
- Returns:
an uint8_t value.
-
void timer_list_next(struct TimerList *tw, uint64_t now, timer_list_callback_t cb)
process the timer wheel, calling cb for every item that should be fired (for which
expiry_time
<=now
).The current algorithm is very basic. Under heavy load, two processes scheduled for different timers might be triggered (same seems to be true with BEAM). The only optimization is the next time is saved so the function doesn’t run every timer on every call.
- Parameters:
tw – the timer wheel
now – the current monotonic date
cb – the callback