erl_driver(3erl)

erl_driver (3erl) β€” C Library Functions πŸŽ€

πŸ’– NAME πŸ’–

erl_driver β€” API functions for an Erlang driver. πŸ’…

✨ DESCRIPTION ✨

Okay so picture this, bestie: an Erlang driver is a library that contains a set of native driver callback functions, and the Erlang Virtual Machine calls those functions when certain events occur. There can be multiple instances of a driver, and each instance is associated with an Erlang port. 🌸

⚠️ Warning ⚠️

Use this functionality with extreme care. 🫣

A driver callback is executed as a direct extension of the native code of the VM. Execution is not made in a safe environment. The VM cannot provide the same services as provided when executing Erlang code, such as pre-emptive scheduling or memory protection. If the driver callback function does not behave well, the whole VM will misbehave. No cap.

  • A driver callback that crashes will crash the whole VM. πŸ’€
  • An erroneously implemented driver callback can cause a VM internal state inconsistency, which can cause a crash of the VM, or miscellaneous misbehaviors of the VM at any point after the call to the driver callback. 😭
  • A driver callback doing lengthy work before returning degrades responsiveness of the VM and can cause miscellaneous strange behaviors. Such strange behaviors include, but are not limited to, extreme memory usage and bad load balancing between schedulers. Strange behaviors that can occur because of lengthy work can also vary between Erlang/OTP releases. It’s giving chaos gremlin energy, fr fr.

As from ERTS 5.5.3 the driver interface has been extended (see extended marker). The extended interface introduces version management, the possibility to pass capability flags (see driver_flags) to the runtime system at driver initialization, and some new driver API functions. ✨

πŸ“ Note πŸ“

As from ERTS 5.9 old drivers must be recompiled and use the extended interface. They must also be adjusted to the 64-bit capable driver interface. 🫢

The driver calls back to the emulator, using the API functions declared in erl_driver.h. They are used for outputting data from the driver, using timers, and so on. πŸ¦‹

Each driver instance is associated with a port. Every port has a port owner process. Communication with the port is normally done through the port owner process. Most of the functions take the port handle as an argument. This identifies the driver instance. Notice that this port handle must be stored by the driver, it is not given when the driver is called from the emulator (see driver_entry). πŸ‘‘

Some of the functions take a parameter of type ErlDrvBinary, a driver binary. It is to be both allocated and freed by the caller. Using a binary directly avoids one extra copying of data. Efficient queen behavior. πŸ’…

Many of the output functions have a "header buffer", with hbuf and hlen parameters. This buffer is sent as a list before the binary (or list, depending on port mode) that is sent. This is convenient when matching on messages received from the port. (Although in the latest Erlang versions there is the binary syntax, which enables you to match on the beginning of a binary.) πŸŽ€

Drivers are locked either on driver level or port level (driver instance level). By default driver level locking will be used, that is, only one emulator thread will execute code in the driver at a time. If port level locking is used, multiple emulator threads can execute code in the driver at the same time. Only one thread at a time will call driver callbacks corresponding to the same port, though. To enable port level locking, set the ERL_DRV_FLAG_USE_PORT_LOCKING driver flag in the driver_entry used by the driver. When port level locking is used, the driver writer is responsible for synchronizing all accesses to data shared by the ports (driver instances). πŸ”₯

Most drivers written before the runtime system with SMP support existed can run in the runtime system with SMP support, without being rewritten, if driver level locking is used. ⭐

πŸ“ Note πŸ“

It is assumed that drivers do not access other drivers. If drivers access each other, they must provide their own mechanism for thread-safe synchronization. Such "inter-driver communication" is strongly discouraged. πŸ™ˆ

πŸ“ Note πŸ“

Regardless of locking scheme used, calls to driver callbacks can be made from different threads. πŸŒ€

Most functions in this API are not thread-safe, that is, they cannot be called from arbitrary threads. Functions that are not documented as thread-safe can only be called from driver callbacks or function calls descending from a driver callback call. Notice that driver callbacks can be called from different threads. This, however, is not a problem for any function in this API, as the emulator has control over these threads. 🧚

⚠️ Warning ⚠️

Functions not explicitly documented as thread-safe are not thread safe. 🚨

A function not explicitly documented as thread-safe can, at some point in time, have a thread-safe implementation in the runtime system. Such an implementation can however change to a thread unsafe implementation at any time without any notice. So don’t get comfortable, bestie.

Only use functions explicitly documented as thread-safe from arbitrary threads. πŸ’œ

As mentioned in the warning text at the beginning of this section, it is of vital importance that a driver callback returns relatively fast. It is difficult to give an exact maximum amount of time that a driver callback is allowed to work, but usually a well-behaving driver callback is to return within 1 millisecond. This can be achieved using different approaches. If you have full control over the code to execute in the driver callback, the best approach is to divide the work into multiple chunks of work, and trigger multiple calls to the time-out callback using zero time-outs. Function erl_drv_consume_timeslice can be useful to determine when to trigger such time-out callback calls. However, sometimes it cannot be implemented this way, for example when calling third-party libraries. In this case, you typically want to dispatch the work to another thread. Information about thread primitives is provided below. 🌈

✨ FUNCTIONALITY ✨

Okay bestie, real talk: every single thing a driver needs to do with Erlang goes through driver API functions. The functionality menu is:

⏰ Timer functions ⏰

Control the timer that a driver can use. The timer has the emulator call the timeout entry function after a specified time. Only one timer is available for each driver instance. One timer per driver instance, fr fr.

πŸŽ€ Queue handling πŸŽ€

Every driver instance has an associated queue. This queue is a SysIOVec, which works as a buffer. It is mostly used for the driver to buffer data that is to be written to a device, and it is a byte stream. If the port owner process closes the driver, and the queue is not empty, the driver is not closed. This enables the driver to flush its buffers before closing.

The queue can be manipulated from any threads if a port data lock is used. For more information, see ErlDrvPDL.

πŸ“€ Output functions πŸ“€

With these functions, the driver sends data back to the emulator. The data is received as messages by the port owner process, see erlang:open_port/2. The vector function and the function taking a driver binary are faster, as they avoid copying the data buffer. There is also a fast way of sending terms from the driver, without going through the binary term format. Fast path unlocked.

πŸ’€ Failure πŸ’€

The driver can exit and signal errors up to Erlang. This is only for severe errors, when the driver cannot possibly keep open. Like, cannot-possibly-keep-open severe. No casual flaking allowed.

🌈 Asynchronous calls 🌈

Erlang/OTP R7B and later versions have provision for asynchronous function calls, using a thread pool provided by Erlang. There is also a select call, which can be used for asynchronous drivers.

🧡 Multi-threading 🧡

A POSIX thread like API for multi-threading is provided. The Erlang driver thread API only provides a subset of the functionality provided by the POSIX thread API. The subset provided is more or less the basic functionality needed for multi-threaded programming:

  • Threads
  • Mutexes
  • Condition variables
  • Read/write locks
  • Thread-specific data

The Erlang driver thread API can be used in conjunction with the POSIX thread API on UN-ices and with the Windows native thread API on Windows. The Erlang driver thread API has the advantage of being portable, but there can exist situations where you want to use functionality from the POSIX thread API or the Windows native thread API.

The Erlang driver thread API only returns error codes when it is reasonable to recover from an error condition. If it is not reasonable to recover from an error condition, the whole runtime system is terminated. For example, if a create mutex operation fails, an error code is returned, but if a lock operation on a mutex fails, the whole runtime system is terminated. So yeah, lock failures are emulator-ending, not a vibe.

Notice that there is no "condition variable wait with time-out" in the Erlang driver thread API. This because of issues with pthread_cond_timedwait. When the system clock suddenly is changed, it is not always guaranteed that you will wake up from the call as expected. An Erlang runtime system must be able to cope with sudden changes of the system clock. Therefore, we have omitted it from the Erlang driver thread API. In the Erlang driver case, time-outs can and are to be handled with the timer functionality of the Erlang driver API.

Notice that many functions in the Erlang driver API are not thread-safe. If a function is not documented as thread-safe, it is not thread-safe. This is the iykyk of driver threading.

πŸ“ Note πŸ“

When executing in an emulator thread, it is very important that you unlock all locks you have locked before letting the thread out of your control; otherwise you are very likely to deadlock the whole emulator. If you need to use thread-specific data in an emulator thread, only have the thread-specific data set while the thread is under your control, and clear the thread-specific data before you let the thread out of your control. In the future, debug functionality will probably be integrated with the Erlang driver thread API. All functions that create entities take a name argument. Currently the name argument is unused, but it will be used when the debug functionality is implemented. If you name all entities created well, the debug functionality will be able to give you better error reports.

🧩 Adding/removing drivers 🧩

A driver can add and later remove drivers.

πŸ‘€ Monitoring processes πŸ‘€

A driver can monitor a process that does not own a port.

🏷️ Version management 🏷️

Version management is enabled for drivers that have set the extended_marker field of their driver_entry to ERL_DRV_EXTENDED_MARKER. erl_driver.h defines:

  • ERL_DRV_EXTENDED_MARKER
  • ERL_DRV_EXTENDED_MAJOR_VERSION, which is incremented when driver incompatible changes are made to the Erlang runtime system. Normally it suffices to recompile drivers when ERL_DRV_EXTENDED_MAJOR_VERSION has changed, but it can, under rare circumstances, mean that drivers must be slightly modified. If so, this will of course be documented.
  • ERL_DRV_EXTENDED_MINOR_VERSION, which is incremented when new features are added. The runtime system uses the minor version of the driver to determine what features to use.

The runtime system normally refuses to load a driver if the major versions differ, or if the major versions are equal and the minor version used by the driver is greater than the one used by the runtime system. Old drivers with lower major versions are however allowed after a bump of the major version during a transition period of two major releases. Such old drivers can, however, fail if deprecated features are used.

The emulator refuses to load a driver that does not use the extended driver interface, to allow for 64-bit capable drivers, as incompatible type changes for the callbacks output, control, and call were introduced in Erlang/OTP R15B. A driver written with the old types would compile with warnings and when called return garbage sizes to the emulator, causing it to read random memory and create huge incorrect result blobs.

Therefore it is not enough to only recompile drivers written with version management for pre R15B types; the types must be changed in the driver suggesting other rewrites, especially regarding size variables. Investigate all warnings when recompiling.

Also, the API driver functions driver_output* and driver_vec_to_buf, driver_alloc/realloc*, and the driver_* queue functions were changed to have larger length arguments and return values. This is a lesser problem, as code that passes smaller types gets them auto-converted in the calls, and as long as the driver does not handle sizes that overflow an int, all will work as before.

⏱️ Time measurement ⏱️

Support for time measurement in drivers:

  • ErlDrvTime
  • ErlDrvTimeUnit
  • erl_drv_monotonic_time
  • erl_drv_time_offset
  • erl_drv_convert_time_unit

✨ REWRITES FOR 64-BIT DRIVER INTERFACE ✨

okay so real talk bestie, this is the glow-up era of drivers πŸ’…

ERTS 5.9 rolled in with two brand-new integer types, ErlDrvSizeT and ErlDrvSSizeT, and these babies can hold 64-bit sizes if they need to. iconic of them honestly 🫢


🚩 the "i'll deal with it later" trap

So here's the thing β€” if you don't update your driver and just recompile it, it probably works when you're building for a 32-bit machine, and that is lowkey a false sense of security πŸ™ˆ. Hopefully that whole situation throws a bunch of important warnings at you. But the second you recompile that same driver later on a 64-bit machine, you're getting warnings and almost certainly crashes. so no cap: postponing the update and not fixing the warnings is a bad idea. fix it now, thank me later πŸŽ€

When you recompile with gcc, use the flag -Wstrict-prototypes to get better warnings. If you're on a different compiler, go find a similar flag β€” iykyk. πŸ”


πŸ—’οΈ the checklist (most important first, periodt)

The following is a checklist for rewriting a pre-ERTS 5.9 driver, most important first:

πŸ₯‡ Return types for driver callbacks

  • Rewrite driver callback control to use return type ErlDrvSSizeT instead of int.
  • Rewrite driver callback call to use return type ErlDrvSSizeT instead of int.
⚠️ Note: These changes are essential β€” not just for aesthetics, we're talking don't crash the emulator or worse, cause malfunction. Without them, a driver can return garbage in the high 32 bits to the emulator, which makes it build a huge result out of random bytes β€” and then it either crashes on memory allocation or succeeds with a random result from the driver call. absolutely not the vibe 😭

πŸ₯ˆ Arguments to driver callbacks

  • Driver callback output now gets ErlDrvSizeT as 3rd argument instead of previously int.
  • Driver callback control now gets ErlDrvSizeT as 4th and 6th arguments instead of previously int.
  • Driver callback call now gets ErlDrvSizeT as 4th and 6th arguments instead of previously int.
  • Sane compiler's calling conventions probably make these changes necessary only for a driver to handle data chunks that require 64-bit size fields (mostly larger than 2 GB, since that's what an int of 32 bits can hold). But it is possible to think of non-sane calling conventions that would make the driver callbacks mix up the arguments, causing malfunction. πŸ’€
⚠️ Note: The argument type change is from signed to unsigned. This can cause problems for, for example, loop termination conditions or error conditions if you only change the types all over the place. read that again bestie 🫢

πŸ₯‰ Larger size field in ErlIOVec

  • The size field in ErlIOVec has been changed to ErlDrvSizeT from int. Check all code that uses that field. πŸ‘€
  • Automatic type-casting probably makes these changes necessary only for a driver that encounters sizes > 32 bits.
⚠️ Note: The size field changed from signed to unsigned. This can cause problems for, for example, loop termination conditions or error conditions if you only change the types all over the place. (yes this is the same warning, it's that serious, don't @ me 🌸)

πŸ… Arguments and return values in the driver API

Many driver API functions have changed argument type and/or return value to ErlDrvSizeT from mostly int. Automatic type-casting probably makes these changes necessary only for a driver that encounters sizes > 32 bits.

Here's the full roster, main characters only 🌈:

  • driver_output
    • 3rd argument
  • driver_output2
    • 3rd and 5th arguments
  • driver_output_binary
    • 3rd, 5th, and 6th arguments
  • driver_outputv
    • 3rd and 5th arguments
  • driver_vec_to_buf
    • 3rd argument and return value
  • driver_alloc
    • 1st argument
  • driver_realloc
    • 2nd argument
  • driver_alloc_binary
    • 1st argument
  • driver_realloc_binary
    • 2nd argument
  • driver_enq
    • 3rd argument
  • driver_pushq
    • 3rd argument
  • driver_deq
    • 2nd argument and return value
  • driver_sizeq
    • Return value
  • driver_enq_bin
    • 3rd and 4th arguments
  • driver_pushq_bin
    • 3rd and 4th arguments
  • driver_enqv
    • 3rd argument
  • driver_pushqv
    • 3rd argument
  • driver_peekqv
    • Return value
⚠️ Note: This is a change from signed to unsigned. This can cause problems for, for example, loop termination conditions and error conditions if you only change the types all over the place. (notice it says and this time β€” everybody say thank you, careful reading πŸ’–)

✨ DATA TYPES ✨

Okay bestie, buckle up β€” this is the cast of characters, the little structs and typedefs that show up everywhere in driver land. No skipping, every single one matters πŸ’…

  • ErlDrvSizeT: β€” an unsigned integer type that you use as size_t. That's it, that's the whole vibe.
  • ErlDrvSSizeT: β€” a signed integer type, and it's the same size as ErlDrvSizeT.
  • ErlDrvSysInfo: β€” the info-dump struct. Here's the whole thing:
typedef struct ErlDrvSysInfo {
   int driver_major_version;
   int driver_minor_version;
   char *erts_version;
   char *otp_release;
   int thread_support;
   int smp_support;
   int async_threads;
   int scheduler_threads;
   int nif_major_version;
   int nif_minor_version;
   int dirty_scheduler_support;
} ErlDrvSysInfo;

So the ErlDrvSysInfo structure is literally the storage unit for info about the Erlang runtime system. driver_system_info writes the system information into it when you pass it a reference to an ErlDrvSysInfo structure. The fields are giving very much "tell me everything" and they are:

  • driver_major_version: β€” the value of ERL_DRV_EXTENDED_MAJOR_VERSION when the runtime system was compiled. This value is the same as the value of ERL_DRV_EXTENDED_MAJOR_VERSION used when compiling the driver; otherwise the runtime system would have refused to load the driver. Iconic gatekeeping, honestly.
  • driver_minor_version: β€” the value of ERL_DRV_EXTENDED_MINOR_VERSION when the runtime system was compiled. This value can differ from the value of ERL_DRV_EXTENDED_MINOR_VERSION used when compiling the driver. So yeah, minor can be a little different, it's fine.
  • erts_version: β€” a string containing the version number of the runtime system (the same as returned by erlang:system_info(version)).
  • otp_release: β€” a string containing the OTP release number (the same as returned by erlang:system_info(otp_release)).
  • thread_support: β€” a value != 0 if the runtime system has thread support; otherwise 0.
  • smp_support: β€” a value != 0 if the runtime system has SMP support; otherwise 0.
  • async_threads: β€” the number of async threads in the async thread pool used by driver_async (the same as returned by erlang:system_info(thread_pool_size)).
  • scheduler_threads: β€” the number of scheduler threads used by the runtime system (the same as returned by erlang:system_info(schedulers)).
  • nif_major_version: β€” the value of ERL_NIF_MAJOR_VERSION when the runtime system was compiled.
  • nif_minor_version: β€” the value of ERL_NIF_MINOR_VERSION when the runtime system was compiled.
  • dirty_scheduler_support: β€” a value != 0 if the runtime system has support for dirty scheduler threads; otherwise 0.
  • ErlDrvBinary: β€” the binary struct, as sent between the emulator and the driver. Behold:
typedef struct ErlDrvBinary {
   ErlDrvSint orig_size;
   char orig_bytes[];
} ErlDrvBinary;

The ErlDrvBinary structure is a binary, as sent between the emulator and the driver. All binaries are reference counted; when driver_binary_free is called, the reference count is decremented, and when it reaches zero, the binary is deallocated. orig_size is the binary size and orig_bytes is the buffer. ErlDrvBinary has not a fixed size β€” its size is orig_size + 2 * sizeof(int). Not me doing math in public but okay πŸ’€

Note: The refc field has been removed. The reference count of an ErlDrvBinary is now stored elsewhere. The reference count of an ErlDrvBinary can be accessed through driver_binary_get_refc, driver_binary_inc_refc, and driver_binary_dec_refc.

Some driver calls, such as driver_enq_binary, increment the driver reference count, and others, such as driver_deq, decrement it.

Using a driver binary instead of a normal buffer is often faster, as the emulator needs not to copy the data, only the pointer is used. Efficient queen behavior ✨

A driver binary allocated in the driver, with driver_alloc_binary, is to be freed in the driver (unless otherwise stated) with driver_free_binary. (Notice that this does not necessarily deallocate it β€” if the driver is still referred in the emulator, the ref-count will not go to zero.) So like, free it, but also respect the ref-count, obviously.

Driver binaries are used in the driver_output2 and driver_outputv calls, and in the queue. Also the driver callback outputv uses driver binaries.

If the driver for some reason wants to keep a driver binary around β€” for example in a static variable β€” the reference count is to be incremented, and the binary can later be freed in the stop callback, with driver_free_binary.

Notice that a driver binary is shared by the driver and the emulator. A binary received from the emulator or sent to the emulator must not be changed by the driver. That's a hard no, bestie 🚫

Since ERTS 5.5 (Erlang/OTP R11B), orig_bytes is guaranteed to be properly aligned for storage of an array of doubles (usually 8-byte aligned). Alignment rights πŸ’–

  • ErlDrvData: β€” a handle to driver-specific data, passed to the driver callbacks. It is a pointer, and is most often type cast to a specific pointer in the driver. Classic "it's a pointer, cast it and go" energy.
  • SysIOVec: β€” a system I/O vector, as used by writev on Unix and WSASend on Win32. It is used in ErlIOVec. Very cross-platform of it.
  • ErlIOVec: β€” the I/O vector used by the emulator and drivers. Here's the struct:
typedef struct ErlIOVec {
  int vsize;
  ErlDrvSizeT size;
  SysIOVec* iov;
  ErlDrvBinary** binv;
} ErlIOVec;

The I/O vector used by the emulator and drivers is a list of binaries, with a SysIOVec pointing to the buffers of the binaries. It is used in driver_outputv and the outputv driver callback. Also, the driver queue is an ErlIOVec. She's everywhere, honestly.

  • ErlDrvMonitor: β€” when a driver creates a monitor for a process, a ErlDrvMonitor is filled in. This is an opaque data type that can be assigned to, but not compared without using the supplied compare function (that is, it behaves like a struct).

