erl_ddll(3erl)
πΈ erl_ddll β the dynamic driver loader & linker (from the Erlang Module Definition manual, section 3erl) πΈ
Okay bestie, so this is erl_ddll, and it's literally the module that lets you load and unload Erlang linked-in drivers at runtime. No cap, it's a whole thing. π
β¨ DESCRIPTION β¨
This module gives you an interface for loading and unloading Erlang linked-in drivers in runtime. Iconic behavior, honestly. π
Note: This is a large reference document, okay? Like, huge. For casual use of this module, and for most real-world applications, the descriptions ofload/2andunload/1are enough to get you started. That's it. That's the starter pack. π«Ά
The driver has to be provided as a dynamically linked library in an object code format that's specific for the platform in use β so that means .so files on most Unix systems, and .ddl files on Windows. And listen: an Erlang linked-in driver must provide specific interfaces to the emulator, so this module is not designed for loading arbitrary dynamic libraries. Not every random lib gets to sit with us. π For more info about Erlang drivers, see erts:erl_driver.
When we're describing a set of functions (so, a module, a part of a module, or an application) that's executing in a process and wants to use a ddll-driver, we use the term user. One process can have many users (different modules needing the same driver), and many processes can run the same code, making up many users of a driver. So many users. It's giving group chat. π
In the basic scenario, each user loads the driver before starting to use it, and unloads it 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 β i.e. it has no user. The driver also keeps track of ports that are opened to it, which means unloading can be delayed until all ports are closed, or all ports that use the driver can be killed when it's unloaded. Choose your fighter. π₯
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. Here's the tea: β
π¦ Load and Unload on a "When Needed Basis"
This (most common) scenario 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. Periodt. β¨
Each user of the driver uses literally the same pathname for the driver when demanding load, but the users are not concerned with whether the driver is already loaded from the file system or whether the object code must be loaded from the file system. Not their problem, not their business. π
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. Slay.
If a process having the driver loaded dies, it has the same effect as if unloading is done. π
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, honestly.
π load_driver/2 and unload_driver/1
These interfaces are intended to be used when it's 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. Bye bestie. π
The function names load_driver and unload_driver are kept for backward compatibility. Vintage but valid. π
π¦ Loading and Reloading for Code Replacement
This scenario can occur if the driver code needs replacement during operation of the Erlang emulator. Ngl, 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. 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. Rules are rules. π
The unloading/loading is done as one atomic operation, blocking all processes in the system from using the driver in question while it's in progress. Main character energy, blocking the whole party. π
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. 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 when using the high-level functions, it's also an error to demand reloading when more than one user has the driver loaded. So don't. π«Ά
To simplify driver replacement, avoid designing your system so that more than one user has the driver loaded. Just don't do it. I'm begging.
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.
Since 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. π 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. Learn from my mistakes.
π 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. π₯
However β and this is a big however β if another process has the driver loaded, calling reload_driver returns error code pending_process. 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 driver reloader only. It's a solo act. π
π DATA TYPES π
driver() = iolist() | atom()
path() = string() | atom()
Look at them. Perfect. No notes. β¨
π EXPORTS π
demonitor(MonitorRef) -> ok
Types:
MonitorRef = reference()
Removes a driver monitor in much the same way as erlang:demonitor/1 in ERTS does with process monitors. For details about how to create driver monitors, see monitor/2, try_load/3, and try_unload/2. Very demure, very mindful. π§
The function throws a badarg exception if the parameter is not a reference(). Rude, but fair.
format_error(ErrorDesc) -> string()
Types:
ErrorDesc = term()
Takes an ErrorDesc returned by load, unload, or reload functions and returns a string that describes the error or warning. Translation services, but for errors. π¦
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 carrying that error across VMs like it's a souvenir. π
info() -> AllInfoList
Types:
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. Static drivers? Not invited to this party. π
info(Name) -> InfoList
Types:
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. The whole lore drop. π
The following tags appear in the list:
processesdriver_optionsport_countlinked_in_driverpermanentawaiting_loadawaiting_unload
For a detailed description of each value, see info/2. π
The function throws a badarg exception if the driver is not present in the system. Gone girl behavior.
info(Name, Tag) -> Value
Types:
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}, whereinteger()denotes the number of users in processpid(). The whole roster. π«Ά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 iskill_ports. That's the only one, bestie. πport_countβ Returns the number of ports (aninteger() >= 0) using the driver. Count 'em.linked_in_driverβ Returns aboolean(), which istrueif the driver is a statically linked-in one, otherwisefalse. Built different, or not.permanentβ Returns aboolean(), which istrueif the driver has made itself permanent (and is not a statically linked-in driver), otherwisefalse. Forever girl. πawaiting_loadβ Returns a list of all processes having monitors for loading active. Each process is returned as{pid(),integer() >= 0}, whereinteger()is the number of monitors held by processpid(). Waiting era. βawaiting_unloadβ Returns a list of all processes having monitors for unloading active. Each process is returned as{pid(),integer() >= 0}, whereinteger()is the number of monitors held by processpid(). Also waiting era. π
If option linked_in_driver or permanent returns true, all other options return linked_in_driver or permanent, respectively. iykyk. π€«
The function throws a badarg exception if the driver is not present in the system, or if the tag is not supported. Double rejection. π
π load(Path, Name) -> ok | {error, ErrorDesc}
Types:
Path = path()
Name = driver()
ErrorDesc = term()
Okay bestie, this one loads and links the dynamic driver Name. Path is a file path to the directory that has the driver in it. Name has to be a shareable object/dynamic library. Two drivers with different Path params cannot be loaded under the same name. Name is a string or atom with at least one character, no empty-string nonsense.
The Name you give is supposed to match the filename of the dynamically loadable object file sitting in the directory you passed as Path, but without the extension (so, without .so). The driver name provided in the driver initialization routine has to correspond with the filename, basically the same way Erlang module names correspond to .beam filenames. It's giving "name match energy" fr fr.
If the driver was previously unloaded but is still hanging around because there are open ports to it, calling load/2 stops the unloading and keeps the driver (as long as Path is the same), and you get ok back. If you actually want the object code reloaded, use reload/2 or the low-level try_load/3 interface instead. Also peep the intro for the different loading/unloading scenarios.
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. That means it's safe for an app to load a driver shared between processes or applications when needed. It can safely be unloaded without causing trouble for other parts of the system. Teamwork, slay.
It is not allowed to load multiple drivers with the same name but with different Path parameters. Periodt.
π Note:Pathis interpreted literally, so all loaders of the same driver must specify the same literalPathstring, even though different paths can point out the same directory in the file system (because of relative paths and links). Literal literal, no cap.
On success, the function returns ok. On failure, the return value is {error,ErrorDesc}, where ErrorDesc is an opaque term that you translate into human-readable form with 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. So don't try it.
π¦ load_driver(Path, Name) -> ok | {error, ErrorDesc}
Types:
Path = path()
Name = driver()
ErrorDesc = term()
Works essentially as load/2, but loads the driver with other options. All ports using the driver are killed with reason driver_unloaded when the driver is to be unloaded. Dramatic? Yes. Accurate? Also yes.
The number of loads and unloads by different users influences the loading and unloading of a driver file. The port killing therefore only occurs when the last user unloads the driver, or when the last process having loaded the driver exits.
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() -> {ok, Drivers}
Types:
Drivers = [Driver]
Driver = string()
Returns a list of all the available drivers β both the (statically) linked-in ones and the dynamically loaded ones.
The driver names come back as a list of strings rather than a list of atoms for historical reasons. Cute lil legacy quirk, iykyk.
For more information about drivers, see info.
π monitor(Tag, Item) -> MonitorRef
Types:
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 gets sent to the calling process. MonitorRef returned by this function is included in the message sent.
As with process monitors, each driver monitor set only generates one single message. The monitor is "destroyed" after the message is sent, so you don't need to call demonitor/1 afterward. It already ate and left.
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 alwaysdriver, because this function can only be used to create driver monitors. In the future, driver monitors will be integrated with process monitors, which is why this parameter has to be specified for consistence.Itemβ ParameterItemspecifies 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 functiontry_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,<|place_holder_mm_span_0442|>Name, load_cancelled}β This message arrives if reloading was underway, but the requesting user cancelled it by dying or callingtry_unload/2(orunload/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. TheFailureterm is one of the errors that can be returned fromtry_load/3. The error term can be passed toformat_error/1for 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. No cross-VM translation shenanigans.
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. Surprise! π
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 areload/2request, 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 asunloaded_onlybehaves exactly as one created asunloadedexcept that the{'UP', reference(), driver, Name, unload_cancelled}message is never sent, but the monitor instead persists until the driver really gets unloaded. Patient queen behavior.
The function throws a badarg exception if the parameters are not specified as described here.
π§ reload(Path, Name) -> ok | {error, ErrorDesc}
Types:
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, it'll just vibe there waiting. Don't panic.
Note: Bestie, lowkey donβt mix multiple users with driver reload requests. To avoid hanging on open ports, use function try_load/3 instead.
TheNameandPathparameters have exactly the same meaning as when calling the plain functionload/2.
On success, the function returnsok. On failure, the function returns an opaque error, except thepending_processerror described earlier. The opaque errors are to be translated into human readable form by functionformat_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.
π reload_driver(Path, Name) -> ok | {error, ErrorDesc}
Types:
Path = path()
Name = driver()
ErrorDesc = pending_process | OpaqueError
OpaqueError = term()
Okay so this one works exactly like reload/2, but itβs for drivers loaded with the load_driver/2 interface. π
Since this interface implies that ports are killed when the last user disappears, the function does not hang waiting for ports to get closed. No sitting around waiting for the group chat to go quiet β it just returns.
For more details, see the scenarios in this module description and the function description for reload/2.
The function throws a badarg exception if the parameters are not specified as described here.
π¦ try_load(Path, Name, OptionList) -> {ok, Status} | {ok, PendingStatus, Ref} | {error, ErrorDesc}
Types:
Path = path()
Name = driver()
OptionList = [Option]
Option =
{driver_options, DriverOptionList} |
{monitor, MonitorOption} |
{reload, ReloadOption}
DriverOptionList = [DriverOption]
DriverOption = kill_ports
MonitorOption = 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 function gives you way more control than the load/2/reload/2 and load_driver/2/reload_driver/2 interfaces. It never waits for completion of other operations related to the driver. It immediately returns the status of the driver as one of the following:
{ok, loaded}β the driver was loaded and is immediately usable. Slay, itβs ready. β¨{ok, already_loaded}β the driver was already loaded by another process or is in use by a living port, or both. The load by you is registered and a correspondingtry_unloadis expected sometime in the future. So like, youβre in the queue, bestie.{ok, pending_driver}or {ok, pending_driver, reference()}β the load request is registered, but the loading is delayed because an earlier instance of the driver is still waiting to get unloaded (open ports use it). Still, unload is expected when you are done with the driver. This return value mostly occurs when options{reload,pending_driver}or{reload,pending}are used, but can occur when another user is unloading a driver in parallel and driver optionkill_portsis set. In other words, this return value always needs to be handled. Do not ignore it. π{ok, pending_process}or {ok, pending_process, reference()}β the 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 only by a port, in which case{ok,pending_driver}would have been returned). Still, unload is expected when you are done with the driver. This return value only occurs when option{reload,pending}is used.
When the function returns {ok, pending_driver} or {ok, pending_process}, one can get information about when the driver is actually loaded by using option {monitor, MonitorOption}.
When monitoring is requested, and a corresponding {ok, pending_driver} or {ok, pending_process} would be returned, the function instead returns a tuple {ok, PendingStatus, reference()} and the process then gets a monitor message later, when the driver gets loaded. The monitor message to expect is described in the function description of monitor/2.
Note: In case of loading, monitoring can not only get triggered by using option{reload, ReloadOption}, but also in special cases where the load error is transient. Thus,{monitor, pending_driver}is to be used under basically all real world circumstances. Like, genuinely, just use it. π«Ά
The function accepts the following parameters:
Pathβ the file system path to the directory where the driver object file is located. The filename of the object file (minus extension) must correspond to the driver name (used in parameterName) and the driver must identify itself with the same name.Pathcan be provided as aniolist(), meaning it can be a list of otheriolist()s, characters (8-bit integers), or binaries, all to be flattened into a sequence of characters.
The (possibly flattened) Path parameter must be consistent throughout the system. A driver is to, by all users, be loaded using the same literal Path. The exception is when reloading is requested, in which case Path can be specified differently. Notice that all users trying to load the driver later need to use the new Path if Path is changed using a reload option. This is yet another reason to have only one loader of a driver one wants to upgrade in a running system. One loader, bestie. One. π
Nameβ this parameter is the name of the driver to be used in subsequent calls to functionerlang:open_portin ERTS. The name can be specified as aniolist()or anatom(). The name specified when loading is used to find the object file (with the help ofPathand the system-implied extension suffix, that is,.so). The name by which the driver identifies itself must also be consistent with thisNameparameter, much as the module name of a Beam file much corresponds to its filename. Identity consistency is the vibe. πOptionListβ some options can be specified to control the loading operation. The options are specified as a list of two-tuples. The tuples have the following values and meanings:{driver_options, DriverOptionList}β this is to provide options that changes its general behavior and "sticks" to the driver throughout its lifespan.
The driver options for a specified driver name need always to be consistent, even when the driver is reloaded, meaning that they are as much a part of the driver as the name.
The only allowed driver option is kill_ports, which means that all ports opened to the driver are killed with exit reason driver_unloaded when no process any longer has the driver loaded. This situation arises either when the last user calls try_unload/2, or when the last process having loaded the driver exits. Ports get got. π
{monitor, MonitorOption}β aMonitorOptiontellstry_load/3to trigger a driver monitor under certain conditions. When the monitor is triggered, the function returns a three-tuple{ok, PendingStatus, reference()}, wherereference()is the monitor reference for the driver monitor.
Only one MonitorOption can be specified. It is 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 is present for completeness, as it is well defined which reload options that can give rise to which delays. However, it can be a good idea to use the same MonitorOption as the ReloadOption, if present.
If reloading is not requested, it can still be useful to specify option monitor, as forced unloads (driver option kill_ports or option kill_ports to try_unload/2) trigger a transient state where driver loading cannot be performed until all closing ports are closed. Thus, as try_unload can, in almost all situations, return {ok, pending_driver}, always specify at least {monitor, pending_driver} in production code (see the monitor discussion earlier). Production code bestie, not vibes-only code. πΈ
{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 parameterPathdoes 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 atompending, 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 if there are still pending users having the driver loaded. Iconic reload behavior, no cap. π
Okay so back to the {reload, ReloadOption} tea β β the pending option also triggers port-killing (if the driver option kill_ports is used) even though there are pending users. That makes it usable for forced driver replacement, but it lays much responsibility on the driver users. The pending option is seldom used because, like, you don't want other users to have loaded the driver when code change is underway, bestie.
pending_driverβ This option is way more useful. Here, reloading is queued if the driver is not loaded by any other users, but the driver has opened ports, in which case{ok, pending_driver}is returned (a monitor option is recommended, fr).
If the driver is unloaded (not present in the system), 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 can only be returned given a certain combination of options.
Some errors are opaque and can only be interpreted by passing them to function format_error/1, but some can be interpreted directly:
{error,linked_in_driver}β The driver with the specified name is an Erlang statically linked-in driver, which cannot be manipulated with this API. π«{error,inconsistent}β The driver is already loaded with otherDriverOptionListor a different literalPathargument.
This can occur even if a reload option is specified, if DriverOptionList differs from the current.
{error, permanent}β The driver has requested itself to be permanent, making it behave like an Erlang linked-in driver and 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}β Driver reload is already requested by another user when option{reload, ReloadOption}was specified.{error, not_loaded_by_this_process}β Appears when optionreloadis specified. The driverNameis present in the system, but there is no user of it in this process.{error, not_loaded}β Appears when optionreloadis specified. The driverNameis 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.
π¦ try_unload(Name, OptionList) π¦
try_unload(Name, OptionList) ->
{ok, Status} |
{ok, PendingStatus, Ref} |
{error, ErrorAtom}
Types:
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. It can be used 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 use the driver. π₯
Unloading can be described as the process of telling the emulator that this particular part of the code in this particular process (that is, this user) no longer needs the driver. That can, if there are no other users, trigger unloading of the driver, in which case the driver name disappears from the system and (if possible) the memory occupied by the driver executable code is reclaimed. π§
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 is delayed until no more open ports use the driver. If, in this case, another user (or even this user) loads the driver again before the driver is unloaded, the unloading never takes place. π
To allow the user to request unloading to wait for actual unloading, monitor triggers can be specified in much the same way as when loading. However, as users of this function seldom are interested in more than decrementing the reference counts, monitoring is seldom needed.
Note: If optionkill_portsis used, monitor trigging is crucial, as the ports are not guaranteed to be killed until the driver is unloaded. Thus, a monitor must be triggered for at least thepending_drivercase. β οΈ
The possible monitor messages to expect are the same as when using option unloaded to function monitor/2.
The function returns one of the following statuses upon success:
{ok, unloaded}β The driver was immediately unloaded, meaning that 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()}β Indicates that 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 reloaded and the name and memory reclaimed.
This return value is valid even if option kill_ports was used, as killing ports can be a process that does not complete immediately. However, the condition is in that case 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 termpending_processcan 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 is the most common return value in the most common scenario described in the introduction. π
The function accepts the following parameters:
NameβNameis the name of the driver to be unloaded. The name can be specified as aniolist()or as anatom().OptionListβ ArgumentOptionListcan 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 reasondriver_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 inMonitorOptionis 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. It must be used to ensure that the driver really is unloaded and the ports 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 that 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):
{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). π{error, not_loaded}β The driverNameis not present in the system.{error, not_loaded_by_this_process}β The driverNameis present in the system, but there is 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.
πΈ unload(Name) πΈ
unload(Name) -> ok | {error, ErrorDesc}
Types:
Name = driver()
ErrorDesc = term()
Okay so this call unloads β or at the very 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, unloading is delayed until all ports are closed and no users remain. π
If there are other users of the driver, the reference counts of the driver are 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. π«Ά
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.
This function throws a badarg exception if the parameters are not specified as described here. π
unload_driver/1
unload_driver(Name) -> ok | {error, ErrorDesc}
Types:
Name = driver()ErrorDesc = term()
Unloads, or at least dereferences, the driver named Name. If the caller is the last user of the driver, all remaining open ports using the driver are killed with reason driver_unloaded and the driver eventually gets unloaded. π
If there are other users of the driver, the reference counts of the driver are merely decreased, so that the caller is no longer considered a user. For use scenarios, see the description in the beginning of this module.
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.
The function throws a badarg exception if the parameters are not specified as described here. β¨
π¦ SEE ALSO π¦
erts:erl_driver(5)erts:driver_entry(5)
Later bestie β this iconic lil page is brought to you by Ericsson AB, version kernel 8.5.4.2, and the erl_ddll(3erl) manual itself. Slay. πβ¨
π¦ where this page comes from
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4 Β· Apache-2.0
- ubuntu noble: erlang-manpages 1:25.3.2.8+dfsg-1ubuntu4.8 Β· Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms