Erlang logo
Reference Manual
Release Notes
PDF
Top

Kernel
Reference Manual
Version 2.14.5


Expand All
Contract All

Table of Contents

code

MODULE

code

MODULE SUMMARY

Erlang Code Server

DESCRIPTION

This module contains the interface to the Erlang code server, which deals with the loading of compiled code into a running Erlang runtime system.

The runtime system can be started in either embedded or interactive mode. Which one is decided by the command line flag -mode.

% erl -mode interactive

Default mode is interactive.

  • In embedded mode, all code is loaded during system start-up according to the boot script. (Code can also be loaded later by explicitly ordering the code server to do so).

  • In interactive mode, only some code is loaded during system startup-up, basically the modules needed by the runtime system itself. Other code is dynamically loaded when first referenced. When a call to a function in a certain module is made, and the module is not loaded, the code server searches for and tries to load the module.

To prevent accidentally reloading modules affecting the Erlang runtime system itself, the kernel, stdlib and compiler directories are considered sticky. This means that the system issues a warning and rejects the request if a user tries to reload a module residing in any of them. The feature can be disabled by using the command line flag -nostick.

Code Path

In interactive mode, the code server maintains a search path -- usually called the code path -- consisting of a list of directories, which it searches sequentially when trying to load a module.

Initially, the code path consists of the current working directory and all Erlang object code directories under the library directory $OTPROOT/lib, where $OTPROOT is the installation directory of Erlang/OTP, code:root_dir(). Directories can be named Name[-Vsn] and the code server, by default, chooses the directory with the highest version number among those which have the same Name. The -Vsn suffix is optional. If an ebin directory exists under Name[-Vsn], it is this directory which is added to the code path.

The environment variable ERL_LIBS (defined in the operating system) can be used to define additional library directories that will be handled in the same way as the standard OTP library directory described above, except that directories that do not have an ebin directory will be ignored.

All application directories found in the additional directories will appear before the standard OTP applications, except for the Kernel and STDLIB applications, which will be placed before any additional applications. In other words, modules found in any of the additional library directories will override modules with the same name in OTP, except for modules in Kernel and STDLIB.

The environment variable ERL_LIBS (if defined) shold contain a colon-separated (for Unix-like systems) or semicolon-separated (for Windows) list of additional libraries.

Example: On an Unix-like system, ERL_LIBS could be set to /usr/local/jungerl:/home/some_user/my_erlang_lib. (On Windows, use semi-colon as separator.)

Code Path Cache

The code server incorporates a code path cache. The cache functionality is disabled by default. To activate it, start the emulator with the command line flag -code_path_cache or call code:rehash(). When the cache is created (or updated), the code server searches for modules in the code path directories. This may take some time if the the code path is long. After the cache creation, the time for loading modules in a large system (one with a large directory structure) is significantly reduced compared to having the cache disabled. The code server is able to look up the location of a module from the cache in constant time instead of having to search through the code path directories.

Application resource files (.app files) are also stored in the code path cache. This feature is used by the application controller (see application(3)) to load applications efficiently in large systems.

Note that when the code path cache is created (or updated), any relative directory names in the code path are converted to absolute.

Loading of Code From Archive Files

Warning

The support for loading of code from archive files is experimental. The sole purpose of releasing it before it is ready is to obtain early feedback. The file format, semantics, interfaces etc. may be changed in a future release. The function lib_dir/2 and the flag -code_path_choice are also experimental.

In the current implementation, Erlang archives are ZIP files with .ez extension. Erlang archives may also be enclosed in escript files whose file extension is arbitrary.

Erlang archive files may contain entire Erlang applications or parts of applications. The structure in an archive file is the same as the directory structure for an application. If you for example would create an archive of mnesia-4.4.7, the archive file must be named mnesia-4.4.7.ez and it must contain a top directory with the name mnesia-4.4.7. If the version part of the name is omitted, it must also be omitted in the archive. That is, a mnesia.ez archive must contain a mnesia top directory.

An archive file for an application may for example be created like this:

   zip:create("mnesia-4.4.7.ez", 
              ["mnesia-4.4.7"], 
              [{cwd, code:lib_dir()},
               {compress, all},
               {uncompress,[".beam",".app"]}]).