The driver writer is to provide the memory for storing the monitor when calling driver_monitor_process. The address of the data is not stored outside of the driver, so ErlDrvMonitor can be used as any other data β€” it can be copied, moved in memory, forgotten, and so on. Lowkey freeing, ngl.

  • ErlDrvNowData: β€” the time stamp structure. It holds a time stamp consisting of three values measured from some arbitrary point in the past. The three structure members are:
  • megasecs: β€” the number of whole megaseconds elapsed since the arbitrary point in time.
  • secs: β€” the number of whole seconds elapsed since the arbitrary point in time.
  • microsecs: β€” the number of whole microseconds elapsed since the arbitrary point in time.
  • ErlDrvPDL: β€” the port data lock situation. If certain port-specific data must be accessed from other threads than those calling the driver callbacks, a port data lock can be used to synchronize the operations on the data. Currently, the only port-specific data that the emulator associates with the port data lock is the driver queue.

Normally a driver instance has no port data lock. If the driver instance wants to use a port data lock, it must create the port data lock by calling driver_pdl_create.

Note: Once the port data lock has been created, every access to data associated with the port data lock must be done while the port data lock is locked. The port data lock is locked and unlocked by driver_pdl_lock and driver_pdl_unlock, respectively.

A port data lock is reference counted, and when the reference count reaches zero, it is destroyed. The emulator at least increments the reference count once when the lock is created and decrements it once the port associated with the lock terminates. The emulator also increments the reference count when an async job is enqueued and decrements it when an async job has been invoked. Also, the driver is responsible for ensuring that the reference count does not reach zero before the last use of the lock by the driver has been made. The reference count can be read, incremented, and decremented by driver_pdl_get_refc, driver_pdl_inc_refc, and driver_pdl_dec_refc, respectively. Ref-count girlies rise πŸ™Œ

  • ErlDrvTid: β€” thread identifier.

See also erl_drv_thread_create, erl_drv_thread_exit, erl_drv_thread_join, erl_drv_thread_self, and erl_drv_equal_tids.

  • ErlDrvThreadOpts: β€” thread options structure passed to erl_drv_thread_create. It's literally just this:
int suggested_stack_size;

The following field exists:

  • suggested_stack_size: β€” a suggestion, in kilowords, on how large a stack to use. A value < 0 means default size. It's a suggestion, not a demand, bestie.

See also erl_drv_thread_opts_create, erl_drv_thread_opts_destroy, and erl_drv_thread_create.

  • ErlDrvMutex: β€” mutual exclusion lock. Used for synchronizing access to shared data. Only one thread at a time can lock a mutex. Respect the lock or catch these threads πŸ”’

See also erl_drv_mutex_create, erl_drv_mutex_destroy, erl_drv_mutex_lock, erl_drv_mutex_trylock, and erl_drv_mutex_unlock.

  • ErlDrvCond: β€” condition variable. Used when threads must wait for a specific condition to appear before continuing execution. Condition variables must be used with associated mutexes. No solo cond, ever.

See also erl_drv_cond_create, erl_drv_cond_destroy, erl_drv_cond_signal, erl_drv_cond_broadcast, and erl_drv_cond_wait.

  • ErlDrvRWLock: β€” read/write lock. Used to allow multiple threads to read shared data while only allowing one thread to write the same data. Multiple threads can read lock an rwlock at the same time, while only one thread can read/write lock an rwlock at a time. Very "everyone can look, only one can touch" of it.

See also erl_drv_rwlock_create, erl_drv_rwlock_destroy, erl_drv_rwlock_rlock, erl_drv_rwlock_tryrlock, erl_drv_rwlock_runlock, erl_drv_rwlock_rwlock, erl_drv_rwlock_tryrwlock, and erl_drv_rwlock_rwunlock.

  • ErlDrvTSDKey: β€” key that thread-specific data can be associated with.

See also erl_drv_tsd_key_create, erl_drv_tsd_key_destroy, erl_drv_tsd_set, and erl_drv_tsd_get.

  • ErlDrvTime: β€” a signed 64-bit integer type for time representation. Big time vibes.
  • ErlDrvTimeUnit: β€” an enumeration of time units supported by the driver API:
  • ERL_DRV_SEC: β€” seconds.
  • ERL_DRV_MSEC: β€” milliseconds.
  • ERL_DRV_USEC: β€” microseconds.
  • ERL_DRV_NSEC: β€” nanoseconds.

πŸš€ EXPORTS πŸš€

Okay so here's where the driver actually exposes stuff to Erlang. This is the "let me introduce myself" section, and it starts with:

void add_driver_entry(ErlDrvEntry *de)
  • void add_driver_entry(ErlDrvEntry *de) β€” adds a driver entry to the list of drivers known by Erlang. The init function of parameter de is called. Like, it literally gets registered and then its init gets summoned.
