erl_ddll(3)

๐Ÿ“ฆ
version 29.0.6 ยท 3 versions
, in ubuntu stonking

erl_ddll ๐Ÿ’– the dynamic driver loader & linker, bestie

okay so this is the manual page for erl_ddll, a module in the Erlang module definition collection. it's giving "load and unload linked-in drivers at runtime" energy, and honestly? it's iconic. โœจ


๐ŸŒธ NAME ๐ŸŒธ

erl_ddll โ€” Dynamic driver loader and linker. periodt. ๐Ÿ’…


๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

okay so here's the tea: this module gives you an interface for loading and unloading Erlang linked-in drivers, like, at runtime. no reboot, no drama, just vibes. ๐ŸŽ€

NOTE: bestie, this is a large reference document. if you're just casually using this module โ€” and for most real world applications, fr fr โ€” the descriptions of functions load/2 and unload/1 are enough to getting started. that's literally all you need to begin. ๐Ÿซถ

so the driver has to be provided as a dynamically linked library, in an object code format that's specific to whatever platform you're on. that means .so files on most Unix systems, and .ddl files on Windows. and here's the important part: an Erlang linked-in driver must provide specific interfaces to the emulator, so this module is not designed for loading arbitrary dynamic libraries. nope. not a thing. don't try it. ๐Ÿ˜ญ

want more info about Erlang drivers in general? see erl_driver.

so when we're describing a set of functions โ€” like a module, part of a module, or an application โ€” that run in a process and wanna use a ddll-driver, we use the term user. and a process can have many users (different modules needing the same driver), and many processes can run the same code, which makes up many users of a driver. it's a whole community situation. ๐Ÿ‘‘

in the basic scenario, each user loads the driver before starting to use it, and unloads the driver when done. the reference counting keeps track of processes and the number of loads by each process. this way the driver is only unloaded when no one wants it โ€” when it has no user. like a group chat that finally goes quiet. ๐Ÿ™ˆ

the driver also keeps track of ports that are opened to it. this enables delay of unloading until all ports are closed, or killing of all ports that use the driver when it is unloaded. options, we love options. โœจ

so the interface supports two basic scenarios of loading and unloading. and each scenario can also have the option of either killing ports when the driver is unloading, or waiting for the ports to close themselves. the scenarios are as follows, bestie โ€” buckle in:


๐Ÿ’œ Load and Unload on a "When Needed Basis" ๐Ÿ’œ

this one is the most common scenario, and it simply supports that each user of the driver loads it when needed and unloads it when no longer needed. the driver is always reference counted, and as long as a process keeping the driver loaded is still alive, the driver is present in the system. main character energy, honestly. ๐ŸŒŸ

each user of the driver uses literally the same pathname for the driver when demanding load, but the users are not concerned with if the driver is already loaded from the file system, or if the object code must be loaded from the file system. it's all handled, no cap. ๐Ÿ”ฅ

the following two pairs of functions support this scenario:

๐ŸŽ€ load/2 and unload/1

when using the load/unload interfaces, the driver is not unloaded until the last port using the driver is closed. function unload/1 can return immediately, because the users have no interest in when the unloading occurs. the driver is unloaded when no one needs it any longer. bye bestie, we'll unload you when we feel like it ๐Ÿ’…

if a process having the driver loaded dies, it has the same effect as if unloading is done. ๐Ÿ’€ (rip, but make it functional)

when loading, function load/2 returns ok when any instance of the driver is present. so if a driver is waiting to get unloaded (because of open ports), it simply changes state to no longer need unloading. glow-up moment. โœจ

๐ŸŽ€ load_driver/2 and unload_driver/1

these interfaces are intended to be used when it is considered an error that ports are open to a driver that no user has loaded. the ports that are still open when the last user calls unload_driver/1, or when the last process having the driver loaded dies, are killed with reason driver_unloaded. dramatic? yes. necessary? also yes. ๐Ÿ˜ค

the function names load_driver and unload_driver are kept for backward compatibility. they're the elders of this module, respect them. ๐Ÿซก


๐Ÿ’œ Loading and Reloading for Code Replacement ๐Ÿ’œ

this scenario can occur if the driver code needs replacement during operation of the Erlang emulator. and here's the thing โ€” implementing driver code replacement is a little more tedious than Beam code replacement, because one driver cannot be loaded as both "old" and "new" code. no dual-wielding here, sorry. ๐Ÿ™…โ™€๏ธ

all users of a driver must have it closed (no open ports) before the old code can be unloaded and the new code can be loaded. everyone out of the pool first. ๐ŸŠโ™€๏ธ

the unloading/loading is done as one atomic operation, blocking all processes in the system from using the driver in question while in progress. it's a whole "do not disturb, we're upgrading" situation. ๐Ÿ‘‘