Any file in the archive may be compressed, but in order to speed up the access of frequently read files, it may be a good idea to store beam and app files uncompressed in the archive.

Normally the top directory of an application is located either in the library directory $OTPROOT/lib or in a directory referred to by the environment variable ERL_LIBS. At startup when the initial code path is computed, the code server will also look for archive files in these directories and possibly add ebin directories in archives to the code path. The code path will then contain paths to directories that looks like $OTPROOT/lib/mnesia.ez/mnesia/ebin or $OTPROOT/lib/mnesia-4.4.7.ez/mnesia-4.4.7/ebin.

The code server uses the module erl_prim_loader (possibly via the erl_boot_server) to read code files from archives. But the functions in erl_prim_loader may also be used by other applications to read files from archives. For example, the call erl_prim_loader:list_dir( "/otp/root/lib/mnesia-4.4.7.ez/mnesia-4.4.7/examples/bench)" would list the contents of a directory inside an archive. See erl_prim_loader(3)

.

An application archive file and a regular application directory may coexist. This may be useful when there is a need of having parts of the application as regular files. A typical case is the priv directory which must reside as a regular directory in order to be able to dynamically link in drivers and start port programs. For other applications that do not have this need, the priv directory may reside in the archive and the files under the priv directory may be read via the erl_prim_loader.

At the time point when a directory is added to the code path as well as when the entire code path is (re)set, the code server will decide which subdirectories in an application that shall be read from the archive and which that shall be read as regular files. If directories are added or removed afterwards, the file access may fail if the code path is not updated (possibly to the same path as before in order to trigger the directory resolution update). For each directory on the second level (ebin, priv, src etc.) in the application archive, the code server will firstly choose the regular directory if it exists and secondly from the archive. The function code:lib_dir/2 returns the path to the subdirectory. For example code:lib_dir(megaco,ebin) may return /otp/root/lib/megaco-3.9.1.1.ez/megaco-3.9.1.1/ebin while code:lib_dir(megaco,priv) may return /otp/root/lib/megaco-3.9.1.1/priv.

When an escript file contains an archive, there are neither restrictions on the name of the escript nor on how many applications that may be stored in the embedded archive. Single beam files may also reside on the top level in the archive. At startup, both the top directory in the embedded archive as well as all (second level) ebin directories in the embedded archive are added to the code path. See escript(1)

When the choice of directories in the code path is strict, the directory that ends up in the code path will be exactly the stated one. This means that if for example the directory $OTPROOT/lib/mnesia-4.4.7/ebin is explicitly added to the code path, the code server will not load files from $OTPROOT/lib/mnesia-4.4.7.ez/mnesia-4.4.7/ebin and vice versa.

This behavior can be controlled via the command line flag -code_path_choice Choice. If the flag is set to relaxed, the code server will instead choose a suitable directory depending on the actual file structure. If there exists a regular application ebin directory,situation it will be choosen. But if it does not exist, the ebin directory in the archive is choosen if it exists. If neither of them exists the original directory will be choosen.

The command line flag -code_path_choice Choice does also affect how init interprets the boot script. The interpretation of the explicit code paths in the boot script may be strict or relaxed. It is particular useful to set the flag to relaxed when you want to elaborate with code loading from archives without editing the boot script. The default is relaxed. See init(3)

Current and Old Code

The code of a module can exists in two variants in a system: current code and old code. When a module is loaded into the system for the first time, the code of the module becomes 'current' and the global export table is updated with references to all functions exported from the module.

If then a new instance of the module is loaded (perhaps because of the correction of an error), then the code of the previous instance becomes 'old', and all export entries referring to the previous instance are removed. After that the new instance is loaded as if it was loaded for the first time, as described above, and becomes 'current'.

Both old and current code for a module are valid, and may even be evaluated concurrently. The difference is that exported functions in old code are unavailable. Hence there is no way to make a global call to an exported function in old code, but old code may still be evaluated because of processes lingering in it.

If a third instance of the module is loaded, the code server will remove (purge) the old code and any processes lingering in it will be terminated. Then the third instance becomes 'current' and the previously current code becomes 'old'.

For more information about old and current code, and how to make a process switch from old to current code, refer to Erlang Reference Manual.

Argument Types and Invalid Arguments

Generally, module and application names are atoms, while file and directory names are strings. For backward compatibility reasons, some functions accept both strings and atoms, but a future release will probably only allow the arguments that are documented.

From the R12B release, functions in this module will generally fail with an exception if they are passed an incorrect type (for instance, an integer or a tuple where an atom was expected). An error tuple will be returned if type of argument was correct, but there was some other error (for instance, a non-existing directory given to set_path/1.

DATA TYPES

load_ret() = {error, What :: load_error_rsn()}
           | {module, Module :: module()}

load_error_rsn() = badfile
                 | native_code
                 | nofile
                 | not_purged
                 | on_load
                 | sticky_directory

EXPORTS

set_path(Path) -> true | {error, What}

Types:

Path = [Dir :: file:filename()]
What = bad_directory | bad_path

Sets the code path to the list of directories Path.

Returns true if successful, or {error, bad_directory} if any Dir is not the name of a directory, or {error, bad_path} if the argument is invalid.

get_path() -> Path

Types:

Path = [Dir :: file:filename()]

Returns the code path

add_path(Dir) -> add_path_ret()
add_pathz(Dir) -> add_path_ret()

Types:

add_path_ret() = true | {error, bad_directory}

Adds Dir to the code path. The directory is added as the last directory in the new path. If Dir already exists in the path, it is not added.

Returns true if successful, or {error, bad_directory} if Dir is not the name of a directory.

add_patha(Dir) -> add_path_ret()

Types:

add_path_ret() = true | {error, bad_directory}

Adds Dir to the beginning of the code path. If Dir already exists, it is removed from the old position in the code path.

Returns true if successful, or {error, bad_directory} if Dir is not the name of a directory.

add_paths(Dirs) -> ok
add_pathsz(Dirs) -> ok

Types:

Dirs = [Dir :: file:filename()]

Adds the directories in Dirs to the end of the code path. If a Dir already exists, it is not added. This function always returns ok, regardless of the validity of each individual Dir.

add_pathsa(Dirs) -> ok

Types:

Dirs = [Dir :: file:filename()]

Adds the directories in Dirs to the beginning of the code path. If a Dir already exists, it is removed from the old position in the code path. This function always returns ok, regardless of the validity of each individual Dir.

del_path(NameOrDir) -> boolean() | {error, What}

Types:

NameOrDir = Name | Dir
Name = atom()
What = bad_name

Deletes a directory from the code path. The argument can be an atom Name, in which case the directory with the name .../Name[-Vsn][/ebin] is deleted from the code path. It is also possible to give the complete directory name Dir as argument.

Returns true if successful, or false if the directory is not found, or {error, bad_name} if the argument is invalid.

replace_path(Name, Dir) -> true | {error, What}

Types:

Name = atom()
What = bad_directory | bad_name | {badarg, term()}

This function replaces an old occurrence of a directory named .../Name[-Vsn][/ebin], in the code path, with Dir. If Name does not exist, it adds the new directory Dir last in the code path. The new directory must also be named .../Name[-Vsn][/ebin]. This function should be used if a new version of the directory (library) is added to a running system.

Returns true if successful, or {error, bad_name} if Name is not found, or {error, bad_directory} if Dir does not exist, or {error, {badarg, [Name, Dir]}} if Name or Dir is invalid.

load_file(Module) -> load_ret()

Types:

Module = module()
load_ret() = {error, What :: load_error_rsn()}
           | {module, Module :: module()}

Tries to load the Erlang module Module, using the code path. It looks for the object code file with an extension that corresponds to the Erlang machine used, for example Module.beam. The loading fails if the module name found in the object code differs from the name Module. load_binary/3 must be used to load object code with a module name that is different from the file name.

Returns {module, Module} if successful, or {error, nofile} if no object code is found, or {error, sticky_directory} if the object code resides in a sticky directory. Also if the loading fails, an error tuple is returned. See erlang:load_module/2 for possible values of What.

load_abs(Filename) -> load_ret()

Types:

Filename = file:filename()
load_ret() = {error, What :: load_error_rsn()}
           | {module, Module :: module()}

loaded_filename() = (Filename :: file:filename())
                  | loaded_ret_atoms()

loaded_ret_atoms() = cover_compiled | preloaded

Does the same as load_file(Module), but Filename is either an absolute file name, or a relative file name. The code path is not searched. It returns a value in the same way as load_file/1. Note that Filename should not contain the extension (for example ".beam"); load_abs/1 adds the correct extension itself.

ensure_loaded(Module) -> {module, Module} | {error, What}

Types:

Module = module()
What = embedded | badfile | native_code | nofile | on_load

Tries to to load a module in the same way as load_file/1, unless the module is already loaded. In embedded mode, however, it does not load a module which is not already loaded, but returns {error, embedded} instead.

load_binary(Module, Filename, Binary) ->
               {module, Module} | {error, What}

Types:

Module = module()
Filename = loaded_filename()
Binary = binary()
What = badarg | load_error_rsn()
loaded_filename() = (Filename :: file:filename())
                  | loaded_ret_atoms()

loaded_ret_atoms() = cover_compiled | preloaded

This function can be used to load object code on remote Erlang nodes. The argument Binary must contain object code for Module. Filename is only used by the code server to keep a record of from which file the object code for Module comes. Accordingly, Filename is not opened and read by the code server.

Returns {module, Module} if successful, or {error, sticky_directory} if the object code resides in a sticky directory, or {error, badarg} if any argument is invalid. Also if the loading fails, an error tuple is returned. See erlang:load_module/2 for possible values of What.

delete(Module) -> boolean()

Types:

Module = module()

Removes the current code for Module, that is, the current code for Module is made old. This means that processes can continue to execute the code in the module, but that no external function calls can be made to it.

Returns true if successful, or false if there is old code for Module which must be purged first, or if Module is not a (loaded) module.

purge(Module) -> boolean()

Types:

Module = module()

Purges the code for Module, that is, removes code marked as old. If some processes still linger in the old code, these processes are killed before the code is removed.

Returns true if successful and any process needed to be killed, otherwise false.

soft_purge(Module) -> boolean()

Types:

Module = module()

Purges the code for Module, that is, removes code marked as old, but only if no processes linger in it.

Returns false if the module could not be purged due to processes lingering in old code, otherwise true.

is_loaded(Module) -> {file, Loaded} | false

Types:

Module = module()
Loaded = loaded_filename()
loaded_filename() = (Filename :: file:filename())
                  | loaded_ret_atoms()

Filename is an absolute filename
loaded_ret_atoms() = cover_compiled | preloaded

Checks if Module is loaded. If it is, {file, Loaded} is returned, otherwise false.

Normally, Loaded is the absolute file name Filename from which the code was obtained. If the module is preloaded (see script(4)), Loaded==preloaded. If the module is Cover compiled (see cover(3)), Loaded==cover_compiled.

all_loaded() -> [{Module, Loaded}]

Types:

Module = module()
Loaded = loaded_filename()
loaded_filename() = (Filename :: file:filename())
                  | loaded_ret_atoms()

Filename is an absolute filename
loaded_ret_atoms() = cover_compiled | preloaded

Returns a list of tuples {Module, Loaded} for all loaded modules. Loaded is normally the absolute file name, as described for is_loaded/1.

which(Module) -> Which

Types:

Module = module()
Which = file:filename() | loaded_ret_atoms() | non_existing
loaded_ret_atoms() = cover_compiled | preloaded

If the module is not loaded, this function searches the code path for the first file which contains object code for Module and returns the absolute file name. If the module is loaded, it returns the name of the file which contained the loaded object code. If the module is pre-loaded, preloaded is returned. If the module is Cover compiled, cover_compiled is returned. non_existing is returned if the module cannot be found.

get_object_code(Module) -> {Module, Binary, Filename} | error

Types:

Module = module()
Binary = binary()
Filename = file:filename()

Searches the code path for the object code of the module Module. It returns {Module, Binary, Filename} if successful, and error if not. Binary is a binary data object which contains the object code for the module. This can be useful if code is to be loaded on a remote node in a distributed system. For example, loading module Module on a node Node is done as follows:

...
{_Module, Binary, Filename} = code:get_object_code(Module),
rpc:call(Node, code, load_binary, [Module, Filename, Binary]),
...

root_dir() -> file:filename()

Returns the root directory of Erlang/OTP, which is the directory where it is installed.

> code:root_dir().
"/usr/local/otp"

lib_dir() -> file:filename()

Returns the library directory, $OTPROOT/lib, where $OTPROOT is the root directory of Erlang/OTP.

> code:lib_dir().
"/usr/local/otp/lib"

lib_dir(Name) -> file:filename() | {error, bad_name}

Types:

Name = atom()

This function is mainly intended for finding out the path for the "library directory", the top directory, for an application Name located under $OTPROOT/lib or on a directory referred to via the ERL_LIBS environment variable.

If there is a regular directory called Name or Name-Vsn in the code path with an ebin subdirectory, the path to this directory is returned (not the ebin directory). If the directory refers to a directory in an archive, the archive name is stripped away before the path is returned. For example, if the directory /usr/local/otp/lib/mnesia-4.2.2.ez/mnesia-4.2.2/ebin is in the path, /usr/local/otp/lib/mnesia-4.2.2/ebin will be returned. This means that the library directory for an application is the same, regardless of whether the application resides in an archive or not.

> code:lib_dir(mnesia).
"/usr/local/otp/lib/mnesia-4.2.2"

Returns {error, bad_name} if Name is not the name of an application under $OTPROOT/lib or on a directory referred to via the ERL_LIBS environment variable. Fails with an exception if Name has the wrong type.

Warning

For backward compatibility, Name is also allowed to be a string. That will probably change in a future release.

lib_dir(Name, SubDir) -> file:filename() | {error, bad_name}

Types:

Name = SubDir = atom()

Returns the path to a subdirectory directly under the top directory of an application. Normally the subdirectories resides under the top directory for the application, but when applications at least partly resides in an archive the situation is different. Some of the subdirectories may reside as regular directories while other resides in an archive file. It is not checked if this directory really exists.

> code:lib_dir(megaco, priv).
"/usr/local/otp/lib/megaco-3.9.1.1/priv"

Fails with an exception if Name or SubDir has the wrong type.

compiler_dir() -> file:filename()

Returns the compiler library directory. Equivalent to code:lib_dir(compiler).

priv_dir(Name) -> file:filename() | {error, bad_name}

Types:

Name = atom()

Returns the path to the priv directory in an application. Equivalent to code:lib_dir(Name, priv)..

Warning

For backward compatibility, Name is also allowed to be a string. That will probably change in a future release.

objfile_extension() -> nonempty_string()

Returns the object code file extension that corresponds to the Erlang machine used, namely ".beam".

stick_dir(Dir) -> ok | error

Types:

This function marks Dir as sticky.

Returns ok if successful or error if not.

unstick_dir(Dir) -> ok | error

Types:

This function unsticks a directory which has been marked as sticky.

Returns ok if successful or error if not.

is_sticky(Module) -> boolean()

Types:

Module = module()

This function returns true if Module is the name of a module that has been loaded from a sticky directory (or in other words: an attempt to reload the module will fail), or false if Module is not a loaded module or is not sticky.

rehash() -> ok

This function creates or rehashes the code path cache.

where_is_file(Filename) -> non_existing | Absname

Types:

Filename = Absname = file:filename()

Searches the code path for Filename, a file of arbitrary type. If found, the full name is returned. non_existing is returned if the file cannot be found. The function can be useful, for example, to locate application resource files. If the code path cache is used, the code server will efficiently read the full name from the cache, provided that Filename is an object code file or an .app file.

clash() -> ok

Searches the entire code space for module names with identical names and writes a report to stdout.

is_module_native(Module) -> boolean() | undefined

Types:

Module = module()

This function returns true if Module is name of a loaded module that has native code loaded, and false if Module is loaded but does not have native. If Module is not loaded, this function returns undefined.