Note: To use this function for adding drivers residing in dynamically loaded code is dangerous. If the driver code for the added driver resides in the same dynamically loaded module (that is, .so file) as a normal dynamically loaded driver (loaded with the erl_ddll interface), the caller is to call driver_lock_driver before adding driver entries. Danger danger, bestie β€” do the lock first πŸ’€
Heads up bestie: the previous function up there? Use of this function is generally deprecated. πŸ’€ Not gone, not forgotten, just… deprecated. We move.

  • void *driver_alloc(ErlDrvSizeT size) β€” gives you a memory block of exactly size bytes and hands you back a pointer to it. The only way this flops is out-of-memory, and then you get NULL back. (It's like, almost always a wrapper around malloc.) 🧚 Whatever you allocate here you HAVE to free yourself with a matching call to driver_free β€” unless the docs say otherwise somewhere. This function is thread-safe. 🫢
  • ErlDrvBinary *driver_alloc_binary(ErlDrvSizeT size) β€” allocates a driver binary with a memory block of at least size bytes, and gives you a pointer to it β€” or NULL if it fails (out of memory, bestie 😭). Once a driver binary has been sent to the emulator, you must not change it. Every allocated binary gets freed by a corresponding call to driver_free_binary, unless otherwise stated.

ok so important: a driver binary has an internal reference counter. That means calling driver_free_binary might not actually dispose of it β€” if it's been sent to the emulator, it can be referenced there. πŸ‘‘

The driver binary also has a field, orig_bytes, which marks the start of the data in the binary.

This function is thread-safe. ✨

  • long driver_async(ErlDrvPort port, unsigned int* key, void (*async_invoke)(void*), void* async_data, void (*async_free)(void*)) β€” performs an asynchronous call πŸ¦‹. The function async_invoke gets invoked in a thread separate from the emulator thread, which is exactly how the driver does time-consuming, blocking operations without blocking the emulator. main character move ngl.

The async thread pool size is settable with the command-line argument +A in erl(1). If there's no async thread pool available, the call is made synchronously in the thread calling driver_async. The current number of async threads in the async thread pool can be retrieved through driver_system_info.

If a thread pool is available, a thread is used. If argument key is NULL, the threads from the pool are used in a round-robin way β€” each call to driver_async uses the next thread in the pool. Set argument key and this behavior changes: the two same values of *key always get the same thread. πŸ’…

To ensure that a driver instance always uses the same thread, the following call can be used:

unsigned int myKey = driver_async_port_key(myPort);

r = driver_async(myPort, &myKey, myData, myFunc);

It's enough to initialize myKey once for each driver instance. πŸŽ€

If a thread is already working, the calls are queued up and executed in order. Using the same thread for each driver instance ensures the calls are made in sequence. Slay.

async_data is the argument to the functions async_invoke and async_free. It's typically a pointer to a structure containing a pipe or event that can be used to signal that the async operation completed. The data is to be freed in async_free. 🌸

When the async operation is done, the ready_async driver entry function is called. If ready_async is NULL in the driver entry, the async_free function is called instead.

The return value is -1 if the driver_async call fails. πŸ™ˆ

Note: as from ERTS 5.5.4.3 the default stack size for threads in the async-thread pool is 16 kilowords, that is, 64 kilobyte on 32-bit architectures. This small default size has been chosen because the amount of async-threads can be quite large. The default stack size is enough for drivers delivered with Erlang/OTP, but is possibly not sufficiently large for other dynamically linked-in drivers that use the driver_async functionality. A suggested stack size for threads in the async-thread pool can be configured through command-line argument +a in erl(1). πŸ’–
  • unsigned int driver_async_port_key(ErlDrvPort port) β€” calculates a key for later use in driver_async. The keys are evenly distributed so you get a fair mapping between port IDs and async thread IDs. iykyk ✨
Note: before Erlang/OTP R16, the port ID could be used as a key with proper casting, but after the rewrite of the port subsystem, this is no longer the case. With this function, you can achieve the same distribution based on port IDs as before Erlang/OTP R16. 🫢
  • long driver_binary_dec_refc(ErlDrvBinary *bin) β€” decrements the reference count on bin and returns the reference count reached after the decrement. This function is thread-safe. πŸ’…
Note: the reference count of a driver binary is normally to be decremented by calling driver_free_binary. driver_binary_dec_refc does not free the binary if the reference count reaches zero. Only use driver_binary_dec_refc when you're sure you're not gonna reach a reference count of zero. 😭
  • long driver_binary_get_refc(ErlDrvBinary *bin) β€” returns the current reference count on bin. This function is thread-safe. πŸŽ€
  • long driver_binary_inc_refc(ErlDrvBinary *bin) β€” increments the reference count on bin and returns the reference count reached after the increment. This function is thread-safe. 🌈
  • ErlDrvTermData driver_caller(ErlDrvPort port) β€” returns the process ID of the process that made the current call to the driver. That process ID can be used with driver_send_term to send data back to the caller. πŸ¦‹ driver_caller only returns valid data when you're currently executing in one of these driver callbacks:
    • start: β€” called from erlang:open_port/2.
    • output: β€” called from erlang:send/2 and erlang:port_command/2.
    • outputv: β€” called from erlang:send/2 and erlang:port_command/2.
    • control: β€” called from erlang:port_control/3.
    • call: β€” called from erlang:port_call/3.

Notice that this function is not thread-safe. ⚠️

  • int driver_cancel_timer(ErlDrvPort port) β€” cancels a timer set with driver_set_timer. The return value is 0. πŸ•
  • int driver_compare_monitors(const ErlDrvMonitor *monitor1, const ErlDrvMonitor *monitor2) β€” compares two ErlDrvMonitors. Can also be used to imply some artificial order on monitors, for whatever reason. πŸ‘‘

Returns 0 if monitor1 and monitor2 are equal, < 0 if monitor1 < monitor2, and > 0 if monitor1 > monitor2.

  • ErlDrvTermData driver_connected(ErlDrvPort port) β€” returns the port owner process. Notice that this function is not thread-safe. πŸ’€
  • ErlDrvPort driver_create_port(ErlDrvPort port, ErlDrvTermData owner_pid, char* name, ErlDrvData drv_data) β€” creates a new port executing the same driver code as the port creating the new port. it's giving "i made you" energy fr fr 🌸
    • port: β€” the port handle of the port (driver instance) creating the new port.
    • owner_pid: β€” the process ID of the Erlang process to become owner of the new port. This process will be linked to the new port. You usually want to use driver_caller(port) as owner_pid.
    • name: β€” the port name of the new port. You usually want to use the same port name as the driver name (the driver_name field of the driver_entry).
    • drv_data: β€” the driver-defined handle that is passed in later calls to driver callbacks. Notice that the driver start callback is not called for this new driver instance. The driver-defined handle is normally created in the driver start callback when a port is created through erlang:open_port/2.

The caller of driver_create_port is allowed to manipulate the newly created port when driver_create_port has returned. When port level locking is used, the creating port is only allowed to manipulate the newly created port until the current driver callback, which was called by the emulator, returns. ⚠️

  • int driver_demonitor_process(ErlDrvPort port, const ErlDrvMonitor *monitor) β€” cancels a monitor created earlier. Returns 0 if a monitor was removed and > 0 if the monitor no longer exists. πŸ™ˆ
  • ErlDrvSizeT driver_deq(ErlDrvPort port, ErlDrvSizeT size) β€” dequeues data by moving the head pointer forward in the driver queue by size bytes. The data in the queue is deallocated. Returns the number of bytes remaining in the queue on success, otherwise -1. πŸ’…

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call. 🫢

  • int driver_enq(ErlDrvPort port, char* buf, ErlDrvSizeT len) β€” enqueues data in the driver queue. The data in buf is copied (len bytes) and placed at the end of the driver queue. The driver queue is normally used in a FIFO way. πŸ“

The driver queue is available to queue output from the emulator to the driver (data from the driver to the emulator is queued by the emulator in normal Erlang message queues). This can be useful if the driver must wait for slow devices, and so on, and wants to yield back to the emulator. The driver queue is implemented as an ErlIOVec. ✨

When the queue contains data, the driver does not close until the queue is empty. 🌈

The return value is 0. This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.

  • int driver_enq_bin(ErlDrvPort port, ErlDrvBinary *bin, ErlDrvSizeT offset, ErlDrvSizeT len) β€” enqueues a driver binary in the driver queue. The data in bin at offset with length len is placed at the end of the queue. This function is most often faster than driver_enq, because no data must be copied. πŸ”₯

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.

The return value is 0.

  • int driver_enqv(ErlDrvPort port, ErlIOVec *ev, ErlDrvSizeT skip) β€” enqueues the data in ev, skipping the first skip bytes of it, at the end of the driver queue. It's faster than driver_enq, because no data must be copied. πŸ’–

The return value is 0.

Oh, and deadass, one last line about the function above: this function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call. πŸ’… Moving on!


πŸŽ€ the driver_failure girlies

int driver_failure(ErlDrvPort port, int error)
int driver_failure_atom(ErlDrvPort port, char *string)
int driver_failure_posix(ErlDrvPort port, int error)

Okay so these three are literally the "we need to talk" text to Erlang. They signal to Erlang that the driver has hit an error and is about to be closed. The port gets closed, and the tuple {'EXIT', error, Err} gets sent to the port owner process β€” where error is an error atom (that's driver_failure_atom and driver_failure_posix for you) or an integer (driver_failure, the O.G.).

Real talk though: only fail when things are genuinely severe, like the driver cannot possibly stay open β€” buffer allocation getting out of memory is the example the page gives. For normal, everyday errors it's way more appropriate to just send error codes with driver_output. Don't be dramatic for no reason. πŸ™ˆ

The return value is 0.


πŸ’€ driver_failure_eof

int driver_failure_eof(ErlDrvPort port)

Signals to Erlang that the driver has encountered an EOF and should be closed β€” unless the port was opened with option eof, in which case eof gets sent to the port instead. Otherwise the port is closed and an 'EXIT' message is sent to the port owner process.

The return value is 0.


🧚 driver_free

void driver_free(void *ptr)

Frees the memory that ptr is pointing at. That memory is to have been allocated with driver_alloc. And like, every allocated memory is to be deallocated β€” only once, bestie, literally only once. There is no garbage collection in drivers, so nobody's coming to clean up your mess. 😭

This function is thread-safe. 🫢


πŸ¦‹ driver_free_binary

void driver_free_binary(ErlDrvBinary *bin)

Frees a driver binary bin that you allocated earlier with driver_alloc_binary. Heads up though: since binaries in Erlang are reference counted, the binary can still be around afterwards. It's giving "we broke up but we still share a friend group".

This function is thread-safe.


πŸ‘‘ driver_get_monitored_process

ErlDrvTermData driver_get_monitored_process(ErlDrvPort port, const ErlDrvMonitor *monitor)

Returns the process ID associated with a living monitor. The glow-up here is that you can use it in the process_exit callback to get the process identification for the process that's exiting.

Returns driver_term_nil if the monitor no longer exists. (Ghosted. πŸ’”)


🌸 driver_get_now

int driver_get_now(ErlDrvNowData *now)
⚠️ Warning: This function is deprecated. Do not use it. Use erl_drv_monotonic_time (perhaps in combination with erl_drv_time_offset) instead. Like seriously, don't.

Reads a time stamp into the memory pointed to by parameter now. Wanna know about the specific fields? See ErlDrvNowData.

The return value is 0, unless the now pointer is invalid, in which case it's < 0. Rude but fair.


⭐ driver_lock_driver

int driver_lock_driver(ErlDrvPort port)

Locks the driver used by the port port in memory for the rest of the emulator process' lifetime. After this call, the driver behaves as one of Erlang's statically linked-in drivers. It's giving "I'm not leaving, I live here now". 🏠


🌈 driver_mk_atom

ErlDrvTermData driver_mk_atom(char *string)

Returns an atom given a name string. The atom is created and does not change, so you can save the return value and reuse it β€” which is way faster than looking up the atom over and over. Cache it, queen. ✨

Notice that this function is not thread-safe.

πŸ’œ driver_mk_port

ErlDrvTermData driver_mk_port(ErlDrvPort port)

Converts a port handle into the Erlang term format, usable in erl_drv_output_term and erl_drv_send_term.

Notice that this function is not thread-safe.

πŸ“ driver_monitor_process

int driver_monitor_process(ErlDrvPort port, ErlDrvTermData process, ErlDrvMonitor *monitor)

Starts monitoring a process from a driver. When a process is monitored, a process exit results in a call to the provided process_exit callback in the ErlDrvEntry structure. The ErlDrvMonitor structure gets filled in, for later removal or compare. Very "I'll know if you leave the group chat".

Parameter process is to be the return value of an earlier call to driver_caller or driver_connected call.

Returns 0 on success, < 0 if no callback is provided, and > 0 if the process is no longer alive. Three moods, honestly.


πŸ”₯ driver_output

int driver_output(ErlDrvPort port, char *buf, ErlDrvSizeT len)

Sends data from the driver up to the emulator. The data is received as terms or binary data, depending on how the driver port was opened.

The data is queued in the port owner process' message queue. Huge caveat: this does not yield to the emulator (as the driver and the emulator run in the same thread). No sneaky handoffs, bestie.

Parameter buf points to the data to send, and len is the number of bytes.

The return value for all output functions is 0 for normal use. If the driver is used for distribution, it can fail and return -1. πŸ’€


πŸŽ€ driver_output_binary

int driver_output_binary(ErlDrvPort port, char *hbuf, ErlDrvSizeT hlen, ErlDrvBinary* bin, ErlDrvSizeT offset, ErlDrvSizeT len)

Sends data to a port owner process from a driver binary. It has a header buffer (hbuf and hlen) just like driver_output2. Parameter hbuf can be NULL.

Parameter offset is an offset into the binary and len is the number of bytes to send.

Driver binaries are created with driver_alloc_binary.

The data in the header is sent as a list, and the binary as an Erlang binary in the tail of the list.

For example, if hlen is 2, the port owner process receives [H1, H2 | <<T>>].

The return value is 0 for normal use.

Notice that, using the binary syntax in Erlang, the driver application can match the header directly from the binary, so the header can be put in the binary, and hlen can be set to 0. Big brain move. 🧠

πŸ’€ driver_output_term

int driver_output_term(ErlDrvPort port, ErlDrvTermData* term, int n)
⚠️ Warning: This function is deprecated. Use erl_drv_output_term instead.

Parameters term and n work as in erl_drv_output_term.

Notice that this function is not thread-safe.

πŸ¦‹ driver_output2

int driver_output2(ErlDrvPort port, char *hbuf, ErlDrvSizeT hlen, char *buf, ErlDrvSizeT len)

First sends hbuf (length in hlen) data as a list, regardless of port settings. Then sends buf as a binary or list. For example, if hlen is 3, the port owner process receives [H1, H2, H3 | T].

The whole point of sending data as a list header is to facilitate matching on the data received. It's giving "here's the label so you know what you're looking at". 🏷️

The return value is 0 for normal use.


🌈 driver_outputv

int driver_outputv(ErlDrvPort port, char* hbuf, ErlDrvSizeT hlen, ErlIOVec *ev, ErlDrvSizeT skip)

Sends data from an I/O vector, ev, to the port owner process. It has a header buffer (hbuf and hlen), just like driver_output2.

Parameter skip is a number of bytes to skip of the ev vector from the head.

You get vectors of ErlIOVec type from the driver queue (see below), and the outputv driver entry function. You can also make them yourself, if you want to send several ErlDrvBinary buffers at once. Often it is faster to use driver_output or .

For example, if hlen is 2 and ev points to an array of three binaries, the port owner process receives [H1, H2, <<B1>>, <<B2>> | <<B3>>].

The return value is 0 for normal use.

The comment for driver_output_binary also applies for driver_outputv. iykyk πŸ’…


🫢 driver_pdl_create

ErlDrvPDL driver_pdl_create(ErlDrvPort port)

Creates a port data lock associated with the port.

Note: Once a port data lock has been created, it must be locked during all operations on the driver queue of the port. No exceptions, bestie.

Returns a newly created port data lock on success, otherwise NULL. The function fails if port is invalid or if a port data lock already has been associated with the port. One per port, we don't share. πŸ™…β€β™€οΈ


🌸 driver_pdl_dec_refc

long driver_pdl_dec_refc(ErlDrvPDL pdl)

Decrements the reference count of the port data lock passed as argument (pdl).

The current reference count after the decrement has been performed is returned.

This function is thread-safe.


⭐ driver_pdl_get_refc

long driver_pdl_get_refc(ErlDrvPDL pdl)

Returns the current reference count of the port data lock passed as argument (pdl). Just a little peek, no changes. πŸ‘€

This function is thread-safe.


πŸ’œ driver_pdl_inc_refc

long driver_pdl_inc_refc(ErlDrvPDL pdl)

Increments the reference count of the port data lock passed as argument (pdl).

The current reference count after the increment has been performed is returned.

This function is thread-safe.


πŸŽ€ driver_pdl_lock

void driver_pdl_lock(ErlDrvPDL pdl)

Locks the port data lock passed as argument (pdl). Locked in, literally. πŸ”’

This function is thread-safe.


πŸ¦‹ driver_pdl_unlock

void driver_pdl_unlock(ErlDrvPDL pdl)

Unlocks the port data lock passed as argument (pdl). Release her. πŸ•ŠοΈ

This function is thread-safe.


πŸ‘‘ driver_peekq

SysIOVec *driver_peekq(ErlDrvPort port, int *vlen)

Retrieves the driver queue as a pointer to an array of SysIOVecs. It also returns the number of elements in vlen. This is one of two ways to get data out of the queue.

Nothing is removed from the queue by this function β€” that must be done with driver_deq. Peek, don't snatch. πŸ‘€

The returned array is suitable to use with the Unix system call writev.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.


🌈 driver_peekqv

ErlDrvSizeT driver_peekqv(ErlDrvPort port, ErlIOVec *ev)

Retrieves the driver queue into a supplied ErlIOVec ev. It also returns the queue size. This is the other one of the two ways to get data out of the queue.

If ev is NULL, all ones β€” that is -1 type cast to ErlDrvSizeT β€” are returned. No cap, that's literally what it says. 😭

Nothing is removed from the queue by this function, that must be done with driver_deq.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.


πŸ“ driver_pushq

int driver_pushq(ErlDrvPort port, char* buf, ErlDrvSizeT len)

Puts data at the head of the driver queue. The data in buf is copied (len bytes) and placed at the beginning of the queue. Front of the line, main character energy. πŸ’…

The return value is 0.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.


πŸ”₯ driver_pushq_bin

int driver_pushq_bin(ErlDrvPort port, ErlDrvBinary *bin, ErlDrvSizeT offset, ErlDrvSizeT len)

And that's where this part cuts off, bestie β€” the description for this one continues in the next chunk. Not me leaving you on a cliffhanger. πŸ’€

Puts data in the binary bin, at offset with length len, at the head of the driver queue πŸŽ€. It's most often faster than driver_pushq, because no data has to be copied bestie β€” zero copies, zero tears.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call πŸ”’.

The return value is 0.

🌸 int driver_pushqv(ErlDrvPort port, ErlIOVec *ev, ErlDrvSizeT skip)

Puts the data in ev at the head of the driver queue, skipping the first skip bytes of it ✨. It's faster than driver_pushq, because no data has to be copied.

The return value is 0.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.

πŸ¦‹ int driver_read_timer(ErlDrvPort port, unsigned long *time_left)

Reads the current time of a timer, and places the result in time_left ⏳. That's the time in milliseconds before the time-out actually goes off.

The return value is 0.

πŸ’œ void *driver_realloc(void *ptr, ErlDrvSizeT size)

Resizes a memory block β€” either in place, or by allocating a new block, copying the data over, and freeing the old block 🧚. You get a pointer back to the reallocated memory. On failure (out of memory), NULL is returned. (This is most often a wrapper for realloc β€” iykyk.)

This function is thread-safe.

πŸ“ ErlDrvBinary *driver_realloc_binary(ErlDrvBinary *bin, ErlDrvSizeT size)

Resizes a driver binary, while keeping the data intact πŸ’….

Returns the resized driver binary on success. Returns NULL on failure (out of memory). Like, if it's out of memory it just gives you NULL, no cap.

This function is thread-safe.

πŸ‘‘ int driver_select(ErlDrvPort port, ErlDrvEvent event, int mode, int on)

This function is how drivers hand the emulator events to check for πŸ‘€. It's the whole reason the emulator can call the driver when something happened asynchronously β€” main character energy for the event loop, honestly.

Parameter event identifies an OS-specific event object. On Unix systems, the functions select/poll are used. The event object must be a socket or pipe (or other object that select/poll can use). On Windows, the Win32 API function WaitForMultipleObjects is used. This places other restrictions on the event object; see the Win32 SDK documentation πŸ“š.

Parameter on is to be 1 for setting events and 0 for clearing them.

Parameter mode is a bitwise OR combination of ERL_DRV_READ, ERL_DRV_WRITE, and ERL_DRV_USE. The first two specify whether to wait for read events and/or write events. A fired read event calls ready_input and a fired write event calls ready_output 🎯.

Note: Some OS (Windows) do not differentiate between read and write events. The callback for a fired event then only depends on the value of mode. πŸ’€

ERL_DRV_USE specifies if we are using the event object or if we want to close it. It is not safe to clear all events and then close the event object after driver_select has returned β€” another thread can still be using the event object internally 😭. To safely close an event object, call driver_select with ERL_DRV_USE and on==0, which clears all events and then either calls stop_select or schedules it to be called when it is safe to close the event object. ERL_DRV_USE is to be set together with the first event for an event object. It is harmless to set ERL_DRV_USE even if it already has been done. Clearing all events but keeping ERL_DRV_USE set indicates that we are using the event object and probably will set events for it again 🫢.

Note: ERL_DRV_USE was added in Erlang/OTP R13. Old drivers still work as before, but it is recommended to update them to use ERL_DRV_USE and stop_select to ensure that event objects are closed in a safe way. πŸ”₯

The return value is 0, unless ready_input/ready_output is NULL, in which case it is -1.

πŸ’€ int driver_send_term(ErlDrvPort port, ErlDrvTermData receiver, ErlDrvTermData* term, int n)

Warning: This function is deprecated. Use erl_drv_send_term instead. πŸ‘‹
Note: The parameters of this function cannot be properly checked by the runtime system when executed by arbitrary threads. This can cause the function not to fail when it should πŸ™ˆ.

Parameters term and n work as in erl_drv_output_term.

This function is thread-safe.

⭐ int driver_set_timer(ErlDrvPort port, unsigned long time)

Sets a timer on the driver, which will count down and call the driver when it is timed out ⏰. Parameter time is the time in milliseconds before the timer expires.

When the timer reaches 0 and expires, the driver entry function timeout is called.

Notice that only one timer exists on each driver instance; setting a new timer replaces an older one. So like, don't get attached πŸ’….

Return value is 0, unless the timeout driver function is NULL, in which case it is -1.

πŸŽ€ ErlDrvSizeT driver_sizeq(ErlDrvPort port)

Returns the number of bytes currently in the driver queue πŸ“.

This function can be called from any thread if a port data lock associated with the port is locked by the calling thread during the call.

🌈 void driver_system_info(ErlDrvSysInfo *sys_info_ptr, size_t size)

Writes information about the Erlang runtime system into the ErlDrvSysInfo structure referred to by the first argument 🧠. The second argument is to be the size of the ErlDrvSysInfo structure, that is, sizeof(ErlDrvSysInfo).

For information about specific fields, see ErlDrvSysInfo.

🧚 ErlDrvSizeT driver_vec_to_buf(ErlIOVec *ev, char *buf, ErlDrvSizeT len)

Collects several segments of data, referenced by ev, by copying them in order to the buffer buf, of the size len 🧺. Like a little picnic basket of data, ngl.

If the data is to be sent from the driver to the port owner process, it is faster to use driver_outputv.

The return value is the space left in the buffer β€” that is, if ev contains less than len bytes it is the difference, and if ev contains len bytes or more, it is 0. This is faster if there is more than one header byte, as the binary syntax can construct integers directly from the binary ✨.

πŸ’– void erl_drv_busy_msgq_limits(ErlDrvPort port, ErlDrvSizeT *low, ErlDrvSizeT *high)

Sets and gets limits that will be used for controlling the busy state of the port message queue 🚦.

The port message queue is set into a busy state when the amount of command data queued on the message queue reaches the high limit. The port message queue is set into a not busy state when the amount of command data queued on the message queue falls below the low limit. Command data is in this context data passed to the port using either Port ! {Owner, {command, Data}} or port_command/[2,3]. Notice that these limits only concern command data that have not yet reached the port. The busy port feature can be used for data that has reached the port πŸ‘€.

Valid limits are values in the range [ERL_DRV_BUSY_MSGQ_LIM_MIN, ERL_DRV_BUSY_MSGQ_LIM_MAX]. Limits are automatically adjusted to be sane. That is, the system adjusts values so that the low limit used is lower than or equal to the high limit used. By default the high limit is 8 kB and the low limit is 4 kB 🎚️.

By passing a pointer to an integer variable containing the value ERL_DRV_BUSY_MSGQ_READ_ONLY, the currently used limit is read and written back to the integer variable. A new limit can be set by passing a pointer to an integer variable containing a valid limit. The passed value is written to the internal limit. The internal limit is then adjusted. After this the adjusted limit is written back to the integer variable from which the new value was read. Values are in bytes πŸ“.

The busy message queue feature can be disabled either by setting the ERL_DRV_FLAG_NO_BUSY_MSGQ driver flag in the driver_entry used by the driver, or by calling this function with ERL_DRV_BUSY_MSGQ_DISABLED as a limit (either low or high). When this feature has been disabled, it cannot be enabled again πŸ’€. When reading the limits, both are ERL_DRV_BUSY_MSGQ_DISABLED if this feature has been disabled.

Processes sending command data to the port are suspended if either the port is busy or if the port message queue is busy. Suspended processes are resumed when neither the port or the port message queue is busy πŸ˜΄βž‘οΈπŸ˜ƒ.

For information about busy port functionality, see set_busy_port.

πŸ¦‹ void erl_drv_cond_broadcast(ErlDrvCond *cnd)

Broadcasts on a condition variable πŸ“’. That is, if other threads are waiting on the condition variable being broadcast on, all of them are woken. Every single one. Group chat notification energy.

cnd is a pointer to a condition variable to broadcast on.

This function is thread-safe.

πŸŽ€ ErlDrvCond *erl_drv_cond_create(char *name)

Creates a condition variable and returns a pointer to it ✨.

name is a string identifying the created condition variable. It is used to identify the condition variable in planned future debug functionality πŸ”.

Returns NULL on failure. The driver creating the condition variable is responsible for destroying it before the driver is unloaded β€” so like, clean up after yourself bestie 🧹.

This function is thread-safe.

πŸ’œ void erl_drv_cond_destroy(ErlDrvCond *cnd)

Destroys a condition variable previously created by erl_drv_cond_create πŸ’₯.

cnd is a pointer to a condition variable to destroy.

This function is thread-safe.

🌸 char *erl_drv_cond_name(ErlDrvCond *cnd)

Returns a pointer to the name of the condition 🏷️.

cnd is a pointer to an initialized condition.

Note: This function is intended for debugging purposes only. πŸ”§

⭐ void erl_drv_cond_signal(ErlDrvCond *cnd)

Signals on a condition variable πŸ“£. That is, if other threads are waiting on the condition variable being signaled, one of them is woken β€” just the one, not the whole group chat πŸ’….

cnd is a pointer to a condition variable to signal on.

This function is thread-safe.

🌈 void erl_drv_cond_wait(ErlDrvCond *cnd, ErlDrvMutex *mtx)

…and the rest of this one picks up in the next chunk, stay tuned 🫢

Okay so erl_drv_cond_wait just... waits πŸ’€ on a condition variable. The calling thread is blocked until another thread wakes it by signaling or broadcasting on the condition variable. But here's the iconic part: before the calling thread gets blocked, it unlocks the mutex that was passed as argument. And when the calling thread is woken, it locks that same mutex again before returning. So basically the mutex must already be locked by the calling thread at the moment you call this function. No cap.

  • cnd β€” a pointer to a condition variable to wait on.
  • mtx β€” a pointer to a mutex to unlock while waiting.
Note, bestie, read this one: erl_drv_cond_wait can totally return even if no one has signaled or broadcast on the condition variable 😭. So any code calling erl_drv_cond_wait is always to be prepared for erl_drv_cond_wait returning even if the condition the thread was waiting for has not occurred. Translation: when you return from erl_drv_cond_wait, always check if the condition has occurred, and if it hasn't, call erl_drv_cond_wait again. Loop it, queen.

This function is thread-safe ✨.


🌈 erl_drv_consume_timeslice

int erl_drv_consume_timeslice(ErlDrvPort port, int percent)

Gives the runtime system a lil hint 🫢 about how much CPU time the current driver callback call has consumed since the last hint, or since the the start of the callback if no previous hint has been given.

  • port β€” Port handle of the executing port.
  • percent β€” Approximate consumed fraction of a full time-slice in percent.

So the time is specified as a fraction, in percent, of a full time-slice that a port is allowed to execute before it is to surrender the CPU to other runnable ports or processes. Valid range is [1, 100] πŸ”₯. Heads up though: the scheduling time-slice is not an exact entity, but can usually be approximated to about 1 millisecond.

Notice that it is up to the runtime system to determine if and how to use this information. Implementations on some platforms can use other means to determine the consumed fraction of the time-slice. Lengthy driver callbacks should, regardless of this, frequently call this function to determine if it is allowed to continue execution or not πŸ‘‘.

This function returns a non-zero value if the time-slice has been exhausted, and zero if the callback is allowed to continue execution. If a non-zero value is returned, the driver callback is to return as soon as possible in order for the port to be able to yield πŸƒβ€β™€οΈπŸ’¨.

This function is provided to better support co-operative scheduling, improve system responsiveness, and to make it easier to prevent misbehaviors of the VM because of a port monopolizing a scheduler thread. It can be used when dividing lengthy work into some repeated driver callback calls, without the need to use threads πŸ’….

See also the important warning text at the beginning of this manual page. Yeah. That one. Go read it πŸ™ˆ.

πŸ¦‹ erl_drv_convert_time_unit

ErlDrvTime erl_drv_convert_time_unit(ErlDrvTime val, ErlDrvTimeUnit from, ErlDrvTimeUnit to)

Converts the val value of time unit from to the corresponding value of time unit to. The result is rounded using the floor function.

  • val β€” Value to convert time unit for.
  • from β€” Time unit of val.
  • to β€” Time unit of returned value.

Returns ERL_DRV_TIME_ERROR if called with an invalid time unit argument πŸ’€.

See also ErlDrvTime and ErlDrvTimeUnit.


⭐ erl_drv_equal_tids

int erl_drv_equal_tids(ErlDrvTid tid1, ErlDrvTid tid2)

Compares two thread identifiers, tid1 and tid2, for equality 🫢.

Returns 0 if they are not equal, and a value not equal to 0 if they are equal. (Yes, that's the right way round, don't @ me.)

Note: a thread identifier can be reused very quickly after a thread has terminated 😭. Therefore, if a thread corresponding to one of the involved thread identifiers has terminated since the thread identifier was saved, the result of erl_drv_equal_tids does possibly not give the expected result. It's giving "stale handle" energy, iykyk.

This function is thread-safe ✨.


πŸŽ€ erl_drv_getenv

int erl_drv_getenv(const char *key, char *value, size_t *value_size)

Retrieves the value of an environment variable 🌸.

  • key β€” A NULL-terminated string containing the name of the environment variable.
  • value β€” A pointer to an output buffer.
  • value_size β€” A pointer to an integer. The integer is used both for passing input and output sizes (see below).

When this function is called, *value_size is to contain the size of the value buffer.

On success, 0 is returned, the value of the environment variable has been written to the value buffer, and *value_size contains the string length (excluding the terminating NULL character) of the value written to the value buffer πŸ‘‘.

On failure, that is, no such environment variable was found, a value < 0 is returned. When the size of the value buffer is too small, a value > 0 is returned and *value_size has been set to the buffer size needed.

Warning, and this one is a big deal: this function reads the emulated environment used by os:getenv/1 and not the environment used by libc's getenv(3erl) or similar πŸ’€. Drivers that require that these are in sync will need to do so themselves, but keep in mind that they are segregated for a reason; getenv(3erl) and its friends are not thread-safe and may cause unrelated code to misbehave or crash the emulator. Like, fr fr, do not mess with this one πŸ™ˆ.

This function is thread-safe ✨.


πŸ’œ erl_drv_init_ack

void erl_drv_init_ack(ErlDrvPort port, ErlDrvData res)

Acknowledges the start of the port 🎬.

  • port β€” The port handle of the port (driver instance) doing the acknowledgment.
  • res β€” The result of the port initialization. Can be the same values as the return value of start, that is, any of the error codes or the ErlDrvData that is to be used for this port.

When this function is called the initiating erlang:open_port call is returned as if the start function had just been called πŸ¦‹. It can only be used when flag ERL_DRV_FLAG_USE_INIT_ACK has been set on the linked-in driver.


🌸 erl_drv_monotonic_time

ErlDrvTime erl_drv_monotonic_time(ErlDrvTimeUnit time_unit)

Returns Erlang monotonic time ⏰. Notice that negative values are not uncommon. Yeah. They're just out here living their truth.

time_unit is time unit of returned value.

Returns ERL_DRV_TIME_ERROR if called with an invalid time unit argument, or if called from a thread that is not a scheduler thread 😭.

See also ErlDrvTime and ErlDrvTimeUnit.


πŸ”₯ erl_drv_mutex_create

ErlDrvMutex *erl_drv_mutex_create(char *name)

Creates a mutex and returns a pointer to it πŸ’….

name is a string identifying the created mutex. It is used to identify the mutex in debug functionality (see note).

Returns NULL on failure. The driver creating the mutex is responsible for destroying it before the driver is unloaded πŸ‘‘.

This function is thread-safe ✨.

Note: one such debug functionality is the lock checker, which can detect locking order violations and thereby potential deadlock bugs πŸ’€. For the lock checker to work the name should be on the format "App.Type" or "App.Type[Instance]", where App is the name of the application, Type is the name of the lock type and Instance is optional information about each lock instance. "App.Type" should be a unique name for the lock checker to detect lock order violations between locks of different types. The Instance information is currently ignored. For example, if we have mutexes of types "myapp.xtable" and "myapp.xitem" then the lock checker will make sure either "myapp.xtable" locks are never locked after "myapp.xitem" locks or vice versa 🫢.

🧚 erl_drv_mutex_destroy

void erl_drv_mutex_destroy(ErlDrvMutex *mtx)

Destroys a mutex previously created by erl_drv_mutex_create πŸŽ€. The mutex must be in an unlocked state before it is destroyed. Like, unlock it first, bestie.

mtx is a pointer to a mutex to destroy.

This function is thread-safe ✨.


πŸ“ erl_drv_mutex_lock

void erl_drv_mutex_lock(ErlDrvMutex *mtx)

Locks a mutex πŸ”’. The calling thread is blocked until the mutex has been locked. A thread that has currently locked the mutex cannot lock the same mutex again β€” that's a no-no, it's not recursive, don't try it.

mtx is a pointer to a mutex to lock.

Warning: if you leave a mutex locked in an emulator thread when you let the thread out of your control, you will very likely deadlock the whole emulator πŸ’€πŸ’€. Not cute. Not the vibe.

This function is thread-safe ✨.


πŸ’– erl_drv_mutex_name

char *erl_drv_mutex_name(ErlDrvMutex *mtx)

Returns a pointer to the mutex name 🏷️.

mtx is a pointer to an initialized mutex.

Note: this function is intended for debugging purposes only πŸ™ˆ.

🌈 erl_drv_mutex_trylock

int erl_drv_mutex_trylock(ErlDrvMutex *mtx)

Tries to lock a mutex 🀞. A thread that has currently locked the mutex cannot try to lock the same mutex again.

mtx is a pointer to a mutex to try to lock.

Returns 0 on success, otherwise EBUSY.

Warning: same warning as above, because it matters β€” if you leave a mutex locked in an emulator thread when you let the thread out of your control, you will very likely deadlock the whole emulator πŸ’€.

This function is thread-safe ✨.


⭐ erl_drv_mutex_unlock

void erl_drv_mutex_unlock(ErlDrvMutex *mtx)

Unlocks a mutex πŸ”“. The mutex currently must be locked by the calling thread.

mtx is a pointer to a mutex to unlock.

This function is thread-safe ✨.


πŸ‘‘ erl_drv_output_term

int erl_drv_output_term(ErlDrvTermData port, ErlDrvTermData* term, int n)

Sends data in the special driver term format to the port owner process πŸ”₯. This is a fast way to deliver term data from a driver. It needs no binary conversion, so the port owner process receives data as normal Erlang terms πŸ¦‹. The erl_drv_send_term functions can be used for sending to any process on the local node.

Note: parameter port is not an ordinary port handle, but a port handle converted using driver_mk_port. Do not just yeet a raw handle in there, bestie 😭.

Okay so term points to an array of ErlDrvTermData with n elements ✨ This array is literally a whole little term-construction kit β€” it contains terms described in the driver term format. Every single term eats up 1–4 elements in the array: the first element is the term type, then the arguments follow. And port tells us which port we're sending to 🎯

Tuples, maps, and lists (except strings β€” more on that below πŸ‘€) get built in reverse polish notation, so to build a tuple you put the elements first and then the tuple term with a count. Same deal for lists and maps.

  • A tuple has to say how many elements it has. (The elements come before the ERL_DRV_TUPLE term, bestie πŸ“Œ)
  • A map has to say how many key-value pairs N you've got. The pairs go before the ERL_DRV_MAP in this order: key1,value1,key2,value2,...,keyN,valueN. And duplicate keys are not allowed β€” don't even try it πŸ™…β€β™€οΈ
  • A list has to say how many elements it has, including the tail, which is the last term before ERL_DRV_LIST.

The special term ERL_DRV_STRING_CONS is how you "splice" a string into a list β€” a string specified this way is not a list by itself, its elements are just elements of the surrounding list 🧡

Term type            Arguments
---------            ---------
ERL_DRV_NIL
ERL_DRV_ATOM         ErlDrvTermData atom (from driver_mk_atom(char *string))
ERL_DRV_INT          ErlDrvSInt integer
ERL_DRV_UINT         ErlDrvUInt integer
ERL_DRV_INT64        ErlDrvSInt64 *integer_ptr
ERL_DRV_UINT64       ErlDrvUInt64 *integer_ptr
ERL_DRV_PORT         ErlDrvTermData port (from driver_mk_port(ErlDrvPort port))
ERL_DRV_BINARY       ErlDrvBinary *bin, ErlDrvUInt len, ErlDrvUInt offset
ERL_DRV_BUF2BINARY   char *buf, ErlDrvUInt len
ERL_DRV_STRING       char *str, int len
ERL_DRV_TUPLE        int sz
ERL_DRV_LIST         int sz
ERL_DRV_PID          ErlDrvTermData pid (from driver_connected(ErlDrvPort port)
                     or driver_caller(ErlDrvPort port))
ERL_DRV_STRING_CONS  char *str, int len
ERL_DRV_FLOAT        double *dbl
ERL_DRV_EXT2TERM     char *buf, ErlDrvUInt len
ERL_DRV_MAP          int sz

Quick size tea β˜• the unsigned integer type ErlDrvUInt and the signed integer type ErlDrvSInt are 64 bits wide on a 64-bit runtime system and 32 bits wide on a 32-bit runtime system. They showed up in ERTS 5.6 and replaced some of the int arguments in that list above.

The unsigned ErlDrvUInt64 and signed ErlDrvSInt64 are always 64 bits wide β€” no cap, they're built different πŸ’… They were introduced in ERTS 5.7.4.

To build the tuple {tcp, Port, [100 | Binary]}, you can make this call πŸ‘‡

ErlDrvBinary* bin = ...
ErlDrvPort port = ...
ErlDrvTermData spec[] = {
    ERL_DRV_ATOM, driver_mk_atom("tcp"),
    ERL_DRV_PORT, driver_mk_port(drvport),
        ERL_DRV_INT, 100,
        ERL_DRV_BINARY, bin, 50, 0,
        ERL_DRV_LIST, 2,
    ERL_DRV_TUPLE, 3,
};
erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));