the preferred way to do driver code replacement is to let one single process keep track of the driver. when the process starts, the driver is loaded. when replacement is required, the driver is reloaded. unload is probably never done, or done when the process exits. and heads up: if more than one user has a driver loaded when code replacement is demanded, the replacement cannot occur until the last "other" user has unloaded the driver. ๐Ÿ’€

demanding reload when a reload is already in progress is always an error. and using the high-level functions, it is also an error to demand reloading when more than one user has the driver loaded. so likeโ€ฆ don't. ๐Ÿ™ˆ

to simplify driver replacement, avoid designing your system so that more than one user has the driver loaded. design tip from me to you, bestie. ๐ŸŽ€

the two functions for reloading drivers are to be used together with corresponding load functions, to support the two different behaviors concerning open ports:

๐ŸŒˆ load/2 and reload/2

this pair of functions is used when reloading is to be done after the last open port to the driver is closed.

as reload/2 waits for the reloading to occur, a misbehaving process keeping open ports to the driver (or keeping the driver loaded) can cause infinite waiting for reload. infinite. that's a long time. ๐Ÿ˜ญ time-outs must be provided outside of the process demanding the reload, or by using the low-level interface try_load/3 in combination with driver monitors.

๐ŸŒˆ load_driver/2 and reload_driver/2

this pair of functions is used when open ports to the driver are to be killed with reason driver_unloaded, to allow for new driver code to get loaded. clean slate, fresh start. โœจ

however โ€” and this is important โ€” if another process has the driver loaded, calling reload_driver returns error code pending_process. and as stated earlier, the recommended design is to not allow other users than the "driver reloader" to demand loading of the driver in question. one reloader to rule them all. ๐Ÿ‘‘


๐Ÿ’œ See Also ๐Ÿ’œ

erl_driver(4), driver_entry(4)


๐ŸŒธ DATA TYPES ๐ŸŒธ

driver() :: iolist() | atom().

path() :: string() | atom().

that's the whole type situation. short, sweet, iconic. ๐Ÿ’…


๐Ÿฆ‹ FUNCTIONS ๐Ÿฆ‹

๐Ÿ’– demonitor(MonitorRef) -> ok when MonitorRef :: reference().

removes a driver monitor in much the same way as erlang:demonitor/1 in ERTS does with process monitors. same energy, different target. ๐ŸŽ€

for details about how to create driver monitors, see monitor/2, try_load/3, and try_unload/2.

the function throws a badarg exception if the parameter is not a reference/0. so if you pass it garbage, it will call you out. ๐Ÿ˜ค

๐Ÿ’– format_error(ErrorDesc) -> string() when ErrorDesc :: term().

takes an ErrorDesc returned by load, unload, or reload functions, and returns a string that describes the error or warning. it's the translator between "cryptic error code" and "ohhh that's what happened". ๐Ÿซถ

NOTE: because of peculiarities in the dynamic loading interfaces on different platforms, the returned string is only guaranteed to describe the correct error if format_error/1 is called in the same instance of the Erlang virtual machine as the error appeared in (meaning the same operating system process). so don't go shipping error descriptions across processes and expecting them to still make sense. no cap. โš ๏ธ

๐Ÿ’– info() -> AllInfoList

when
    AllInfoList :: [DriverInfo],
    DriverInfo :: {DriverName, InfoList},
    DriverName :: string(),
    InfoList :: [InfoItem],
    InfoItem :: {Tag :: atom(), Value :: term()}.

returns a list of tuples {DriverName, InfoList}, where InfoList is the result of calling info/1 for that DriverName. only dynamically linked-in drivers are included in the list. if it's not dynamically linked in, it's not invited to this party. ๐Ÿ™…โ™€๏ธ

๐Ÿ’– info(Name) -> InfoList

when
    Name :: driver(),
    InfoList :: [InfoItem, ...],
    InfoItem :: {Tag :: atom(), Value :: term()}.

returns a list of tuples {Tag, Value}, where Tag is the information item and Value is the result of calling info/2 with this driver name and this tag. the result is a tuple list containing all information available about a driver. literally all of it. the whole lore. ๐Ÿ“š

the following tags appears in the list:

  • processes
  • driver_options
  • port_count
  • linked_in_driver
  • permanent
  • awaiting_load
  • awaiting_unload

