beam_lib(3erl)
โจ beam_lib(3erl) โ Erlang Module Definition โจ
๐ NAME ๐
beam_lib โ an interface to the BEAM file format. That's the whole name, and honestly it's giving VIP pass into BEAM files, bestie. ๐
๐ฆ DESCRIPTION ๐ฆ
Okay so this module gives you an interface to files created by the BEAM Compiler ("BEAM files"). The format used is a variant of "EA IFF 1985" Standard for Interchange Format Files, and it divides data into chunks. Cute, organized, chunkified. โจ
Chunk data can be returned as binaries or as compound terms. Compound terms are returned when chunks are referenced by names (atoms) rather than identifiers (strings). The recognized names and the corresponding identifiers are as follows:
atomsโ identifier"Atom"attributesโ identifier"Attr"compile_infoโ identifier"CInf"debug_infoโ identifier"Dbgi"exportsโ identifier"ExpT"importsโ identifier"ImpT"indexed_importsโ identifier"ImpT"labeled_exportsโ identifier"ExpT"labeled_localsโ identifier"LocT"localsโ identifier"LocT"
๐ง DEBUG INFORMATION/ABSTRACT CODE ๐ง
Option debug_info can be specified to the Compiler (see compile(3erl)) to have debug information, such as Erlang Abstract Format, stored in the debug_info chunk. Tools such as Debugger and Xref require the debug information to be included.
โ ๏ธ Warning: Source code can be reconstructed from the debug information. To prevent this, use encrypted debug information (see below).
The debug information can also be removed from BEAM files using strip/1, strip_files/1, and/or strip_release/1.
๐ช RECONSTRUCT SOURCE CODE ๐ช
The following example shows how to reconstruct Erlang source code from the debug information in a BEAM file Beam:
{ok,{_,[{abstract_code,{_,AC}}]}} = beam_lib:chunks(Beam,[abstract_code]).
io:fwrite("~s~n", [erl_prettypr:format(erl_syntax:form_list(AC))]).
๐ ENCRYPTED DEBUG INFORMATION ๐
The debug information can be encrypted to keep the source code secret, but still be able to use tools such as Debugger or Xref.
To use encrypted debug information, a key must be provided to the compiler and beam_lib. The key is specified as a string. It is recommended that the string contains at least 32 characters and that both upper and lower case letters as well as digits and special characters are used.
The default type (and currently the only type) of crypto algorithm is des3_cbc, three rounds of DES. The key string is scrambled using erlang:md5/1 to generate the keys used for des3_cbc.
๐ก Note: As far as we know by the time of writing, it is infeasible to break des3_cbc encryption without any knowledge of the key. Therefore, as long as the key is kept safe and is unguessable, the encrypted debug information should be safe from intruders.
The key can be provided in the following two ways:
- Use Compiler option
{debug_info_key,Key}, seecompile(3erl)and functioncrypto_key_fun/1to register a fun that returns the key wheneverbeam_libmust decrypt the debug information.- If no such fun is registered,
beam_libinstead searches for an.erlang.cryptfile, see the next section.
- If no such fun is registered,
- Store the key in a text file named
.erlang.crypt.- In this case, Compiler option
encrypt_debug_infocan be used, seecompile(3erl).
- In this case, Compiler option
๐๏ธ .ERLANG.CRYPT ๐๏ธ
beam_lib searches for .erlang.crypt in the current directory, then the user's home directory and then filename:basedir(user_config, "erlang"). If the file is found and contains a key, beam_lib implicitly creates a crypto key fun and registers it.
File .erlang.crypt is to contain a single list of tuples:
{debug_info, Mode, Module, Key}
Mode is the type of crypto algorithm; currently, the only allowed value is des3_cbc. Module is either an atom, in which case Key is only used for the module Module, or [], in which case Key is used for all modules. Key is the non-empty key string.
Key in the first tuple where both Mode and Module match is used.
The following is an example of an .erlang.crypt file that returns the same key for all modules:
[{debug_info, des3_cbc, [], "%>7}|pc/DM6Cga*68$Mw]L#&_Gejr]G^"}].
The following is a slightly more complicated example of an .erlang.crypt providing one key for module t and another key for all other modules:
[{debug_info, des3_cbc, t, "My KEY"},
{debug_info, des3_cbc, [], "%>7}|pc/DM6Cga*68$Mw]L#&_Gejr]G^"}].
๐ก Note: Do not use any of the keys in these examples. Use your own keys.
๐งฌ DATA TYPES ๐งฌ
Here's the type lore, bestie. These are literal definitions, so keep the shapes exactly as written. No remixing, no cap. ๐ซถ
๐ชฉ beam()
beam() = file:filename() | binary()
Each of the functions described below accept either the filename (as a string) or a binary containing the BEAM module.
๐งฉ chunkdata()
chunkdata() =
{chunkid(), dataB()} |
{abstract_code, abst_code()} |
{debug_info, debug_info()} |
{attributes, [attrib_entry()]} |
{compile_info, [compinfo_entry()]} |
{exports, [{atom(), arity()}]} |
{labeled_exports, [labeled_entry()]} |
{imports, [mfa()]} |
{indexed_imports,
[{index(), module(), Function :: atom(), arity()}]} |
{locals, [{atom(), arity()}]} |
{labeled_locals, [labeled_entry()]} |
{atoms, [{integer(), atom()}]}
The list of attributes is sorted on Attribute (in attrib_entry()) and each attribute name occurs once in the list. The attribute values occur in the same order as in the file. The lists of functions are also sorted.
๐ท๏ธ chunkid()
chunkid() = nonempty_string()
"Attr" | "CInf" | "Dbgi" | "ExpT" | "ImpT" | "LocT" | "AtU8"
๐งฑ dataB()
dataB() = binary()
๐ debug_info()
debug_info() =
{DbgiVersion :: atom(), Backend :: module(), Data :: term()} |
no_debug_info
The format stored in the debug_info chunk. To retrieve particular code representation from the backend, Backend:debug_info(Format, Module, Data, Opts) must be invoked. Format is an atom, such as erlang_v1 for the Erlang Abstract Format or core_v1 for Core Erlang. Module is the module represented by the beam file and Data is the value stored in the debug info chunk. Opts is any list of values supported by the Backend. Backend:debug_info/4 must return {ok, Code} or {error, Term}.
Developers must always invoke the debug_info/4 function and never rely on the Data stored in the debug_info chunk, as it is opaque and may change at any moment. no_debug_info means that chunk "Dbgi" is present, but empty.
๐งพ abst_code()
abst_code() =
{AbstVersion :: atom(), forms()} | no_abstract_code
It is not checked that the forms conform to the abstract format indicated by AbstVersion. no_abstract_code means that chunk "Abst" is present, but empty.
For modules compiled with OTP 20 onwards, the abst_code chunk is automatically computed from the debug_info chunk.
๐ forms()
forms() = [erl_parse:abstract_form() | erl_parse:form_info()]
๐งฎ compinfo_entry()
compinfo_entry() = {InfoKey :: atom(), term()}
๐ท๏ธ attrib_entry()
attrib_entry() =
{Attribute :: atom(), [AttributeValue :: term()]}
๐ซ labeled_entry()
labeled_entry() = {Function :: atom(), arity(), label()}
๐ข index()
index() = integer() >= 0
๐ท๏ธ label()
label() = integer()
๐งท chunkref()
chunkref() = chunkname() | chunkid()
๐งธ chunkname()
chunkname() =
abstract_code | debug_info | attributes | compile_info |
exports | labeled_exports | imports | indexed_imports |
locals | labeled_locals | atoms
๐ฅ chnk_rsn()
chnk_rsn() =
{unknown_chunk, file:filename(), atom()} |
{key_missing_or_invalid,
file:filename(),
abstract_code | debug_info} |
{missing_backend, file:filename(), module()} |
info_rsn()
๐ญ info_rsn()
info_rsn() =
{chunk_too_big,
file:filename(),
chunkid(),
ChunkSize :: integer() >= 0,
FileSize :: integer() >= 0} |
{invalid_beam_file,
file:filename(),
Position :: integer() >= 0} |
{invalid_chunk, file:filename(), chunkid()} |
{missing_chunk, file:filename(), chunkid()} |
{not_a_beam_file, file:filename()} |
{file_error, file:filename(), file:posix()}
๐ค EXPORTS ๐ค
Here come the actual functions. Every signature and type is kept literal, because we do not mess with API shapes. ๐
๐๏ธ all_chunks
all_chunks(File :: beam()) ->
{ok, beam_lib, [{chunkid(), dataB()}]} |
{error, beam_lib, info_rsn()}
Reads chunk data for all chunks.
๐ ๏ธ build_module
build_module(Chunks) -> {ok, Binary}
Types:
Chunks = [{chunkid(), dataB()}]
Binary = binary()
Builds a BEAM module (as a binary) from a list of chunks.
๐งฉ chunks/2
chunks(Beam, ChunkRefs) ->
{ok, {module(), [chunkdata()]}} |
{error, beam_lib, chnk_rsn()}
Types:
Beam = beam()
ChunkRefs = [chunkref()]
Reads chunk data for selected chunks references. The order of the returned list of chunk data is determined by the order of the list of chunks references.
๐งฉ chunks/3
chunks(Beam, ChunkRefs, Options) ->
{ok, {module(), [ChunkResult]}} |
{error, beam_lib, chnk_rsn()}
Types:
Beam = beam()
ChunkRefs = [chunkref()]
Options = [allow_missing_chunks]
ChunkResult =
chunkdata() | {ChunkRef :: chunkref(), missing_chunk}
Reads chunk data for selected chunks references. The order of the returned list of chunk data is determined by the order of the list of chunks references.
By default, if any requested chunk is missing in Beam, an error tuple is returned. However, if option allow_missing_chunks is specified, a result is returned even if chunks are missing. In the result list, any missing chunks are represented as {ChunkRef,missing_chunk}. Notice however that if chunk "Atom" is missing, that is considered a fatal error and the return value is an error tuple.
๐งน clear_crypto_key_fun
clear_crypto_key_fun() -> undefined | {ok, Result}
Types:
Result = undefined | term()
Unregisters the crypto key fun and terminates the process holding it, started by crypto_key_fun/1.
Returns either {ok, undefined} if no crypto key fun is registered, or {ok, Term}, where Term is the return value from CryptoKeyFun(clear), see crypto_key_fun/1.
โ๏ธ cmp
cmp(Beam1, Beam2) -> ok | {error, beam_lib, cmp_rsn()}
Types:
Beam1 = Beam2 = beam()
cmp_rsn() =
{modules_different, module(), module()} |
{chunks_different, chunkid()} |
different_chunks |
info_rsn()
Compares the contents of two BEAM files. If the module names are the same, and all chunks except for chunk "CInf" (the chunk containing the compilation information that is returned by Module:module_info(compile)) have the same contents in both files, ok is returned. Otherwise an error message is returned.
๐ cmp_dirs
cmp_dirs(Dir1, Dir2) ->
{Only1, Only2, Different} | {error, beam_lib, Reason}
Types:
okay so we're mid-cmp_dirs/2 โ picking up right where the types block left off, no interruption, we ride at dawn ๐ฆ
Dir1 = Dir2 = atom() | file:filename()
Only1 = Only2 = [file:filename()]
Different =
[{Filename1 :: file:filename(), Filename2 ::
file:filename()}]
Reason = {not_a_directory, term()} | info_rsn()
Compares the BEAM files in two directories ๐
Only files with extension .beam are compared โ everything else gets politely ignored, like your ex in the group chat. BEAM files that exist only in directory Dir1 (or only in Dir2) get dropped into Only1 (Only2). And the files that exist in both directories but are considered different by cmp/2? Those come back as pairs {Filename1, Filename2}, where Filename1 lives in Dir1 and Filename2 lives in Dir2. Two dirs, one vibe check. โจ
๐ crypto_key_fun(CryptoKeyFun) -> ok | {error, Reason}
Types:
CryptoKeyFun = crypto_fun()
Reason = badfun | exists | term()
crypto_fun() = fun((crypto_fun_arg()) -> term())
crypto_fun_arg() =
init | clear | {debug_info, mode(), module(), file:filename()}
mode() = des3_cbc
Registers a unary fun that gets called whenever beam_lib has to read a debug_info chunk that's been encrypted ๐ The fun doesn't just float around in the void โ it's held in a process that gets started by this very function. Main character energy for a fun, honestly.
Heads up bestie: if a fun is already registered when you try to register one, you get {error, exists} back. One fun, one process, no polyamory. ๐
The fun has to handle these arguments:
CryptoKeyFun(init) -> ok | {ok, NewCryptoKeyFun} | {error, Term}
Called when the fun is registered, in the process that holds the fun ๐ซถ This is where your crypto key fun can do whatever initialization it needs. If it returns {ok, NewCryptoKeyFun}, then NewCryptoKeyFun is what actually gets registered instead of CryptoKeyFun โ a little glow-up at the door. If it returns {error, Term}, the registration is aborted and crypto_key_fun/1 also returns {error, Term}, so the error travels right back to you, fr fr.
CryptoKeyFun({debug_info, Mode, Module, Filename}) -> Key
Called when the key is needed for module Module in the file named Filename ๐๏ธ Mode is the type of crypto algorithm โ and currently, the only possible value is des3_cbc. If no key is available, the call is to fail (raise an exception). No key, no entry, no exceptions to that rule. ๐ญ
CryptoKeyFun(clear) -> term()
Called before the fun is unregistered โ your cleanup era ๐งน Do any cleaning up you need here. The return value is not important, but it is passed back to the caller of clear_crypto_key_fun/0 as part of its return value, so it's not just vibing into the void. โจ
๐ธ diff_dirs(Dir1, Dir2) -> ok | {error, beam_lib, Reason}
Types:
Dir1 = Dir2 = atom() | file:filename()
Reason = {not_a_directory, term()} | info_rsn()
Compares the BEAM files in two directories just like cmp_dirs/2 โ same energy, different delivery ๐ But instead of handing you a tidy data structure, the names of files that exist in only one directory or are different get presented on standard output. It's giving "I'm not gonna text you back, I'm gonna post about it." ๐
๐ฆ format_error(Reason) -> io_lib:chars()
Types:
Reason = term()
For a specified error returned by any function in this module, this function hands you a descriptive string of the error in English ๐ซถ Like a translator for your error messages. But listen โ for file errors, function file:format_error(Posix) is the one you're supposed to call instead. Different department, different icon. โจ
๐ info(Beam) -> [InfoPair] | {error, beam_lib, info_rsn()}
Types:
Beam = beam()
InfoPair =
{file, Filename :: file:filename()} |
{binary, Binary :: binary()} |
{module, Module :: module()} |
{chunks,
[{ChunkId :: chunkid(),
Pos :: integer() >= 0,
Size :: integer() >= 0}]}
Returns a list containing some information about a BEAM file, as tuples of {Item, Info} ๐ Here's the breakdown:
{file, Filename}|{binary, Binary}โ the name (a string) of the BEAM file, or the binary that the information was extracted from. Either/or, depending on where you got your tea. ๐{module, Module}โ the name (an atom) of the module. Obviously. That's the whole point. ๐{chunks, [{ChunkId, Pos, Size}]}โ for each chunk: the identifier (a string), plus the position and size of the chunk data, in bytes. Every chunk gets its own little spotlight. ๐
๐
md5(Beam) -> {ok, {module(), MD5}} | {error, beam_lib, chnk_rsn()}
Types:
Beam = beam()
MD5 = binary()
Calculates an MD5 redundancy check for the code of the module ๐ฅ Note the fine print though: compilation date and other attributes are not included. Just the code. Nothing extra. Minimalist queen. โจ
๐ strip(Beam1) -> {ok, {module(), Beam2}} | {error, beam_lib, info_rsn()}
Types:
Beam1 = Beam2 = beam()
Removes all chunks from a BEAM file except those used by the loader ๐งน So in particular, the debug information (chunk debug_info and abstract_code) is removed. Gone. Not invited. Say bye to your debug info bestie, she's not coming to the function. ๐ญ
๐ strip(Beam1, AdditionalChunks) -> {ok, {module(), Beam2}} | {error, beam_lib, info_rsn()}
Types:
Beam1 = beam()
AdditionalChunks = [chunkid()]
Beam2 = beam()
Same vibe, but this time you get to keep the chunks used by the loader plus anything you named in AdditionalChunks โ those get a VIP pass ๐ซถ Everything else is still yeeted. And in particular, the debug information (chunk debug_info and abstract_code) is removed. Still. Always. ๐
๐ strip_files(Files) -> {ok, [{module(), Beam}]} | {error, beam_lib, info_rsn()}
Types:
Files = [beam()]
Beam = beam()
Removes all chunks except those used by the loader from BEAM files ๐ฅ And in particular โ you know the drill โ the debug information (chunk debug_info and abstract_code) is removed. The returned list contains one element for each specified filename, in the same order as in Files. Order is preserved, we're not chaotic in this house. โจ
๐ strip_files(Files, AdditionalChunks) -> {ok, [{module(), Beam}]} | {error, beam_lib, info_rsn()}
Types:
Files = [beam()]
AdditionalChunks = [chunkid()]
Beam = beam()
Removes all chunks except those used by the loader or mentioned in AdditionalChunks ๐ And in particular, the debug information (chunk debug_info and abstract_code) is removed. Same one-element-per-filename, same-order-as-Files deal as above. Consistency is the moment. ๐
โญ strip_release(Dir) -> {ok, [{module(), file:filename()}]} | {error, beam_lib, Reason}
Types:
Dir = atom() | file:filename()
Reason = {not_a_directory, term()} | info_rsn()
Removes all chunks except those used by the loader from the BEAM files of a whole release ๐ธ Dir is to be the installation root directory โ like, the actual root of the whole thing. For example, the current OTP release can be stripped with the call beam_lib:strip_release(code:root_dir()). Whole release, one glow-up. ๐ฅ
โญ strip_release(Dir, AdditionalChunks) -> {ok, [{module(), file:filename()}]} | {error, beam_lib, Reason}
Types:
Dir = atom() | file:filename()
AdditionalChunks = [chunkid()]
Reason = {not_a_directory, term()} | info_rsn()
Removes all chunks except those used by the loader or mentioned in AdditionalChunks ๐ Dir is to be the installation root directory, same as before. For example, the current OTP release can be stripped with the call beam_lib:strip_release(code:root_dir()). Yes, identical example, because it's literally the same call with an extra list. We keep the receipts. ๐งพ
๐ version(Beam) -> {ok, {module(), [Version :: term()]}} | {error, beam_lib, chnk_rsn()}
Types:
Beam = beam()
Returns the module version or versions โญ A version is defined by the module attribute -vsn(Vsn). If that attribute isn't specified, the version defaults to the checksum of the module. Notice that if version Vsn is not a list, it is made into one โ that is, {ok,{Module,[Vsn]}} is returned. And if there are many -vsn module attributes, the result is the concatenated list of versions. All the versions, all the time. ๐
Examples:
1> beam_lib:version(a). % -vsn(1).
{ok,{a,[1]}}
2> beam_lib:version(b). % -vsn([1]).
{ok,{b,[1]}}
3> beam_lib:version(c). % -vsn([1]). -vsn(2).
{ok,{c,[1,2]}}
4> beam_lib:version(d). % no -vsn attribute
{ok,{d,[275613208176997377698094100858909383631]}}
Look at case 4 โ no -vsn attribute so it just goes "here's a giant checksum, hope that's fine" ๐ญ iconic behavior honestly.
and that's the whole page bestie โ every last chunk, stripped and unstripped. this tea was brewed by Ericsson AB, poured from stdlib 4.3.1.3, and served on the beam_lib(3erl) menu. go forth and inspect your beams. periodt. ๐ โจ๐ฆ
๐ฆ 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