Here bin is a driver binary of length at least 50 and drvport is a port handle. Notice how ERL_DRV_LIST comes after the elements of the list β€” same energy as ERL_DRV_TUPLE 🫢

The ERL_DRV_STRING_CONS term is a way to construct strings, and it works differently from how ERL_DRV_STRING works. ERL_DRV_STRING_CONS builds a string list in reverse order (as opposed to how ERL_DRV_LIST works), concatenating the strings added to a list. The tail must be specified before ERL_DRV_STRING_CONS β€” order matters, bestie πŸ“

ERL_DRV_STRING constructs a string and ends it. (So yes, it's the same as ERL_DRV_NIL followed by ERL_DRV_STRING_CONS β€” iconic shortcut behavior πŸ‘‘)

/* to send [x, "abc", y] to the port: */
ErlDrvTermData spec[] = {
    ERL_DRV_ATOM, driver_mk_atom("x"),
    ERL_DRV_STRING, (ErlDrvTermData)"abc", 3,
    ERL_DRV_ATOM, driver_mk_atom("y"),
    ERL_DRV_NIL,
    ERL_DRV_LIST, 4
};
erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));

/* to send "abc123" to the port: */
ErlDrvTermData spec[] = {
    ERL_DRV_NIL,        /* with STRING_CONS, the tail comes first */
    ERL_DRV_STRING_CONS, (ErlDrvTermData)"123", 3,
    ERL_DRV_STRING_CONS, (ErlDrvTermData)"abc", 3,
};
erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));