for a detailed description of each value, see info/2. (and yes, it's right below, keep reading bestie ๐Ÿ’œ)

the function throws a badarg exception if the driver is not present in the system. if it's not there, it's gonna tell you. loudly. ๐Ÿ˜ญ

๐Ÿ’– info(Name, Tag) -> Value

when
    Name :: driver(),
    Tag ::
        processes | driver_options | port_count |
        linked_in_driver | permanent | awaiting_load |
        awaiting_unload,
    Value :: term().

returns specific information about one aspect of a driver. parameter Tag specifies which aspect to get information about. the return Value differs between different tags:

  • processes โ€” returns all processes containing users of the specific drivers as a list of tuples {pid(),integer() >= 0}, where integer/0 denotes the number of users in process pid/0.
  • driver_options โ€” returns a list of the driver options provided when loading, and any options set by the driver during initialization. the only valid option is kill_ports.
  • port_count โ€” returns the number of ports (an integer() >= 0) using the driver.
  • linked_in_driver โ€” returns a boolean/0, which is true if the driver is a statically linked-in one, otherwise false.
  • permanent โ€” returns a boolean/0, which is true if the driver has made itself permanent (and is not a statically linked-in driver), otherwise false.
  • awaiting_load โ€” returns a list of all processes having monitors for loading active. each process is returned as {pid(),integer() >= 0}, where integer/0 is the number of monitors held by process pid/0.
  • awaiting_unload โ€” returns a list of all processes having monitors for unloading active. each process is returned as {pid(),integer() >= 0}, where integer/0 is the number of monitors held by process pid/0.

and the special rule, so listen up: if option linked_in_driver or permanent returns true, all other options return linked_in_driver or permanent, respectively. that's just how it is. ๐Ÿ’…

the function throws a badarg exception if the driver is not present in the system, or if the tag is not supported. โš ๏ธ


๐ŸŒธ and that's where this part wraps up โ€” but bestie, we are not done, there's so much more coming ๐Ÿ’–

๐Ÿซถ load/2 โ€” the classic loader

load(Path, Name) -> ok | {error, ErrorDesc}
              when Path :: path(), Name :: driver(), ErrorDesc ::
              term().

Okay bestie, this one loads and links the dynamic driver Name. Path is a file path pointing at the directory that's holding your driver. And heads up โ€” Name has to be a shareable object/dynamic library. Also, two drivers with different Path parameters cannot be loaded under the same name. Name is a string or atom containing at least one character. โœจ

The Name you pass is supposed to match up with the filename of the dynamically loadable object file sitting in the directory you gave as Path โ€” but without the extension (that is, .so). And the driver name you provide in the driver initialization routine has to correspond with the filename, in much the same way as Erlang module names correspond to the names of the .beam files. Matchy matchy, it's giving beam file energy. ๐ŸŽ€

If the driver was previously unloaded but is still present because of open ports to it, a call to load/2 stops the unloading and keeps the driver (as long as Path is the same), and ok is returned. But if you really want the object code to be reloaded, use reload/2 or the low-level interface try_load/3 instead. Also go peek at the description of different scenarios for loading/unloading in the introduction. ๐Ÿ‘€

Now, if more than one process tries to load an already loaded driver with the same Path, or if the same process tries to load it many times โ€” the function returns ok. The emulator keeps track of the load/2 calls, so a corresponding number of unload/2 calls must be done from the same process before the driver gets unloaded. So it is therefore safe for an application to load a driver that is shared between processes or applications when needed. It can safely be unloaded without causing trouble for other parts of the system. Reference counting but make it driver vibes, we love to see it. ๐Ÿ’…

It is not allowed to load multiple drivers with the same name but with different Path parameters. No. Nope. Don't.

NOTE: Path is interpreted literally, so that all loaders of the same driver must specify the same literal Path string, although different paths can point out the same directory in the file system (because of use of relative paths and links). Like, same string, bestie. Literal. ๐Ÿ”ฅ

On success, the function returns ok. On failure, the return value is {error,ErrorDesc}, where ErrorDesc is an opaque term to be translated into human readable form by function format_error/1.

For more control over the error handling, use the try_load/3 interface instead.

The function throws a badarg exception if the parameters are not specified as described here. ๐Ÿซ 


๐ŸŒธ load_driver/2 โ€” the O.G. with extra spice

load_driver(Path, Name) -> ok | {error, ErrorDesc}
                     when
                         Path :: path(),
                         Name :: driver(),
                         ErrorDesc :: term().

Works essentially as load/2, but loads the driver with other options. Here's the dramatic part: all ports using the driver are killed with reason driver_unloaded when the driver is to be unloaded. ๐Ÿ’€

The number of loads and unloads by different users influences the loading and unloading of a driver file. So the port killing therefore only occurs when the last user unloads the driver, or when the last process having loaded the driver exits. Last one out, lights off, ports gone. ๐Ÿ•ฏ๏ธ

This interface (or at least the name of the functions) is kept for backward compatibility. Using try_load/3 with {driver_options,[kill_ports]} in the option list gives the same effect regarding the port killing.

The function throws a badarg exception if the parameters are not specified as described here. ๐Ÿ‘‘


๐Ÿฆ‹ loaded_drivers/0 โ€” the guest list

loaded_drivers() -> {ok, Drivers}
                        when Drivers :: [Driver], Driver :: string().

Returns a list of all the available drivers โ€” both the (statically) linked-in ones AND the dynamically loaded ones. Everyone's on the list, no gatekeeping. โœจ

The driver names are returned as a list of strings rather than a list of atoms for historical reasons. It's a legacy thing, iykyk. ๐Ÿ™ˆ

For more information about drivers, see info.


๐Ÿ’– monitor/2 โ€” create a driver monitor

monitor(Tag, Item) -> MonitorRef
                 when
                     Tag :: driver,
                     Item :: {Name, When},
                     Name :: driver(),
                     When :: loaded | unloaded | unloaded_only,
                     MonitorRef :: reference().

Creates a driver monitor and works in many ways as erlang:monitor/2 in ERTS does for processes. When a driver changes state, the monitor results in a monitor message that is sent to the calling process. The MonitorRef returned by this function is included in the message that gets sent. Like a little ping when the driver does something. ๐ŸŽ€

As with process monitors, each driver monitor set only generates one single message. The monitor is "destroyed" after the message is sent, so it is then not needed to call demonitor/1. One and done, iconic behaviour. ๐Ÿ’…

MonitorRef can also be used in subsequent calls to demonitor/1 to remove a monitor.

The function accepts the following parameters:

  • Tag โ€” the monitor tag is always driver, as this function can only be used to create driver monitors. In the future, driver monitors will be integrated with process monitors, why this parameter has to be specified for consistence. (Yes, you gotta pass it. Foresight, bestie. ๐Ÿ”ฎ)
  • Item โ€” parameter Item specifies which driver to monitor (the driver name) and which state change to monitor. The parameter is a tuple of arity two whose first element is the driver name and second element is one of the following:
    • loaded โ€” notifies when the driver is reloaded (or loaded if loading is underway). It only makes sense to monitor drivers that are in the process of being loaded or reloaded. A future driver name for loading cannot be monitored. That only results in a DOWN message sent immediately. Monitoring for loading is therefore most useful when triggered by function try_load/3, where the monitor is created because the driver is in such a pending state.

Setting a driver monitor for loading eventually leads to one of the following messages being sent:

  • {'UP', reference(), driver, Name, loaded} โ€” this message is sent either immediately if the driver is already loaded and no reloading is pending, or when reloading is executed if reloading is pending.

The user is expected to know if reloading is demanded before creating a monitor for loading.

  • {'UP', reference(), driver, Name, permanent} โ€” this message is sent if reloading was expected, but the (old) driver made itself permanent before reloading. It is also sent if the driver was permanent or statically linked-in when trying to create the monitor.
  • {'DOWN', reference(), driver, Name, load_cancelled} โ€” this message arrives if reloading was underway, but the requesting user cancelled it by dying or calling try_unload/2 (or unload/1/unload_driver/1) again before it was reloaded.
  • {'DOWN', reference(), driver, Name, {load_failure, Failure}} โ€” this message arrives if reloading was underway but the loading for some reason failed. The Failure term is one of the errors that can be returned from try_load/3. The error term can be passed to format_error/1 for translation into human readable form. Notice that the translation must be done in the same running Erlang virtual machine as the error was detected in. โš ๏ธ (Same VM, no cap!)
  • unloaded โ€” monitors when a driver gets unloaded. If one monitors a driver that is not present in the system, one immediately gets notified that the driver got unloaded. There is no guarantee that the driver was ever loaded. ๐Ÿ˜ญ

A driver monitor for unload eventually results in one of the following messages being sent:

  • {'DOWN', reference(), driver, Name, unloaded} โ€” the monitored driver instance is now unloaded. As the unload can be a result of a reload/2 request, the driver can once again have been loaded when this message arrives.
  • {'UP', reference(), driver, Name, unload_cancelled} โ€” this message is sent if unloading was expected, but while the driver was waiting for all ports to get closed, a new user of the driver appeared, and the unloading was cancelled.

This message appears if {ok, pending_driver} was returned from try_unload/2 for the last user of the driver, and then {ok, already_loaded} is returned from a call to try_load/3.

If one really wants to monitor when the driver gets unloaded, this message distorts the picture, because no unloading was done. Option unloaded_only creates a monitor similar to an unloaded monitor, but never results in this message.

  • {'UP', reference(), driver, Name, permanent} โ€” this message is sent if unloading was expected, but the driver made itself permanent before unloading. It is also sent if trying to monitor a permanent or statically linked-in driver.
  • unloaded_only โ€” a monitor created as unloaded_only behaves exactly as one created as unloaded except that the {'UP', reference(), driver, Name, unload_cancelled} message is never sent, but the monitor instead persists until the driver really gets unloaded. โœจ Clean, undisturbed unload-watching, we stan.

The function throws a badarg exception if the parameters are not specified as described here. ๐Ÿซ 


๐ŸŒˆ reload/2 โ€” glow up your driver

reload(Path, Name) -> ok | {error, ErrorDesc}
                when
                    Path :: path(),
                    Name :: driver(),
                    ErrorDesc :: pending_process | OpaqueError,
                    OpaqueError :: term().

Reloads the driver named Name from a possibly different Path than previously used. This function is used in the code change scenario described in the introduction. โœจ

If there are other users of this driver, the function returns {error, pending_process}, but if there are no other users, the function call hangs until all open ports are closed. So yeah โ€” if you're the only one, prepare to wait. โณ

NOTE: Avoid mixing multiple users with driver reload requests. Seriously. Just don't. ๐Ÿ™…โ€โ™€๏ธ

So yeah โ€” to dodge the whole hanging-on-open-ports situation, use try_load/3 instead. ๐Ÿ’…

The Name and Path parameters mean exactly the same thing here as when you call the plain old load/2, no cap.

On success you get ok back. On failure you get an opaque error โ€” the only exception being that pending_process error we already talked about. Those opaque errors are literally meant to be translated into human-readable form by format_error/1. ๐Ÿซถ

Want more control over the error handling? Bestie, use the try_load/3 interface instead.

Heads up: this function throws a badarg exception if you don't specify the parameters exactly as described here. ๐Ÿ‘€

๐ŸŒธ reload_driver(Path, Name) -> ok | {error, ErrorDesc}

reload_driver(Path, Name) -> ok | {error, ErrorDesc}
                       when
                           Path :: path(),
                           Name :: driver(),
                           ErrorDesc :: pending_process | OpaqueError,
                           OpaqueError :: term().

Works exactly like reload/2, bestie โ€” but for drivers that were loaded with the load_driver/2 interface. ๐Ÿ’–

And because this interface implies that ports get killed the moment the last user dips out, this function does not hang around waiting for ports to get closed. Slay, no waiting room energy. โœจ

For more details, go read the scenarios in this module's description and the function description for reload/2. ๐Ÿ“–

Same deal as always: the function throws a badarg exception if the parameters aren't specified as described here. ๐Ÿ˜ญ

๐Ÿฆ‹ try_load/3

try_load(Path, Name, OptionList) ->
                  {ok, Status} |
                  {ok, PendingStatus, Ref} |
                  {error, ErrorDesc}
                  when
                      Path :: path(),
                      Name :: driver(),
                      OptionList :: [Option],
                      Option ::
                          {driver_options, DriverOptionList} |
                          {monitor, MonitorOption} |
                          {reload, ReloadOption},
                      DriverOptionList :: [DriverOption],
                      DriverOption :: kill_ports,
                      MonitorOption :: pending_driver | pending,
                      ReloadOption :: pending_driver | pending,
                      Status :: loaded | already_loaded | PendingStatus,
                      PendingStatus :: pending_driver | pending_process,
                      Ref :: reference(),
                      ErrorDesc :: ErrorAtom | OpaqueError,
                      ErrorAtom ::
                          linked_in_driver | inconsistent | permanent |
                          not_loaded_by_this_process | not_loaded |
                          pending_reload | pending_process,
                      OpaqueError :: term().

This one gives you way more control than the load/2/reload/2 and load_driver/2/reload_driver/2 interfaces combined. The way it never waits for other operations related to the driver to finish? Iconic. Instead it hands you the driver's status right away, as one of these:

  • {ok, loaded} โ€” the driver is loaded and immediately usable. Go off. ๐ŸŽ‰
  • {ok, already_loaded} โ€” the driver was already loaded by some other process, or it's in use by a living port, or honestly both. Your load is registered regardless, and a matching try_unload is expected from you somewhere down the line. ๐Ÿ“
  • {ok, pending_driver} or {ok, pending_driver, reference()} โ€” your load request is registered, but the actual loading is delayed because an earlier instance of the driver is still waiting to get unloaded (open ports are using it). Still, unload is expected from you when you're done with the driver. This return value mostly shows up when the options {reload, pending_driver} or {reload, pending} are used, but it can also happen when another user is unloading a driver in parallel and the driver option kill_ports is set. In other words โ€” this return value always needs to be handled. Not optional. Periodt. ๐Ÿ’€
  • {ok, pending_process} or {ok, pending_process, reference()} โ€” your load request is registered, but the loading is delayed because an earlier instance of the driver is still waiting to get unloaded by another user (not just by a port โ€” because if it were just a port, you'd have gotten {ok, pending_driver} instead). Still, unload is expected from you when you're done with the driver. This return value only ever happens when the option {reload, pending} is used. ๐Ÿ™ˆ

When the function hands you {ok, pending_driver} or {ok, pending_process}, you can find out when the driver actually gets loaded by using the option {monitor, MonitorOption}. Lowkey genius. ๐Ÿ”

When monitoring is requested, and a corresponding {ok, pending_driver} or {ok, pending_process} would have been returned, the function returns a tuple {ok, PendingStatus, reference()} instead โ€” and then your process gets a monitor message later, when the driver finally gets loaded. The monitor message you should be expecting is described in the function description of monitor/2. ๐Ÿ“ฌ

NOTE: when it comes to loading, monitoring can't only get triggered by using the option {reload, ReloadOption} โ€” it can also get triggered in special cases where the load error is transient. Which means {monitor, pending_driver} is the move under basically all real-world circumstances. Fr fr. โœจ

The function accepts the following parameters, bestie:

๐Ÿ’œ Path

The file system path to the directory where the driver object file lives. The filename of the object file (minus the extension) must correspond to the driver name (used in the parameter Name), and the driver must identify itself with that same name. No identity crises allowed. ๐Ÿชช

Path can be provided as an iolist(), meaning it can be a list of other iolist/0s, characters (8-bit integers), or binaries โ€” all flattened into a sequence of characters.

The (possibly flattened) Path parameter must be consistent throughout the system. A driver is to be loaded, by all users, using the same literal Path. The exception is when reloading is requested, in which case Path can be specified differently. Note though that all users trying to load the driver later need to use the new Path if Path was changed using a reload option. Which is yet another reason to have only one loader of a driver you want to upgrade in a running system. ๐Ÿ‘‘ (iykyk)

๐ŸŽ€ Name

This parameter is the name of the driver, to be used in subsequent calls to the function erlang:open_port in ERTS. The name can be specified as an iolist/0 or an atom/0.

The name you specify when loading is used to find the object file (with a little help from Path and the system-implied extension suffix, that is, .so). And the name by which the driver identifies itself must also be consistent with this Name parameter โ€” much like how the module name of a Beam file has to correspond to its filename. Same energy, different lane. ๐ŸŒˆ

๐ŸŒธ OptionList

Some options can be specified to control the loading operation. They're specified as a list of two-tuples, and those tuples have the following values and meanings:

  • {driver_options, DriverOptionList} โ€” this is to provide options that change its general behavior and stick to the driver throughout its whole lifespan. ๐Ÿ’…

The driver options for a specified driver name always need to be consistent, even when the driver is reloaded โ€” meaning they're as much a part of the driver as the name is.

The only allowed driver option is kill_ports, which means that all ports opened to the driver get killed with exit reason driver_unloaded when no process has the driver loaded any longer. This situation arises either when the last user calls try_unload/2, or when the last process having loaded the driver exits. ๐Ÿ’€

  • {monitor, MonitorOption} โ€” a MonitorOption tells try_load/3 to trigger a driver monitor under certain conditions. When the monitor is triggered, the function returns a three-tuple {ok, PendingStatus, reference()}, where reference/0 is the monitor reference for the driver monitor. ๐Ÿงš

Only one MonitorOption can be specified. It's one of the following:

  • The atom pending, which means that a monitor is to be created whenever a load operation is delayed. โณ
  • The atom pending_driver, in which a monitor is created whenever the operation is delayed because of open ports to an otherwise unused driver. ๐Ÿšช

Option pending_driver is of little use, but it's present for completeness, since it's well defined which reload options can give rise to which delays. Still, it can be a good idea to use the same MonitorOption as the ReloadOption, if present. ๐Ÿค

And if reloading isn't requested, it can still be useful to specify the option monitor, because forced unloads (driver option kill_ports or option kill_ports to try_unload/2) trigger a transient state where driver loading can't be performed until all the closing ports are closed. So, since try_unload can return {ok, pending_driver} in almost all situations, always specify at least {monitor, pending_driver} in production code โ€” go re-read the monitor discussion earlier if you need the receipts. ๐Ÿ”ฅ

  • {reload, ReloadOption} โ€” this option is used to reload a driver from disk, most often in a code upgrade scenario. Having a reload option also implies that the parameter Path does not need to be consistent with earlier loads of the driver. ๐Ÿฆ‹

To reload a driver, the process must have loaded the driver before โ€” that is, there must be an active user of the driver in the process.

The reload option can be either of the following:

  • pending โ€” with the atom pending, reloading is requested for any driver and is effectuated when all ports opened to the driver are closed. The driver replacement in this case takes place regardless of whether there are still pending users having the driver loaded. ๐Ÿ“Œ

pending also triggers port-killing (if the driver option kill_ports is in play) even when there are still pending users โ€” which is what makes it usable for forced driver replacement, but omg it lays so much responsibility on the driver users. And honestly? pending gets used like, never, because nobody wants other users to have loaded the driver while a code change is underway. ๐Ÿ˜ญ

  • pending_driver โ€” okay this one is way more useful ๐Ÿ’–. Here, reloading gets queued if no other users have the driver loaded but the driver has opened ports โ€” and in that case {ok, pending_driver} is returned (a monitor option is recommended, bestie, take the hint).

If the driver is unloaded (like, not present in the system at all), error code not_loaded is returned. Option reload is intended for when the user has already loaded the driver in advance. ๐ŸŽ€

The function can return numerous errors, and some of them can only appear given a certain combination of options. ๐Ÿ‘€

Some errors are opaque and can only be interpreted by passing them to function format_error/1, but a few you can read directly:

  • {error,linked_in_driver} โ€” the driver with the specified name is an Erlang statically linked-in driver, and that cannot be manipulated with this API. Periodt. ๐Ÿšซ
  • {error,inconsistent} โ€” the driver is already loaded with other DriverOptionList or a different literal Path argument. And yes, this can pop up even if a reload option is specified โ€” if DriverOptionList differs from the current one, it's a no. โœจ
  • {error, permanent} โ€” the driver has requested itself to be permanent, which makes it behave like an Erlang linked-in driver and means it can no longer be manipulated with this API. ๐Ÿ‘‘
  • {error, pending_process} โ€” the driver is loaded by other users when option {reload, pending_driver} was specified.
  • {error, pending_reload} โ€” a driver reload was already requested by another user when option {reload, ReloadOption} was specified. Somebody got there first, bestie. ๐Ÿซ 
  • {error, not_loaded_by_this_process} โ€” shows up when option reload is specified. The driver Name is present in the system, but there's no user of it in this process.
  • {error, not_loaded} โ€” also shows up when option reload is specified. The driver Name is not in the system. Only drivers loaded by this process can be reloaded.

All other error codes are to be translated by function format_error/1. โš ๏ธ Notice that calls to format_error are to be performed from the same running instance of the Erlang virtual machine as the error is detected in, because of system-dependent behavior concerning error values.

If the arguments or options are malformed, the function throws a badarg exception.


๐Ÿฆ‹ next up: try_unload

try_unload(Name, OptionList) ->
                    {ok, Status} |
                    {ok, PendingStatus, Ref} |
                    {error, ErrorAtom}
                    when
                        Name :: driver(),
                        OptionList :: [Option],
                        Option :: {monitor, MonitorOption} | kill_ports,
                        MonitorOption :: pending_driver | pending,
                        Status :: unloaded | PendingStatus,
                        PendingStatus ::
                            pending_driver | pending_process,
                        Ref :: reference(),
                        ErrorAtom ::
                            linked_in_driver | not_loaded |
                            not_loaded_by_this_process | permanent.

This is the low-level function to unload (or decrement reference counts of) a driver ๐Ÿ“‰. You can use it to force port killing, in much the same way as the driver option kill_ports implicitly does. Also, it can trigger a monitor โ€” either because other users still have the driver loaded, or because open ports are using the driver. Two very different reasons, same cute little monitor. ๐Ÿ“ก

Unloading is basically the vibe of telling the emulator that this particular part of the code in this particular process (aka, this user) no longer needs the driver. If there are no other users, that can trigger the actual unloading of the driver โ€” the driver name disappears from the system and (if possible) the memory occupied by the driver executable code is reclaimed. Freeing memory? Slay. ๐Ÿ’…

If the driver has option kill_ports set, or if kill_ports is specified as an option to this function, all pending ports using this driver are killed when unloading is done by the last user. If no port-killing is involved and there are open ports, the unloading gets delayed until no more open ports use the driver. And if, in that case, another user (or even this same user) loads the driver again before it's unloaded โ€” the unloading never happens at all. ๐Ÿšซ

To let the user request that unloading wait for actual unloading, monitor triggers can be specified in much the same way as when loading. However โ€” and this is the real tea โ€” users of this function seldom care about more than decrementing the reference counts, so monitoring is seldom needed.

NOTE: If option kill_ports is used, monitor trigging is crucial, as the ports are not guaranteed to be killed until the driver is unloaded. So a monitor must be triggered for at least the pending_driver case. ๐Ÿ˜ค

The possible monitor messages to expect are the same as when using option unloaded to function monitor/2.

The function returns one of these statuses upon success โœจ:

  • {ok, unloaded} โ€” the driver was immediately unloaded, meaning the driver name is now free to use by other drivers and, if the underlying OS permits it, the memory occupied by the driver object code is now reclaimed. ๐Ÿ’€โžก๏ธ๐Ÿฆ‹ The driver can only be unloaded when there are no open ports using it and no more users require it to be loaded.
  • {ok, pending_driver} or {ok, pending_driver, reference()} โ€” this call removed the last user from the driver, but there are still open ports using it. When all ports are closed and no new users have arrived, the driver is unloaded and the name and memory reclaimed. ๐Ÿงน This return value is valid even if option kill_ports was used, since killing ports can be a process that doesn't complete immediately โ€” though in that case the condition is transient. Monitors are always useful to detect when the driver is really unloaded.
  • {ok, pending_process} or {ok, pending_process, reference()} โ€” the unload request is registered, but other users still hold the driver. Notice that the term pending_process can refer to the running process โ€” there can be more than one user in the same process. ๐Ÿ‘ฏ This is a normal, healthy return value if the call was just placed to inform the emulator that you have no further use of the driver. It's the most common return value in the most common scenario described in the introduction.

The function accepts the following parameters:

  • Name โ€” Name is the name of the driver to be unloaded. The name can be specified as an iolist/0 or as an atom/0. ๐Ÿ”ค
  • OptionList โ€” argument OptionList can be used to specify certain behavior regarding ports and triggering monitors under certain conditions:
    • kill_ports โ€” forces killing of all ports opened using this driver, with exit reason driver_unloaded, if you are the last user of the driver. If other users have the driver loaded, this option has no effect. To get the consistent behavior of killing ports when the last user unloads, use driver option kill_ports when loading the driver instead.
    • {monitor, MonitorOption} โ€” creates a driver monitor if the condition specified in MonitorOption is true. The valid options are:
      • pending_driver โ€” creates a driver monitor if the return value is to be {ok, pending_driver}.
      • pending โ€” creates a monitor if the return value is {ok, pending_driver} or {ok, pending_process}.

The pending_driver MonitorOption is by far the most useful one ๐Ÿซถ. It must be used to ensure that the driver really is unloaded and the ports are closed whenever option kill_ports is used, or the driver can have been loaded with driver option kill_ports.

Using the monitor triggers in the call to try_unload ensures that the monitor is added before the unloading is executed โ€” meaning the monitor is always properly triggered, which is not the case if monitor/2 is called separately. ๐Ÿ™ˆ

The function can return the following error conditions, all well specified (no opaque values, bless):

  • {error, linked_in_driver} โ€” you were trying to unload an Erlang statically linked-in driver, which cannot be manipulated with this interface (and cannot be unloaded at all, like, ever).
  • {error, not_loaded} โ€” the driver Name is not present in the system.
  • {error, not_loaded_by_this_process} โ€” the driver Name is present in the system, but there's no user of it in this process. As a special case, drivers can be unloaded from processes that have done no corresponding call to try_load/3 if, and only if, there are no users of the driver at all โ€” which can occur if the process containing the last user dies. ๐Ÿชฆ
  • {error, permanent} โ€” the driver has made itself permanent, in which case it can no longer be manipulated by this interface (much like a statically linked-in driver).

The function throws a badarg exception if the parameters are not specified as described here.


๐ŸŒธ and finally: unload

unload(Name) -> ok | {error, ErrorDesc}
                when Name :: driver(), ErrorDesc :: term().

Unloads, or at least dereferences, the driver named Name. ๐Ÿซก If the caller is the last user of the driver, and no more open ports use the driver, the driver gets unloaded. Otherwise, the unloading is delayed until all ports are closed and no users remain. That's it, that's the whole function. Cute, right? ๐Ÿ’–

If there are other users of the driver, the reference counts of the driver is merely decreased, so that the caller is no longer considered a user of the driver. For use scenarios, see the description in the beginning of this module. (yes bestie, scroll up, the lore is all there ๐Ÿ’–)

The ErrorDesc you get back is an opaque value โ€” like, literally do not try to read it, do not try to interpret it, just pass it further on to format_error/1 and let it do its thing. For more control over the operation, use the try_unload/2 interface instead.

Fr fr, this function throws a badarg exception if the parameters aren't specified exactly as described here. So, like, follow the instructions. ๐Ÿ™ˆ

unload_driver/1 ๐Ÿ’…

unload_driver(Name) -> ok | {error, ErrorDesc}
                       when Name :: driver(), ErrorDesc :: term().

Unloads the driver named Name โ€” or, at the very least, dereferences it. It's giving "I'm leaving the group chat but not necessarily deleting the account," iykyk. ๐Ÿฆ‹

If you are the last user of the driver, then all the remaining open ports using that driver get killed with reason driver_unloaded, and the driver eventually gets unloaded. Not me being the last one in the party and flipping the lights off. ๐Ÿ‘‘

If there are other users of the driver, the reference counts of the driver is merely decreased, so that the caller is no longer considered a user of the driver. For use scenarios, see the description in the beginning of this module. (again โ€” lore's at the top, go look โœจ)

The ErrorDesc returned is an opaque value to be passed further on to function format_error/1. For more control over the operation, use the try_unload/2 interface. It's literally the same deal as unload/1, just with a different name vibe. ๐ŸŽ€

And yes, this function throws a badarg exception if the parameters are not specified as described here. The way that badarg stays undefeated. ๐Ÿ’€

And that's the whole page, bestie!! ๐Ÿซถ You just read the entire erl_ddll(3) manual, no skimming, no skipping, main character energy fr fr. ๐ŸŒˆ

This lil masterpiece comes to you courtesy of <b>Ericsson AB</b>, shipping with <b>kernel 11.0.3</b> โ€” and dated whenever your copy of the page got rendered, which is honestly iconic of it. ๐Ÿ’–

Go forth and dynamically load some drivers. Slay. โญ๐ŸŒธ๐Ÿงš

๐Ÿ“ฆ where this page comes from