The ERL_DRV_EXT2TERM term type is for passing a term encoded with the external format β€” that's a term that's been encoded by erlang:term_to_binary, erl_interface:ei(3erl), and so on πŸ”₯ For example, if binp is a pointer to an ErlDrvBinary that contains the term {17, 4711} encoded with the external format, and you want to wrap it in a two-tuple with the tag my_tag β€” that is, {my_tag, {17, 4711}} β€” you can do this:

ErlDrvTermData spec[] = {
        ERL_DRV_ATOM, driver_mk_atom("my_tag"),
        ERL_DRV_EXT2TERM, (ErlDrvTermData) binp->orig_bytes, binp->orig_size
    ERL_DRV_TUPLE, 2,
};
erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));

To build the map #{key1 => 100, key2 => {200, 300}}, this is the call you want πŸ’–

ErlDrvPort port = ...
ErlDrvTermData spec[] = {
    ERL_DRV_ATOM, driver_mk_atom("key1"),
        ERL_DRV_INT, 100,
    ERL_DRV_ATOM, driver_mk_atom("key2"),
        ERL_DRV_INT, 200,
        ERL_DRV_INT, 300,
    ERL_DRV_TUPLE, 2,
    ERL_DRV_MAP, 2
};
erl_drv_output_term(driver_mk_port(drvport), spec, sizeof(spec) / sizeof(spec[0]));

If you want to pass a binary and you don't already have its content sitting in an ErlDrvBinary, you absolutely should use ERL_DRV_BUF2BINARY instead of making an ErlDrvBinary via driver_alloc_binary and then passing it through ERL_DRV_BINARY πŸ¦‹ The runtime system often allocates binaries smarter when ERL_DRV_BUF2BINARY is used. BUT β€” if the binary content already lives in an ErlDrvBinary, it's normally better to pass it using ERL_DRV_BINARY and the ErlDrvBinary in question. Use what you've got, iykyk 🌸

The ERL_DRV_UINT, ERL_DRV_BUF2BINARY, and ERL_DRV_EXT2TERM term types were introduced in ERTS 5.6 ⭐

This function is thread-safe βœ…


int erl_drv_putenv(const char *key, char *value)

Sets the value of an environment variable, periodt 🌍

  • key is a NULL-terminated string containing the name of the environment variable.
  • value is a NULL-terminated string containing the new value of the environment variable.

Returns 0 on success, otherwise a value != 0.

Note: passing the empty string ("") as a value is platform-dependent 😭 On some platforms the variable value gets set to the empty string, on others the environment variable is straight-up removed. No universal answer, sorry bestie.
Warning: This function modifies the emulated environment used by os:putenv/2 β€” not the environment used by libc's putenv(3erl) or similar 🚨 Drivers that need those two in sync have to do the syncing themselves. And keep in mind they're segregated for a reason: putenv(3erl) and its friends are not thread-safe and may cause unrelated code to misbehave or straight-up crash the emulator. Do not mess with that πŸ’€

This function is thread-safe βœ…


ErlDrvRWLock *erl_drv_rwlock_create(char *name)

Creates an rwlock and hands you a pointer to it πŸŽ€

name is a string identifying the created rwlock. It's used to identify the rwlock in debug functionality (see the note about the lock checker πŸ‘€).

Returns NULL on failure. The driver that creates the rwlock is responsible for destroying it before the driver is unloaded β€” clean up after yourself, bestie 🧹

This function is thread-safe βœ…


void erl_drv_rwlock_destroy(ErlDrvRWLock *rwlck)

Destroys an rwlock that was previously created by erl_drv_rwlock_create. The rwlock must be in an unlocked state before it's destroyed β€” do not skip that step πŸ”’

rwlck is a pointer to an rwlock to destroy.

This function is thread-safe βœ…


char *erl_drv_rwlock_name(ErlDrvRWLock *rwlck)

Returns a pointer to the name of the rwlock 🏷️

rwlck is a pointer to an initialized rwlock.

Note: this function is intended for debugging purposes only β€” don't build your whole architecture on it, okay? πŸ™ˆ

void erl_drv_rwlock_rlock(ErlDrvRWLock *rwlck)

Read locks an rwlock. The calling thread is blocked until the rwlock has been read locked πŸ“₯ A thread that currently has read or read/write locked the rwlock cannot lock the same rwlock again β€” no recursion, no cap 🚫

rwlck is a pointer to the rwlock to read lock.

Warning: if you leave an rwlock locked in an emulator thread when you let that thread out of your control, you will very likely deadlock the whole emulator πŸ’€πŸ”’ That's a whole emulator, not just your driver. Be careful.

This function is thread-safe βœ…


void erl_drv_rwlock_runlock(ErlDrvRWLock *rwlck)

Read unlocks an rwlock. The rwlock currently must be read locked by the calling thread πŸ“€

rwlck is a pointer to an rwlock to read unlock.

This function is thread-safe βœ…


void erl_drv_rwlock_rwlock(ErlDrvRWLock *rwlck)

Read/write locks an rwlock. The calling thread is blocked until the rwlock has been read/write locked πŸ” A thread that currently has read or read/write locked the rwlock cannot lock the same rwlock again β€” same rule as before, no re-entry 🚫

rwlck is a pointer to an rwlock to read/write lock.

Warning: if you leave an rwlock locked in an emulator thread when you let that thread out of your control, you will very likely deadlock the whole emulator πŸ’€πŸ”’ Being reckless with locks is not the vibe.

This function is thread-safe βœ…


void erl_drv_rwlock_rwunlock(ErlDrvRWLock *rwlck)

Read/write unlocks an rwlock. The rwlock currently must be read/write locked by the calling thread πŸ”“

rwlck is a pointer to an rwlock to read/write unlock.

This function is thread-safe βœ…


int erl_drv_rwlock_tryrlock(ErlDrvRWLock *rwlck)

Tries to read lock an rwlock. πŸ’…

rwlck is a pointer to an rwlock to try to read lock.

Returns 0 on success, otherwise EBUSY. A thread that currently has read or read/write locked the rwlock cannot try to lock the same rwlock again. (like, it already has the vibe, it can't double-book, bestie 😭)

Warning: If you leave an rwlock locked in an emulator thread when you let the thread out of your control, you will very likely deadlock the whole emulator. No cap, that's the whole thing falling over. 🫠

This function is thread-safe. ✨


int erl_drv_rwlock_tryrwlock(ErlDrvRWLock *rwlck)

Tries to read/write lock an rwlock. A thread that currently has read or read/write locked the rwlock cannot try to lock the same rwlock again. rude but true.

rwlck is pointer to an rwlock to try to read/write lock.

Returns 0 on success, otherwise EBUSY.

Warning: If you leave an rwlock locked in an emulator thread when you let the thread out of your control, you will very likely deadlock the whole emulator. Same warning, same drama, same catastrophe. πŸ’€

This function is thread-safe. 🌸


int erl_drv_send_term(ErlDrvTermData port, ErlDrvTermData receiver, ErlDrvTermData* term, int n)

This function is the only way for a driver to send data to other processes than the port owner process. Parameter receiver specifies the process to receive the data. πŸ“¬

Note: Parameter port is not an ordinary port handle, but a port handle converted using driver_mk_port. Don't skip that step, iykyk.

Parameters port, term, and n work as in erl_drv_output_term.

This function is thread-safe. ✨


void erl_drv_set_os_pid(ErlDrvPort port, ErlDrvSInt pid)

Sets the os_pid seen when doing erlang:port_info/2 on this port. Like, it's the pid the rest of the world peeks at. πŸ‘€

port is the port handle of the port (driver instance) to set the pid on. pid is the pid to set.


int erl_drv_thread_create(char *name, ErlDrvTid *tid, void * (*func)(void *), void *arg, ErlDrvThreadOpts *opts)

Creates a new thread. New thread just dropped, main character energy. πŸ¦‹

  • name: β€” A string identifying the created thread. It is used to identify the thread in planned future debug functionality.
  • tid: β€” A pointer to a thread identifier variable.
  • func: β€” A pointer to a function to execute in the created thread.
  • arg: β€” A pointer to argument to the func function.
  • opts: β€” A pointer to thread options to use or NULL.

Returns 0 on success, otherwise an errno value is returned to indicate the error. The newly created thread begins executing in the function pointed to by func, and func is passed arg as argument. When erl_drv_thread_create returns, the thread identifier of the newly created thread is available in *tid. opts can be either a NULL pointer, or a pointer to an ErlDrvThreadOpts structure. If opts is a NULL pointer, default options are used, otherwise the passed options are used.

Warning: You are not allowed to allocate the ErlDrvThreadOpts structure by yourself. It must be allocated and initialized by erl_drv_thread_opts_create. Do not freelance this one πŸ™ˆ.

The created thread terminates either when func returns or if erl_drv_thread_exit is called by the thread. The exit value of the thread is either returned from func or passed as argument to erl_drv_thread_exit. The driver creating the thread is responsible for joining the thread, through erl_drv_thread_join, before the driver is unloaded. "Detached" threads cannot be created, that is, threads that do not need to be joined. Periodt β€” every thread gets joined. πŸ’…

Warning: All created threads must be joined by the driver before it is unloaded. If the driver fails to join all threads created before it is unloaded, the runtime system most likely crashes when the driver code is unloaded. That's not a vibe check you want to fail. 😭

This function is thread-safe. ✨


void erl_drv_thread_exit(void *exit_value)

Terminates the calling thread with the exit value passed as argument. exit_value is a pointer to an exit value or NULL. Bye bestie πŸ‘‹

You are only allowed to terminate threads created with erl_drv_thread_create.

The exit value can later be retrieved by another thread through erl_drv_thread_join.

This function is thread-safe. ✨


int erl_drv_thread_join(ErlDrvTid tid, void **exit_value)

Joins the calling thread with another thread, that is, the calling thread is blocked until the thread identified by tid has terminated. It literally waits at the door until the other one's done. 🫢

tid is the thread identifier of the thread to join. exit_value is a pointer to a pointer to an exit value, or NULL.

Returns 0 on success, otherwise an errno value is returned to indicate the error.

A thread can only be joined once. The behavior of joining more than once is undefined, an emulator crash is likely. If exit_value == NULL, the exit value of the terminated thread is ignored, otherwise the exit value of the terminated thread is stored at *exit_value.

This function is thread-safe. ✨


char *erl_drv_thread_name(ErlDrvTid tid)

Returns a pointer to the name of the thread. 🏷️

tid is a thread identifier.

Note: This function is intended for debugging purposes only. It's not the moment to build your whole architecture on it, ngl.

ErlDrvThreadOpts *erl_drv_thread_opts_create(char *name)

Allocates and initializes a thread option structure. ✨

name is a string identifying the created thread options. It is used to identify the thread options in planned future debug functionality.

Returns NULL on failure. A thread option structure is used for passing options to erl_drv_thread_create. If the structure is not modified before it is passed to erl_drv_thread_create, the default values are used.

Warning: You are not allowed to allocate the ErlDrvThreadOpts structure by yourself. It must be allocated and initialized by erl_drv_thread_opts_create. Say it with me: let the function do it. πŸ’…

This function is thread-safe. ✨


void erl_drv_thread_opts_destroy(ErlDrvThreadOpts *opts)

Destroys thread options previously created by erl_drv_thread_opts_create. Cleanup era 🧹

opts is a pointer to thread options to destroy.

This function is thread-safe. ✨


ErlDrvTid erl_drv_thread_self(void)

Returns the thread identifier of the calling thread. It's giving selfie, but make it threads. 🀳

This function is thread-safe. ✨


ErlDrvTime erl_drv_time_offset(ErlDrvTimeUnit time_unit)

Returns the current time offset between Erlang monotonic time and Erlang system time converted into the time_unit passed as argument. ⏰

time_unit is time unit of returned value.

Returns ERL_DRV_TIME_ERROR if called with an invalid time unit argument, or if called from a thread that is not a scheduler thread.

See also ErlDrvTime and ErlDrvTimeUnit. πŸ¦‹


void *erl_drv_tsd_get(ErlDrvTSDKey key)

Returns the thread-specific data associated with key for the calling thread. Your thread's own lil stash. πŸŽ€

key is a thread-specific data key.

Returns NULL if no data has been associated with key for the calling thread.

This function is thread-safe. ✨


int erl_drv_tsd_key_create(char *name, ErlDrvTSDKey *key)

Creates a thread-specific data key. πŸ”‘

name is a string identifying the created key. It is used to identify the key in planned future debug functionality.

key is a pointer to a thread-specific data key variable.

Returns 0 on success, otherwise an errno value is returned to indicate the error. The driver creating the key is responsible for destroying it before the driver is unloaded. You made it, you clean it up 🫢

This function is thread-safe. ✨


void erl_drv_tsd_key_destroy(ErlDrvTSDKey key)

Destroys a thread-specific data key previously created by erl_drv_tsd_key_create. All thread-specific data using this key in all threads must be cleared (see erl_drv_tsd_set) before the call to erl_drv_tsd_key_destroy. Read that twice, bestie 😭

key is a thread-specific data key to destroy.

Warning: A destroyed key is very likely to be reused soon. Therefore, if you fail to clear the thread-specific data using this key in a thread before destroying the key, you will very likely get unexpected errors in other parts of the system. Like, chaos in someone else's lane. πŸ’€

This function is thread-safe. ✨


void erl_drv_tsd_set(ErlDrvTSDKey key, void *data)

Sets thread-specific data associated with key for the calling thread. You are only allowed to set thread-specific data for threads while they are fully under your control. For example, if you set thread-specific data in a thread calling a driver callback function, it must be cleared, that is, set to NULL, before returning from the driver callback function. No leaving your stuff in the shared bathroom 🚿

key is a thread-specific data key.

data is a pointer to data to associate with key in the calling thread.

Warning: If you fail to clear thread-specific data in an emulator thread before letting it out of your control, you might never be able to clear this data, with later unexpected errors in other parts of the system as a result. 😭 Don't do that.

This function is thread-safe. ✨


char *erl_errno_id(int error)

Returns the atom name of the Erlang error, given the error number in error. The error atoms are einval, enoent, and so on. It can be used to make error terms from the driver. Errors, but make it cute and Erlang-y 🌈


int remove_driver_entry(ErlDrvEntry *de)

Removes a driver entry de previously added with add_driver_entry.

Driver entries added by the erl_ddll Erlang interface cannot be removed by using this interface. Not your entry, not your call πŸ™…


void set_busy_port(ErlDrvPort port, int on)

Sets and unsets the busy state of the port. If on is non-zero, the port is set to busy. If it is zero, the port is set to not busy. You typically want to combine this feature with the busy port message queue functionality.

Processes sending command data to the port are suspended if either the port or the port message queue is busy. Suspended processes are resumed when neither the port or the port message queue is busy. Command data is in this context data passed to the port using either Port ! {Owner, {command, Data}} or port_command/[2,3]. 🚦

Okay so if ERL_DRV_FLAG_SOFT_BUSY has been set in the driver_entry, data can be forced into the driver through erlang:port_command(Port, Data, [force]) even if the driver has signaled that it is busy. No cap, that's the whole vibe πŸ’…

For info about busy port message queue functionality, see erl_drv_busy_msgq_limits β€” she's got the details, bestie ✨


Next up, the iconic:

void set_port_control_flags(ErlDrvPort port, int flags)

This one sets flags for how the control driver entry function will return data to the port owner process. (The control function is called from erlang:port_control/3, iykyk.)

Currently there are only two meaningful values for flags:

  • 0 β€” data is returned in a list πŸŽ€
  • PORT_CONTROL_FLAG_BINARY β€” data is returned as a binary from control πŸ¦‹

That's literally it. Two moods. Pick your fighter πŸ’–

🌸 SEE ALSO 🌸


And that's the page, bestie! This masterpiece is brought to you by Ericsson AB, version erts 13.2.2.5, for erl_driver(3erl) β€” the footer doesn't show a date, but the source/version is right there and it's serving βœ¨πŸ’œπŸ«Ά

πŸ“¦ where this page comes from