asn1

v5.4.2-rc0

asn1 Release Notes

This document describes the changes made to the asn1 application.

Asn1 5.4.2

Fixed Bugs and Malfunctions

Decoding a constrained BIT STRING using JER was broken.

Own Id: OTP-19681 Aux Id: PR-9949

NIFs and linked-in drivers are now loadable when running in an Erlang source tree on Windows.

Own Id: OTP-19686 Aux Id: PR-9969

Asn1 5.4.1

Fixed Bugs and Malfunctions

The ASN.1 compiler could generate code that would cause Dialyzer with the unmatched_returns option to emit warnings.

Own Id: OTP-19638 Aux Id: GH-9841, PR-9846

Asn1 5.4

Fixed Bugs and Malfunctions

The undec_rest option would be ignored in generated functions for exclusive decode. The option is now respected, meaning that the return value from such functions are now three-tuples instead of a two-tuples.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19290 Aux Id: PR-8798

Improvements and New Features

The license and copyright header has changed format to include an SPDX-License-Identifier. At the same time, most files have been updated to follow a uniform standard for license headers.

Own Id: OTP-19575 Aux Id: PR-9670

The ancient ASN.1 modules used in public_key has been replaced with more modern versions, but we have strived to keep the documented Erlang API for the public_key application compatible.

POTENTIAL INCOMPATIBILITY

Own Id: OTP-19612 Aux Id: PR-9774

Asn1 5.3.4.2

Fixed Bugs and Malfunctions

Decoding a constrained BIT STRING using JER was broken.

Own Id: OTP-19681 Aux Id: PR-9949

Asn1 5.3.4.1

Fixed Bugs and Malfunctions

The ASN.1 compiler could generate code that would cause Dialyzer with the unmatched_returns option to emit warnings.

Own Id: OTP-19638 Aux Id: GH-9841, PR-9846

Asn1 5.3.4

Fixed Bugs and Malfunctions

Negative REAL numbers greater than -1 would be incorrectly encoded (the minus sign would be lost).

Own Id: OTP-19567 Aux Id: ERIERL-1214, PR-9658

Asn1 5.3.3

Fixed Bugs and Malfunctions

The JER backend will now include the SIZE constraint in the type info for OCTET STRINGs, and a SIZE constraint with a range will now be included for BIT STRINGs. This does not change the actual encoding or decoding of JER, but can be useful for tools.

Own Id: OTP-19542 Aux Id: ERIERL-1204, PR-9588

Improvements and New Features

When using the JSON encoding rules, it is now possible to call the decode/2 function in the following way with data that has already been decoded by json:decode/1:

SomeModule:decode(Type, {json_decoded, Decoded}).

Own Id: OTP-19547 Aux Id: ERIERL-1206, PR-9611

Asn1 5.3.2

Fixed Bugs and Malfunctions

Multiple bugs in decoding of the REAL type has been eliminated. Also, the documentation for REAL has been updated to mention the special values 0, PLUS-INFINITY, and MINUS-INFINITY.

Own Id: OTP-19504 Aux Id: GH-9096, PR-9469

Asn1 5.3.1

Fixed Bugs and Malfunctions

Fixed a cosmetic but harmless issue with the ASN.1 compiler passing on the undec_rest option to the Erlang compiler.

Own Id: OTP-19218 Aux Id: GH-8779, PR-8781

Asn1 5.3

Fixed Bugs and Malfunctions

Multiple bugs has been eliminated in the specialized decode feature.

Own Id: OTP-18813 Aux Id: PR-7790

Improvements and New Features

Specs have been added to all asn1ct API functions.

Own Id: OTP-18804 Aux Id: PR-7738

The documentation has been migrated to use Markdown and ExDoc.

Own Id: OTP-18955 Aux Id: PR-8026

The jer (JSON Encoding Rules) for ASN.1 now use the new json module for encoding and decoding JSON. Thus, there is no longer any need for an external JSON library.

Own Id: OTP-19018 Aux Id: PR-8241

Asn1 5.2.2.1

Fixed Bugs and Malfunctions

The ASN.1 compiler could generate code that would cause Dialyzer with the unmatched_returns option to emit warnings.

Own Id: OTP-19638 Aux Id: GH-9841, PR-9846

Asn1 5.2.2

Fixed Bugs and Malfunctions

An ASN.1 module that contains named BIT STRING values would fail to compiled if both the BER and JER back-ends were enabled.

Own Id: OTP-19039 Aux Id: GH-8291, PR-8297

Asn1 5.2.1

Fixed Bugs and Malfunctions

Fix benign warning from gcc 11 about mismatching call to free().

Own Id: OTP-18844

Asn1 5.2

Fixed Bugs and Malfunctions

The ASN.1 compiler would ignore a constraint such as (SIZE (1..4), ...), causing incorrect behavior of the encoding and decoding function for the PER and UPER backends. Corrected to handle the constraint in the same way as (SIZE (1..4, ...)).

Own Id: OTP-18729 Aux Id: PR-7575

Improvements and New Features

The JER backend has been internally refactored in a way that is compatible for applications that use the documented API. However, for a group of ASN.1 modules that depend on each other (for example, S1AP-PDU-Descriptions, S1AP-Contents, and so on), all modules in the group must be recompiled if on of the group members is recompiled.

Own Id: OTP-18748 Aux Id: ERIERL-957, PR-7637

Asn1 5.1

Fixed Bugs and Malfunctions

The ASN.1 compiler used to reject correctly specified RELATIVE-OID values containing other RELATIVE-OID values. This is now corrected.

Own Id: OTP-18534 Aux Id: ERIERL-737, PR-7039

Improvements and New Features

Minor code improvements.

Own Id: OTP-18441

Handling of on_load modules during boot has been improved by adding an extra step in the boot order for embedded mode that runs all on_load handlers, instead of relying on explicit invocation of them, later, when the kernel supervision tree starts.

This is mostly a code improvement and OTP internal simplification to avoid future bugs and to simplify code maintenance.

Own Id: OTP-18447

Asn1 5.0.21.1

Fixed Bugs and Malfunctions

Fix benign warning from gcc 11 about mismatching call to free().

Own Id: OTP-18844

Asn1 5.0.21

Fixed Bugs and Malfunctions

For the per and uper ASN.1 encoding rules, encoding and decoding the SEQUENCE OF and SET OF constructs with 16384 items or more is now supported.

Own Id: OTP-18245 Aux Id: ERIERL-859

Asn1 5.0.20

Improvements and New Features

There is a new configure option, --enable-deterministic-build, which will apply the deterministic compiler option when building Erlang/OTP. The deterministic option has been improved to eliminate more sources of non-determinism in several applications.

Own Id: OTP-18165 Aux Id: PR-5965

Asn1 5.0.19

Fixed Bugs and Malfunctions

The atom maybe has been quoted in the source code.

Own Id: OTP-17980

Asn1 5.0.18.2

Fixed Bugs and Malfunctions

Fix benign warning from gcc 11 about mismatching call to free().

Own Id: OTP-18844

Asn1 5.0.18.1

Fixed Bugs and Malfunctions

For the per and uper ASN.1 encoding rules, encoding and decoding the SEQUENCE OF and SET OF constructs with 16384 items or more is now supported.

Own Id: OTP-18245 Aux Id: ERIERL-859

Asn1 5.0.18

Fixed Bugs and Malfunctions

Add support for the maps option in combination with the jer backend.

Own Id: OTP-17959 Aux Id: GH-5757

Asn1 5.0.17

Fixed Bugs and Malfunctions

A parameterized type with a SEQUENCE with extension ("...") made the compiler backend to crash. The previous fix for this in GH-4514 was not complete.

Own Id: OTP-17522 Aux Id: GH-4902

Asn1 5.0.16

Fixed Bugs and Malfunctions

Fixed a bug in the asn1 compiler that potentially could cause it to fail to open a file.

Own Id: OTP-17387 Aux Id: OTP-17123

Asn1 5.0.15.1

Fixed Bugs and Malfunctions

A parameterized type with a SEQUENCE with extension ("...") made the compiler backend to crash. The previous fix for this in GH-4514 was not complete.

Own Id: OTP-17522 Aux Id: GH-4902

Asn1 5.0.15

Fixed Bugs and Malfunctions

A parameterized type with a SEQUENCE with extension ("...") made the compiler backend to crash.

Own Id: OTP-17227 Aux Id: GH-4514

For JER encoding rules an INTEGER value outside the declared range is now reported as error during decode.

Own Id: OTP-17306 Aux Id: ERIERL-506

Improvements and New Features

For the JER encoding rules, the declared order of the fields in a SEQUENCE is now maintained in the resulting JSON object. Previously a map was used which caused an undefined order of the fields which was not friendly for debugging.

Own Id: OTP-17297 Aux Id: ERIERL-607

Asn1 5.0.14

Improvements and New Features

Changes in order to build on the Haiku operating system.

Thanks to Calvin Buckley

Own Id: OTP-16707 Aux Id: PR-2638

Asn1 5.0.13

Fixed Bugs and Malfunctions

Adhere to the ASN.1 specification for hstring & bstring lexical items. That is they may include white space.

Own Id: OTP-16490

Improvements and New Features

Refactored the internal handling of deprecated and removed functions.

Own Id: OTP-16469

Improve handling of ellipsis in a CHOICE

Own Id: OTP-16554 Aux Id: ERL-1189

Asn1 5.0.12

Improvements and New Features

Dialyzer warnings of type no_match are now suppressed in the generated files.

Own Id: OTP-16636 Aux Id: ERIERL-145

Asn1 5.0.11

Improvements and New Features

The compiler now has limited support for the JSON encoding rules (ITU-T X.697 ASN.1 encoding rules: Specification of JavaScript Object Notation Encoding Rules).

Own Id: OTP-16030

Asn1 5.0.10

Improvements and New Features

Fix 'DEFAULT' with 'OCTET STRING' and 'SEQUENCE OF CHOICE' with extensions.

Own Id: OTP-16542 Aux Id: PR-2159

Asn1 5.0.9

Fixed Bugs and Malfunctions

All incorrect (that is, all) uses of "can not" has been corrected to "cannot" in source code comments, documentation, examples, and so on.

Own Id: OTP-14282 Aux Id: PR-1891

Corrected problems with the following value definitions:

value of SEQUENCE OF CHOICE with extensions

value of CHOICE with extensions

DEFAULT used with OCTET STRING

Own Id: OTP-15697 Aux Id: PR-2159

Asn1 5.0.8

Fixed Bugs and Malfunctions

Handle erroneous length during decode (BER only) without crashing.

Own Id: OTP-15470 Aux Id: ERIERL-278

Asn1 5.0.7

Fixed Bugs and Malfunctions

A bug in ASN.1 BER decoding has been fixed. When decoding a recursively enclosed term the length was not propagated to that term decoding, so if the length of the enclosed term was longer than the enclosing that error was not detected.

A hard coded C stack limitation for decoding recursive ASN.1 terms has been introduced. This is currently set to 8 kWords giving a nesting depth of about 1000 levels. Deeper terms can not be decoded, which should not be much of a real world limitation.

Own Id: OTP-14440 Aux Id: ERIERL-220

Asn1 5.0.6

Improvements and New Features

Update to use the new string api instead of the old.

Own Id: OTP-15036

Asn1 5.0.5.2

Fixed Bugs and Malfunctions

Handle erroneous length during decode (BER only) without crashing.

Own Id: OTP-15470 Aux Id: ERIERL-278

Asn1 5.0.5.1

Known Bugs and Problems

A bug in ASN.1 BER decoding has been fixed. When decoding a recursively enclosed term the length was not propagated to that term decoding, so if the length of the enclosed term was longer than the enclosing that error was not detected

A hard coded C stack limitation for decoding recursive ASN.1 terms has been introduced. This is currently set to 8 kWords giving a nesting depth of about 1000 levels. Deeper terms can not be decoded, which should not be much of a real world limitation.

Own Id: OTP-14440 Aux Id: ERIERL-220

Asn1 5.0.5

Fixed Bugs and Malfunctions

Dialyzer suppression has been added for the generated ASN.1 helper function to_bitstring/1 that previously created irrelevant warnings.

Own Id: OTP-13882 Aux Id: ERIERL-144

Asn1 5.0.4

Fixed Bugs and Malfunctions

There was a issue with BER encoding and the undec_rest option in generated decoders. An exception could be thrown instead of returning an error tuple.

Own Id: OTP-14786 Aux Id: ERL-518

The asn1ct:test functions crashed on decoders generated with options no_ok_wrapper, undec_rest.

Own Id: OTP-14787 Aux Id: ERL-518

Asn1 5.0.3

Fixed Bugs and Malfunctions

Compiling an ASN.1 module using the option {n2n, EnumTypeName} when EnumTypeName contains a hyphen like for example Cause-Misc caused syntax errors when compiling the generated Erlang code. This is now corrected.

Own Id: OTP-14495 Aux Id: ERL-437

Asn1 5.0.2

Fixed Bugs and Malfunctions

Default values now work in extension for PER, so if you give the atom asn1_DEFAULT instead of a value it will become the default value.

Own Id: OTP-13011 Aux Id: ERIERL-60

Asn1 5.0.1

Fixed Bugs and Malfunctions

Fixed compilation error of generated code caused by a missing quotation of function names as part of an external call for encoding.

Own Id: OTP-14519 Aux Id: ERIERL-49

Asn1 5.0

Fixed Bugs and Malfunctions

Add compile option -compile(no_native) in modules with on_load directive which is not yet supported by HiPE.

Own Id: OTP-14316 Aux Id: PR-1390

Improvements and New Features

The error tuple returned from the encode and decode functions will now include the stack backtrace to make it easier to understand what went wrong.

Own Id: OTP-13961

The deprecated module asn1rt has been removed. The deprecated functions asn1ct:encode/3 and asn1ct:decode/3 have been removed. The undocumented function asn1ct:encode/2 has been removed.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-14146

The new 'maps' option changes the representation of the types SEQUENCE and SET to be maps (instead of records).

Own Id: OTP-14219

Asn1 4.0.4

Fixed Bugs and Malfunctions

Compiling multiple ASN.1 modules in the same directory with parallel make (make -j) should now be safe.

Own Id: OTP-13624

Asn1 4.0.3

Improvements and New Features

Internal changes

Own Id: OTP-13551

Asn1 4.0.2

Fixed Bugs and Malfunctions

When compiling to the PER format, the ASN.1 compiler would crash when attempting to compile an ASN.1 module with a constrained INTEGER with more than 65536 values and named values. (Thanks to Ingars for reporting this bug.)

Own Id: OTP-13257

The ASN.1 compiler will now emit Dialyzer suppressions for improper lists. Thus, there is no longer any need to use --Wno_improper_lists when analyzing modules generated by the ASN.1 compiler.

Own Id: OTP-13324

Asn1 4.0.1

Fixed Bugs and Malfunctions

Trying to encode an empty named BIT STRING in BER would fail with a function_clause exception. (Thanks to Svilen Ivanov for reporting this bug.)

Own Id: OTP-13149

Asn1 4.0

Fixed Bugs and Malfunctions

Many bugs have been eliminated in the ASN.1 compiler so that it can now successfully compile many more ASN.1 specifications. Error messages have also been improved.

Own Id: OTP-12395

Improvements and New Features

The documentation for asn1ct:test/1,2,3 and asn1ct:value/2 has been updated with information about the limitations of the functions.

Own Id: OTP-12765 Aux Id: seq12866, seq12867

Asn1 3.0.4

Fixed Bugs and Malfunctions

The ASN.1 compiler would crash if a SEQUENCE ended with a double set of ellipses (...).

Own Id: OTP-12546 Aux Id: seq12815

Asn1 3.0.3

Fixed Bugs and Malfunctions

When decoding BER, primitives with an indefinite length will be immediately rejected. (Thanks to Simon Cornish for reporting this bug.)

Own Id: OTP-12205

BER: A bug with compliance to X.680 (200811) s31.2.7 has been fixed. Basically, when TagDefault is AUTOMATIC then tags are IMPLICIT unless EXPLICIT is given.

Own Id: OTP-12318

Usage of the EXTERNAL 1994 variant type was broken.

Own Id: OTP-12326

Asn1 3.0.2

Fixed Bugs and Malfunctions

Several problems where the ASN.1 compiler would crash when attempting to compile correct specifications have been corrected.

Own Id: OTP-12125

Robustness when decoding incorrect BER messages has been improved.

Own Id: OTP-12145

Asn1 3.0.1

Fixed Bugs and Malfunctions

The ASN.1 compiler now generates code that don't trigger Dialyzer warnings. Along the way, a few minor bugs were fixed.

Own Id: OTP-11372 Aux Id: seq12397

Asn1 3.0

Fixed Bugs and Malfunctions

Subtyping an extensible ENUMERATED would cause an compilation error. (Thanks to Morten Nygaard Åsnes for reporting this bug.)

Own Id: OTP-11700

When specifying the value for an OCTET STRING in a specification, the ASN.1 standard clearly states that the value must be either a bstring or an hstring, but NOT a cstring. The ASN.1 compiler will now generate a compilation error if the value of an OCTET STRING is given as a character string.

That is, the following example is now illegal:

string OCTET STRING ::= "Now illegal"

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-11727

Application upgrade (appup) files are corrected for the following applications:

asn1, common_test, compiler, crypto, debugger, dialyzer, edoc, eldap, erl_docgen, et, eunit, gs, hipe, inets, observer, odbc, os_mon, otp_mibs, parsetools, percept, public_key, reltool, runtime_tools, ssh, syntax_tools, test_server, tools, typer, webtool, wx, xmerl

A new test utility for testing appup files is added to test_server. This is now used by most applications in OTP.

(Thanks to Tobias Schlager)

Own Id: OTP-11744

Improvements and New Features

By giving --enable-static-{nifs,drivers} to configure it is now possible to statically linking of nifs and drivers to the main Erlang VM binary. At the moment only the asn1 and crypto nifs of the Erlang/OTP nifs and drivers have been prepared to be statically linked. For more details see the Installation Guide in the System documentation.

Own Id: OTP-11258

Code generation for the per and uper backends has been somewhat improved.

Own Id: OTP-11573

The OCTET STRING and BIT STRING types now have a more natural mapping to Erlang types (binary and bitstring, respectively), which is more efficient and will avoid useless conversions between lists and binaries/bitstrings.

This is an incompatible change. To revert to the old mapping to support existing applications, use the legacy_erlang_types option.

Impact: There is a potential for better performance, as it is now possible to avoid conversions between lists and binaries both in the generated ASN.1 encode/decode code and in the application itself.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-11594

All functions in the asn1rt module, as well as asn1ct:decode/3 and asn1ct:encode/3, are now deprecated.

Own Id: OTP-11731

Generated .hrl files are now protected from being included more than once.

Own Id: OTP-11804

Asn1 2.0.4

Fixed Bugs and Malfunctions

The default value for a BIT STRING would not always be recognized, causing the encoding to be incorrect for the DER/PER/UPER encodings.

Own Id: OTP-11319

The ASN.1 application would fail to build if the .erlang file printed something to standard output.

Own Id: OTP-11360

An union of integer ranges in an INTEGER constraint could sometimes be interpreted as the intersection of the range.

Own Id: OTP-11411 Aux Id: seq12443

Extensible, multiple single value constraints (such as INTEGER (1|17, ...)) would be incorrectly encoded.

Own Id: OTP-11415

The ASN.1 compiler would fail to compile a constraint with values given for the extension part (such as INTEGER (1..10, ..., 11..20)).

Own Id: OTP-11504

Improvements and New Features

The new option 'no_ok_wrapper' generates M:encode/2 and M:decode/2 functions that don't wrap the return value in an {ok,...} tuple.

Own Id: OTP-11314

Asn1 2.0.3

Fixed Bugs and Malfunctions

Open types greater than 16383 bytes will now be correctly encoded and decoded.

Own Id: OTP-11262 Aux Id: seq12386, OTP-11223

Improvements and New Features

For the PER and UPER formats, code generation especially for encoding has been improved.

When encoding BIT STRINGs, values longer than the maximum size for the BIT STRING type would be truncated silently - they now cause an exception.

Open types greater than 16383 bytes will now be correctly encoded and decoded.

IMPORTANT NOTE: For ASN.1 specifications that depend on each other, such as the S1AP-* specifications, it is important to recompile all specifications (compiling some with this version of the compiler and some with an older version will not work).

Own Id: OTP-11300

Asn1 2.0.2

Fixed Bugs and Malfunctions

Fix some Makefile rules that didn't support silent rules. Thanks to Anthony Ramine.

Own Id: OTP-11111

PER/UPER: A semi-constrained INTEGER with a non-zero lower bound would be incorrectly decoded. This bug was introduced in R16.

PER/UPER: Given INTEGER (10..MAX, ...), attempting to decode any integer below 10 would cause the encoder to enter an infinite loop.

PER/UPER: For a type with an extensible SIZE constraint, sizes outside of the root range were incorrectly encoded.

Given a constraint such as (SIZE (5, ...)), encoding a size less than 5 would fail (PER/UPER). Similarly, for BER decoding would fail.

PER: The encoder did not align a known multiplier string (such as IA5String) of length 16 bits (exactly) to an octet boundary.

In rare circumstances, DEFAULT values for the UPER backend could be wrongly encoded.

Own Id: OTP-11134

UPER: The compiler would crash when compiling an ENUMERATED having more than 63 extended values.

PER/UPER: A SEQUENCE with more 64 extended values could not be decoded.

Own Id: OTP-11153

When decoding a SEQUENCE defined inline inside a an extension addition group, the record named generated by the decoding code would not match the name in the generated .hrl file.

Own Id: OTP-11154 Aux Id: seq12339

Improvements and New Features

Postscript files no longer needed for the generation of PDF files have been removed.

Own Id: OTP-11016

Asn1 2.0.1.2

Fixed Bugs and Malfunctions

When an object set is an actual parameter, the extension marker for the object set could get lost (which would cause the decoding of unknown values to fail).

Own Id: OTP-10995 Aux Id: seq12290

Asn1 2.0.1.1

Fixed Bugs and Malfunctions

The generated decoder for the 'per' and 'uper' backends did not correctly decode ENUMERATEDs with a single value.

The generated encoder for the 'per' and 'uper' backends generated an empty binary for a top-level type that did not need to be encoded (such as an ENUMERATED with a single value). The correct result should be a binary containing a 0 byte.

Own Id: OTP-10916 Aux Id: seq12270

Asn1 2.0.1

Fixed Bugs and Malfunctions

Fixed broken table constraints within a SET OF or SEQUENCE OF for the BER backend.

Own Id: OTP-10853 Aux Id: seq12245

Asn1 2.0

Fixed Bugs and Malfunctions

Encoding SEQUENCEs with multiple extension addition groups with optional values could fail (depending both on the specification and whether all values were provided).

Own Id: OTP-10664

Improvements and New Features

The options for the ASN.1 compiler has been drastically simplified. The backend is chosen by using ber, per, or uper. The options optimize, nif, and driver are no longer needed. The old options will still work, but will issue a warning.

Another change is that generated encode/2 function will always return a binary (some backends used to return an iolist).

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-10410 Aux Id: kunagi-254 [165]

The ASN.1 compiler generates faster decode functions for PER and UPER. Some minor improvements have also been made for PER/UPER encoding, and to the BER backend.

Own Id: OTP-10519 Aux Id: kunagi-322 [233]

The ASN.1 compiler will now always include necessary run-time functions in the generated Erlang modules (except for asn1rt_nif which is still needed). If the option 'inline' is used the ASN.1 compiler will generate a warning. But if '{inline,OutputFile}' is use, the ASN.1 compiler will refuse to compile the file. (Use a .set.asn file if you need to remove the output file.)

The 'BIT STRING' type will now be decoded as Erlang bitstrings by default. Use the new legacy_bit_string option to encode as lists of ones and zeroes. (The compact_bit_string option still works as before.)

Open types are now always returned as binaries (when there is no information allowing them to be decoded).

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-10588 Aux Id: kunagi-341 [252]

Asn1 1.8.1

Fixed Bugs and Malfunctions

ASN.1 decoders generated with the options -bber_bin +optimize +nif would decode open types with a size larger than 511 incorrectly. That bug could cause decoding by public_key to fail. The bug was in the NIF library asn1_erl_nif.so; therefore there is no need re-compile ASN.1 specifications that had the problem.

Own Id: OTP-10805 Aux Id: seq12244

Encoding SEQUENCEs with multiple extension addition groups with optional values could fail (depending both on the specification and whether all values were provided).

Own Id: OTP-10811 Aux Id: OTP-10664

Asn1 1.8

Fixed Bugs and Malfunctions

Encoding and decoding of integer ranges can now be done with an upper bound larger than the previous limit of 16^10. The new upper bound in per encoding and decodings for constrained whole numbers is 2^2040 (close to 16^508)

Own Id: OTP-10128

Per encoding/decoding now works correctly for single value subtyping of an integer type where a subtype is a predefined value. Previously a predefined value could cause a non-valid range-check in the generated Erlang code for per encoding/decoding due to a bug in the constraint checking.

Own Id: OTP-10139

Fix typo error in selected decode function (Thanks to Artem Teslenko)

Own Id: OTP-10152

Better error indication when detecting unexpected tags during decoding of BER encoded data.

Own Id: OTP-10186

asn1rt_check: Fix transform_to_EXTERNAL1990 for binary input (Thanks to Harald Welte)

Own Id: OTP-10233

Improvements and New Features

Add support for multiple ExtensionAdditionGroups

Own Id: OTP-10058

Add support for extensible enumeration types in n2n generated functions.

Own Id: OTP-10144

Asn1 1.7

Improvements and New Features

Some ASN.1 INTEGER type and SEQUENCE constructor variants previously not handled by the ASN.1 compiler are now correctly handled

Own Id: OTP-9688

An INTEGER with a value constraint where unions are used e.g. X1 ::= INTEGER (1..4 | 6 | 8 | 10 | 20) is not handled correctly. For PER the value is encoded in wrong number of bits.

Own Id: OTP-9946

Asn1 1.6.19

Improvements and New Features

The linked-in driver used for ber decode and per encode has been replaced with nifs. To enable the usage of nifs pass the nif option to erlc or asn1rt:compile when compiling. If you previously used the linked-in driver, you have to recompile your ASN1 modules with the current version of asn1 application as the linked-in driver modules have been removed.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-9419

A few of the heavy calculations which are done for encoding and decoding operations when dealing with SEQUENCE OF and DEFAULT in runtime have been moved to be done in compile time instead.

Own Id: OTP-9440

When compiling an ASN.1 ber module with the +nif option, the module will use a new nif for ber encoding, increasing performance by about 5%.

Own Id: OTP-9441

Tuple funs (a two-element tuple with a module name and a function) are now officially deprecated and will be removed in R16. Use 'fun M:F/A' instead. To make you aware that your system uses tuple funs, the very first time a tuple fun is applied, a warning will be sent to the error logger.

Own Id: OTP-9649

Asn1 1.6.18

Fixed Bugs and Malfunctions

Implement or fix -Werror option

If -Werror is enabled and there are warnings no output file is written. Also make sure that error/warning reporting is consistent. (Thanks to Tuncer Ayaz)

Own Id: OTP-9536

Asn1 1.6.17

Fixed Bugs and Malfunctions

Test cases which started failing when timer:tc was changed to not catch are corrected.

Own Id: OTP-9286

The bounds checking in the asn1_erl_driver when the length value of a TLV is a Long Definite Length is corrected. Thanks to Vance Shipley.

Own Id: OTP-9303

Asn1 1.6.16

Fixed Bugs and Malfunctions

asn1ct: Make formatting of errors and warnings consistent

Consistently format warning and error reports. Warning and error options from erlc now also work in asnc1ct. (thanks to Tuncer Ayaz)

Own Id: OTP-9062

Shut off some dialyzer warnings

Own Id: OTP-9063

Improvements and New Features

Crash in asn1ct_check, componentrelation_leadingattr fixed. (Thanks to Stephane Pamelard for finding the bug)

Own Id: OTP-9092

Asn1 1.6.15

Fixed Bugs and Malfunctions

The encoding of ExtensionAdditionGroup (for PER and UPER) is corrected.

Own Id: OTP-8866 Aux Id: OTP-8797, SEQ-11557

A race condition when several processes in parallel start to do encode/decode using the driver could cause an error log regarding crashing port owner process. This race is now eliminated.

Own Id: OTP-8948 Aux Id: seq11733

Asn1 1.6.14.1

Fixed Bugs and Malfunctions

Extension Addition Groups are now supported by the parser and in all backends.

Own Id: OTP-8598 Aux Id: seq-11557

Extension Addition Groups are now supported in nested types within a SEQUENCE and CHOICE as well (missed that in previous fix)

Own Id: OTP-8797 Aux Id: seq-11557

Improvements and New Features

Bug in UNALIGNED PER regarding encoding and decoding of constrained numbers with a valuerange > 1024. (Thanks to Vincent de Phily)

Own Id: OTP-8779

Minor corrections in the User Guide.

Own Id: OTP-8829

Asn1 1.6.14

Improvements and New Features

By default, the ASN.1 compiler is now silent in the absence of warnings or errors. The new 'verbose' option or the '-v' option for erlc can be given to show extra information (for instance, about the files that are generated). (Thanks to Tuncer Ayaz.)

Own Id: OTP-8565

Asn1 1.6.13

Fixed Bugs and Malfunctions

Harmless buffer overflow by one byte in asn1 and ram_file_drv.

Own Id: OTP-8451

Improvements and New Features

Cross compilation improvements and other build system improvements.

Most notable:

Lots of cross compilation improvements. The old cross compilation support was more or less non-existing as well as broken. Please, note that the cross compilation support should still be considered as experimental. Also note that old cross compilation configurations cannot be used without modifications. For more information on cross compiling Erlang/OTP see the $ERL_TOP/INSTALL-CROSS.md file.

Support for staged install using DESTDIR. The old broken INSTALL_PREFIX has also been fixed. For more information see the $ERL_TOP/INSTALL.md file.

Documentation of the release target of the top Makefile. For more information see the $ERL_TOP/INSTALL.md file.

make install now by default creates relative symbolic links instead of absolute ones. For more information see the $ERL_TOP/INSTALL.md file.

$ERL_TOP/configure --help=recursive now works and prints help for all applications with configure scripts.

Doing make install, or make release directly after make all no longer triggers miscellaneous rebuilds.

Existing bootstrap system is now used when doing make install, or make release without a preceding make all.

The crypto and ssl applications use the same runtime library path when dynamically linking against libssl.so and libcrypto.so. The runtime library search path has also been extended.

The configure scripts of erl_interface and odbc now search for thread libraries and thread library quirks the same way as ERTS do.

The configure script of the odbc application now also looks for odbc libraries in lib64 and lib/64 directories when building on a 64-bit system.

The config.h.in file in the erl_interface application is now automatically generated in instead of statically updated which reduces the risk of configure tests without any effect.

(Thanks to Henrik Riomar for suggestions and testing)

(Thanks to Winston Smith for the AVR32-Linux cross configuration and testing)

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-8323

Add support for prefixing macro names generated by the compiler

This is useful when multiple protocols that contains macros with identical names are included in a single module.

Add the missing record_name_prefix compiler option to the documentation.

Own Id: OTP-8453

Cleanups suggested by tidier and modernization of types and specs.

Own Id: OTP-8455

Support for EXTENSIBILITY IMPLIED and SET/SEQ OF NamedType is added.

Own Id: OTP-8463

Asn1 1.6.12

Improvements and New Features

The documentation is now built with open source tools (xsltproc and fop) that exists on most platforms. One visible change is that the frames are removed.

Own Id: OTP-8256

Asn1 1.6.11

Improvements and New Features

A new option {n2n,TypeName} can be used to enable generation of conversion functions from name to number and vice versa for selected ENUMERATION types. The option can be repeated many times in order to specify several types in the same file.
If the TypeName specified does not exists or is not an ENUMERATION type, the compilation will be terminated with an error code.
Below follows an example on how to use the option from the command line with erlc:
erlc -bper+"{n2n,'CauseMisc'}" +"{n2n,'CausePcl'}" MyModyle.asn

Own Id: OTP-8136 Aux Id: seq11347

Range checks added for BIT STRING with fixed SIZE constraint.

Own Id: OTP-7972 Aux Id: seq11280

Now support multiple-line comments in asn1-specs as specified in ASN1 X.680 (07/2002), section 11.6.4

Own Id: OTP-8043

Now parses and adds abstract syntax for PATTERN subtype constraint. No other action is taken on this type of constraint.

Own Id: OTP-8046

The ASN1 subtype constraint CONTAINING Type, CONTAINING Type ENCODED BY Value and ENCODED BY Value now is parsed. Abstract syntax is added but no further action in generated code is taken.

Own Id: OTP-8047

Asn1 1.6.10

Fixed Bugs and Malfunctions

A faulty receive case that catch-ed all messages in the initialization of the driver has been removed, the initialization has been restructured.

Own Id: OTP-7954 Aux Id: seq11220

Improvements and New Features

The anonymous part of the decode that splits the ASN1 TLV into Tag Value tuples has been optimized.

Own Id: OTP-7953

Asn1 1.6.9

Fixed Bugs and Malfunctions

Error that caused crash when drivers were loaded is now corrected. Parallel driver for asn1 now enabled.

Own Id: OTP-7904 Aux Id: seq11220

Improvements and New Features

Optimized code for ENUMERATION type in encoder/decoder.

Own Id: OTP-7909

Asn1 1.6.8.1

Fixed Bugs and Malfunctions

Removed parallel-driver functionality due to failure when loading the driver.

Own Id: OTP-7900 Aux Id: seq11220

Improvements and New Features

Generated code now uses guards that is not obsolete, e.g. is_integer/1 instead of integer/1.

Own Id: OTP-7910

Asn1 1.6.8

Fixed Bugs and Malfunctions

A BIT STRING with a size constraint that has a single value and an extension as in BIT STRING (SIZE (16,...)) was erroneous encoded/decoded. This is now corrected and follows X.691 Section 15.6.

Own Id: OTP-7876 Aux Id: seq11220

Asn1 1.6.7

Improvements and New Features

Now asn1 starts multiple drivers to enable simultaneous encode/decode in different processes for the asn1-backends using linked-in driver.

Own Id: OTP-7801

Asn1 1.6.6

Fixed Bugs and Malfunctions

Decode of an open_type when the value was empty tagged type encoded with indefinite length failed. This is now corrected.

Own Id: OTP-7759 Aux Id: seq11166

Encode of BIT STRING with size of exact length, on compact_bit_string format in UNALIGNED PER failed when value had the right size, i.e. no padding needed.

Own Id: OTP-7763 Aux Id: seq11182

Asn1 1.6.5

Fixed Bugs and Malfunctions

For a BIT STRING with SIZE constraint higher than 255 compiled with [per_bin,optimize, compact_bit_string] an improper io-list was created and sent to the c-driver for complete encoding. This error has been resolved.

Own Id: OTP-7734 Aux Id: seq11170

Asn1 1.6.4

Fixed Bugs and Malfunctions

A a SEQUENCE OF with a type that is a CHOICE with ellipses occurred falsely a compile error. The error causing that is now removed.

Own Id: OTP-7708 Aux Id: seq11136

Asn1 1.6.3

Fixed Bugs and Malfunctions

constrained number with a value-range greater than 512 now has the proper interpretation of the values that causes shift to the next number of units (bits), According to limit condition 2^m < "range" =< 2^(m + 1) then the number of bits are m + 1.

Own Id: OTP-7681 Aux Id: seq11114

Improvements and New Features

Can now handle default values of simple types that is provided on its own format, i.e. not just as asn1_DEFAULT.

Own Id: OTP-7678 Aux Id: seq11114

Asn1 1.6.2

Fixed Bugs and Malfunctions

comparison of two value definitions failed due to new module name field in valuedef record. It is now corrected.

Own Id: OTP-7608

Asn1 1.6.1

Fixed Bugs and Malfunctions

Bug regarding propagation of parameters of parameterized type fixed.

Own Id: OTP-7174 Aux Id: seq10864

A bug, related to instantiation of a parameterized type with a type definition in the parameter-list, has been removed. The definition of the parameter type was in another module than the instance definition causing limited module info.

Own Id: OTP-7299 Aux Id: seq10864

Removed hard-coded name that may cause name collision.

Own Id: OTP-7322 Aux Id: seq10864

Object set of a class with id with properties UNIQUE OPTIONAL and the id field is lacking in the object is for now treated as a object without a unique identifier, i.e. no table is generated for this object.

Own Id: OTP-7332 Aux Id: seq10864

Compiler crashed when failed to handle a OID as ValueFromObject.

Own Id: OTP-7476 Aux Id: seq10999

A corrupted encoding may cause a loop when a buffer of at least two bytes of zero matches tag and length of a SET component. This behavior occurred only with decoder generated with ber or ber_bin options. Now a control breaks the loop.

Own Id: OTP-7533

Encode of BIT STRING longer than 255 bits with a SIZE(integer()) constraint caused a crash when spec was compiled with per_bin, optimize options.

Own Id: OTP-7602 Aux Id: seq11079

Improvements and New Features

Now supports REAL type of base 2 and 10

Own Id: OTP-7166 Aux Id: seq10864

By the asn1 compiler option {record_name_prefix Name} a prefix is chosen to the name of the record generated in the .hrl and used in the generated .erl files.

Own Id: OTP-7204 Aux Id: seq10853

The TypeFromObject production now covered

Own Id: OTP-7295 Aux Id: seq10468

Extended support for ObjectSetFromObjects. Production occurred as a part of the RootElementSetSpec of the ObjectSetSpec. Added also support for Exclusion of Element in ObjectSetSpec.

Own Id: OTP-7306 Aux Id: seq10864

Now implements RELATIVE-OID

Own Id: OTP-7334 Aux Id: seq10864

Asn1 1.6

Fixed Bugs and Malfunctions

Now is ordering, according to the canonical order, of components in a SET added. Canonical order is described in X.691 9.2 and X.680 8.6

Own Id: OTP-7375 Aux Id: unaligned PER

The precedence rules for extended constraints have been misinterpreted. The rule says for instance that if there are more than one constraint on a type that have extension-mark, only the last of the extension-marks would be kept. This affects the encoding of PER and is now corrected.

Own Id: OTP-7400 Aux Id: OTP-7335

A constrained number with a single-value constraint that is extensible was falsely encoded/decoded in aligned/unaligned PER. This is now corrected.

Own Id: OTP-7403

Improvements and New Features

The ASN.1 compiler has got a new backend supporting PER UNALIGNED. Previously it was only support for PER ALIGNED.

Own Id: OTP-7335

Now the asn1-compiler handles unions and intersections of PermittedAlphabet constraints.

Own Id: OTP-7374 Aux Id: unaligned PER

With the undocumented option no_final_padding the whole encoded message is not padded to a border of a byte. Thus the returned encoded message is a bitstring.

Own Id: OTP-7407

Asn1 1.5.2

Fixed Bugs and Malfunctions

When duplicates of object fields were removed only one table access function for each unique identifier value was generated. This can occur when several object sets are merged by use of ObjectSetFromObjects.

Own Id: OTP-7263 Aux Id: seq10864

DER: For some complex types and components with reference to type in several steps the default value check function was not generated. This is now fixed.

Own Id: OTP-7268 Aux Id: seq10684

Now is the tag in a tagged type as parameter propagated to the instance.

Own Id: OTP-7273 Aux Id: seq10864

Improvements and New Features

Added type T61String that is similar to TeletexString

Own Id: OTP-7264 Aux Id: seq10864

Asn1 1.5.1

Fixed Bugs and Malfunctions

A bug related to renaming of types has been fixed.This occurred using the .set.asn functionality.

Own Id: OTP-7149 Aux Id: seq10853

syntax error in ASN1 value now correctly shown

Own Id: OTP-7154 Aux Id: seq10864

Now a COMPONENTS OF construct in a parameterized type is expanded correctly

Own Id: OTP-7155 Aux Id: seq10864

Now the asn1-compiler also handles empty SEQUENCE DEFAULT values as {}.

Own Id: OTP-7169 Aux Id: seq10864

Now SelectionType gets the tag of the selected type.

Own Id: OTP-7171 Aux Id: seq10864

Correction of generated code for decode of an open type in a SEQUECNE OF/ SET OF

Own Id: OTP-7193 Aux Id: seq10875

Improvements and New Features

Misc improvements and bug corrections regarding default values.

Own Id: OTP-7199 Aux Id: seq10864

Asn1 1.5

Improvements and New Features

Now generating records in .hrl file for instances of parameterized SEQUENCE or SET.

Own Id: OTP-6835

Optimization using bitstr in encode/decode functions. Active with [per_bin, optimize] options.

* POTENTIAL INCOMPATIBILITY *

Own Id: OTP-6882

Asn1 1.4.6

Fixed Bugs and Malfunctions

Parsing and encoding/decoding of type constrained with SIZE with extension is now recovered.

Own Id: OTP-6763

inline failed because trying to use a removed module.

Own Id: OTP-6769

Fixed problem with a reference to a type from an object. The failure was caused bye change of type name when using inline option.

Own Id: OTP-6770

Handling of decode pattern for exclusive decode was false in the case when an un-decoded component had more than one following elements that should be decoded.

Own Id: OTP-6786

Improvements and New Features

Now the asn1-compiler supports two root lists in SEQUENCE and SET according to alternative three in ComponentTypeLists (X.680 07/2002 section 24.1), i.e. with an extension list between two ellipses.

Own Id: OTP-5067 Aux Id: seq8452

Asn1 1.4.5

Fixed Bugs and Malfunctions

Merging modules by inline earlier disabled the driver (used in modules generated with [optimized]/[optimized,driver] options). Now this is repaired.

Own Id: OTP-6601

Checking phase now aware of which module an INSTANCE OF is declared in.

Own Id: OTP-6702

Improvements and New Features

The compiler now handle all forms of ObjectSetSpec according to ITU-T recommendation X.681 (ISO/IEC 8824-2:2002).

Own Id: OTP-6698

Enhanced support of referencing object sets by ObjectSetFromObjects.

Own Id: OTP-6707

Support for parameterized object in an object set.

Own Id: OTP-6717

Introduction

The asn1 application provides the following:

An ASN.1 compiler for Erlang, which generates encode and decode functions to be used by Erlang programs sending and receiving ASN.1-specified data.

Runtime functions used by the generated code.

Support for the following encoding rules:

Basic Encoding Rules (BER)

Distinguished Encoding Rules (DER), a specialized form of BER that is used in security-conscious applications

Packed Encoding Rules (PER), both the aligned and unaligned variant

JSON Encoding Rules (JER)

Scope

This application covers all features of ASN.1 up to the 1997 edition of the specification. In the 2002 edition, new features were introduced. The following features of the 2002 edition are fully or partly supported:

Decimal notation (for example, "1.5e3) for REAL values. The NR1, NR2, and NR3 formats as explained in ISO 6093 are supported.

The RELATIVE-OID type for relative object identifiers is fully supported.

The subtype constraint (CONTAINING/ENCODED BY) to constrain the content of an octet string or a bit string is parsed when compiling, but no further action is taken. This constraint is not a PER-visible constraint.

The subtype constraint by regular expressions (PATTERN) for character string types is parsed when compiling, but no further action is taken. This constraint is not a PER-visible constraint.

Multiple-line comments as in C, /* ... */, are supported.

Prerequisites

It is assumed that the reader is familiar with the Erlang programming language, concepts of OTP, and is familiar with the ASN.1 notation. The ASN.1 notation is documented in the standard definition X.680, which is the primary text. It can also be helpful, but not necessary, to read the standard definitions X.681, X.682, X.683, X.690, and X.691.

A good book explaining those reference texts is Dubuisson: ASN.1 - Communication Between Heterogeneous Systems, is free to download at http://www.oss.com/asn1/dubuisson.html.

ASN.1

Introduction

ASN.1 is a formal language for describing data structures to be exchanged between distributed computer systems. The purpose of ASN.1 is to have a platform and programming language independent notation to express types using a standardized set of rules for the transformation of values of a defined type into a stream of bytes. This stream of bytes can then be sent on any type of communication channel. This way, two applications written in different programming languages running on different computers, and with different internal representation of data, can exchange instances of structured data types.

Getting Started

Example

The following example demonstrates the basic functionality used to run the Erlang ASN.1 compiler.

Create a file named People.asn containing the following:

People DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
  Person ::= SEQUENCE {
    name PrintableString,
    location INTEGER {home(0),field(1),roving(2)},
    age INTEGER OPTIONAL
  }
END

This file must be compiled before it can be used. The ASN.1 compiler checks that the syntax is correct and that the text represents proper ASN.1 code before generating an abstract syntax tree. The code generator then uses the abstract syntax tree to generate code.

The generated Erlang files are placed in the current directory or in the directory specified with option {outdir,Dir}.

The compiler can be called from the Erlang shell like this:

1> asn1ct:compile("People", [ber]).
ok

Option verbose can be added to get information about the generated files:

2> asn1ct:compile("People", [ber,verbose]).
Erlang ASN.1 compiling "People.asn"
--{generated,"People.asn1db"}--
--{generated,"People.hrl"}--
--{generated,"People.erl"}--
ok

ASN.1 module People is now accepted and the abstract syntax tree is saved in file People.asn1db. The generated Erlang code is compiled using the Erlang compiler and loaded into the Erlang runtime system. There is now an API for encode/2 and decode/2 in module People, which is called like this:

'People':encode(<Type name>, <Value>)

or:

'People':decode(<Type name>, <Value>)

Assume that there is a network application that receives instances of the ASN.1 defined type Person, modifies, and sends them back again:

receive
   {Port,{data,Bytes}} ->
       case 'People':decode('Person',Bytes) of
           {ok,P} ->
               {ok,Answer} = 'People':encode('Person',mk_answer(P)),
               Port ! {self(),{command,Answer}};
           {error,Reason} ->
               exit({error,Reason})
       end
    end,

In this example, a series of bytes is received from an external source and the bytes are then decoded into a valid Erlang term. This was achieved with the call 'People':decode('Person',Bytes), which returned an Erlang value of the ASN.1 type Person. Then an answer was constructed and encoded using 'People':encode('Person',Answer), which takes an instance of a defined ASN.1 type and transforms it to a binary according to the BER or PER encoding rules.

The encoder and decoder can also be run from the shell:

2> Rockstar = {'Person',"Some Name",roving,50}.
{'Person',"Some Name",roving,50}
3> {ok,Bin} = 'People':encode('Person',Rockstar).
{ok,<<243,17,19,9,83,111,109,101,32,78,97,109,101,2,1,2,
      2,1,50>>}
4> {ok,Person} = 'People':decode('Person',Bin).
{ok,{'Person',"Some Name",roving,50}}

Module Dependencies

It is common that ASN.1 modules import defined types, values, and other entities from another ASN.1 module.

Earlier versions of the ASN.1 compiler required that modules that were imported from had to be compiled before the module that imported. This caused problems when ASN.1 modules had circular dependencies.

Referenced modules are now parsed when the compiler finds an entity that is imported. No code is generated for the referenced module. However, the compiled modules rely on that the referenced modules are also compiled.

ASN.1 Application User Interface

The ASN.1 application provides the following two separate user interfaces:

The module asn1ct, which provides the compile-time functions (including the compiler)

The module asn1rt_nif, which provides the runtime functions for the ASN.1 decoder for the BER back end

The reason for this division of the interfaces into compile-time and runtime is that only runtime modules (asn1rt_nif) need to be loaded in an embedded system.

Compile-Time Functions

The ASN.1 compiler can be started directly from the command line by the erlc program. This is convenient when compiling many ASN.1 files from the command line or when using Makefiles. Here some examples showing of how erlc can compile ASN.1 modules:

erlc Person.asn
erlc -bper Person.asn
erlc -bber ../Example.asn
erlc -o ../asnfiles -I ../asnfiles -I /usr/local/standards/asn1 Person.asn

Useful options for the ASN.1 compiler:

-b[ber | per | uper | jer] - Choice of encoding rules. If omitted, ber is the default.

-o OutDirectory - Where to put the generated files. Default is the current directory.

-I IncludeDir - Where to search for .asn1db files and ASN.1 source specs to resolve references to other modules. This option can be repeated many times if there are several places to search in. The compiler searches the current directory first.

+der - DER encoding rule. Only when using option -bber.

+jer - Functions jer_encode/2 and jer_decode/2 for JSON encoding rules are generated together with functions for ber or per. Only to be used when the main encoding option is -bber, -bper or -buper.

+maps - Use maps instead of records to represent the SEQUENCE and SET types. No .hrl files will be generated. See the section Map representation for SEQUENCE and SET for more information.

+asn1config - This functionality works together with option ber. It enables the specialized decodes, see section Specialized Decode.

+undec_rest - A buffer that holds a message being decoded can also have trailing bytes. If those trailing bytes are important, they can be returned along with the decoded value by compiling the ASN.1 specification with option +undec_rest. The return value from the decoder is {ok,Value,Rest} where Rest is a binary containing the trailing bytes.

+'Any Erlc Option' - Any option can be added to the Erlang compiler when compiling the generated Erlang files. Any option unrecognized by the ASN.1 compiler is passed to the Erlang compiler.

For a complete description of erlc, see ERTS Reference Manual.

The compiler and other compile-time functions can also be started from the Erlang shell. Here follows a brief description of the primary functions. For a complete description of each function, see module asn1ct in the ASN.1 Reference Manual.

The compiler is started by asn1ct:compile/1 with default options, or asn1ct:compile/2 if explicit options are given.

Example:

asn1ct:compile("H323-MESSAGES").

This is equivalent to:

asn1ct:compile("H323-MESSAGES", [ber]).

If PER encoding is wanted:

asn1ct:compile("H323-MESSAGES", [per]).

The generic encode and decode functions can be called as follows:

'H323-MESSAGES':encode('SomeChoiceType', {call,<<"octetstring">>}).
'H323-MESSAGES':decode('SomeChoiceType', Bytes).

Runtime Functions

When an ASN.1 specification is compiled with option ber, the asn1rt_nif module and the NIF library in asn1/priv_dir are needed at runtime.

By calling function info/0 in a generated module, you get information about which compiler options were used.

Special Decode Functionality for JSON Encoding Rules (JER)

When using the JSON encoding rules, it is possible to call the decode/2 function in the following way with data that has already been decoded by json:decode/1:

SomeModule:decode(Type, {json_decoded, Decoded}).

Example:

1> asn1ct:compile("People", [jer]).
ok
2> Rockstar = {'Person',"Vince Eclipse",roving,50}.
{'Person',"Vince Eclipse",roving,50}
3> {ok,Bin} = 'People':encode('Person', Rockstar).
{ok,<<"{\"name\":\"Vince Eclipse\",\"location\":2,\"age\":50}">>}
4> 'People':decode('Person', Bin).
{ok,{'Person',"Vince Eclipse",roving,50}}
5> 'People':decode('Person', {json_decoded,json:decode(Bin)}).
{ok,{'Person',"Vince Eclipse",roving,50}}

Errors

Errors detected at compile-time are displayed on the screen together with line numbers indicating where in the source file the respective error was detected. If no errors are found, an Erlang ASN.1 module is created.

The runtime encoders and decoders execute within a catch and return {ok, Data} or {error, {asn1, Description}} where Description is an Erlang term describing the error.

Currently, Description looks like this: {ErrorDescription, StackTrace}. Applications should not depend on the exact contents of Description as it could change in the future.

Multi-File Compilation

There are various reasons for using multi-file compilation:

To choose the name for the generated module, for example, because you need to compile the same specs for different encoding rules.

You want only one resulting module.

Specify which ASN.1 specs to compile in a module with extension .set.asn. Choose a module name and provide the names of the ASN.1 specs. For example, if you have the specs File1.asn, File2.asn, and File3.asn, your module MyModule.set.asn looks as follows:

File1.asn
File2.asn
File3.asn

If you compile with the following, the result is one merged module MyModule.erl with the generated code from the three ASN.1 specs:

% erlc MyModule.set.asn

Note about tags

Tags used to be important for all users of ASN.1, because it was necessary to to manually add tags to certain constructs in order for the ASN.1 specification to be valid. Example of an old-style specification:

Tags DEFINITIONS ::=
BEGIN
  Afters ::= CHOICE { cheese [0] IA5String,
                      dessert [1] IA5String }
END

Without the tags (the numbers in square brackets) the ASN.1 compiler refused to compile the file.

In 1994 the global tagging mode AUTOMATIC TAGS was introduced. By putting AUTOMATIC TAGS in the module header, the ASN.1 compiler automatically adds tags when needed. The following is the same specification in AUTOMATIC TAGS mode:

Tags DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
  Afters ::= CHOICE { cheese IA5String,
                      dessert IA5String }
END

ASN.1 Types

This section describes the ASN.1 types including their functionality, purpose, and how values are assigned in Erlang.

ASN.1 has both primitive and constructed types:

Primitive Types | Constructed Types
BOOLEAN | SEQUENCE
INTEGER | SET
REAL | CHOICE
NULL | SET OF and SEQUENCE OF
ENUMERATED | ANY
BIT STRING | ANY DEFINED BY
OCTET STRING | EXTERNAL
Character Strings | EMBEDDED PDV
OBJECT IDENTIFIER | CHARACTER STRING
Object Descriptor |
TIME Types |

Table: Supported ASN.1 Types

Note

The values of each ASN.1 type have their own representation in Erlang, as described in the following sections. Users must provide these values for encoding according to the representation, as shown in the following example:

Operational ::= BOOLEAN --ASN.1 definition

In Erlang code it can look as follows:

Val = true,
{ok,Bytes} = MyModule:encode('Operational', Val),

BOOLEAN

Booleans in ASN.1 express values that can be either TRUE or FALSE. The meanings assigned to TRUE and FALSE are outside the scope of this text.

In ASN.1 it is possible to have:

Operational ::= BOOLEAN

Assigning a value to type Operational in Erlang is possible by using the following Erlang code:

Myvar1 = true,

Thus, in Erlang the atoms true and false are used to encode a boolean value.

INTEGER

An ASN.1 INTEGER is represented by an integer in Erlang.

The concept of subtyping can be applied to integers and to other ASN.1 types. The details of subtyping are not explained here; for more information, see X.680. Various syntaxes are allowed when defining a type as an integer:

T1 ::= INTEGER
T2 ::= INTEGER (-2..7)
T3 ::= INTEGER (0..MAX)
T4 ::= INTEGER (0<..MAX)
T5 ::= INTEGER (MIN<..-99)
T6 ::= INTEGER {red(0),blue(1),white(2)}

The Erlang representation of an ASN.1 INTEGER is an integer or an atom if a Named Number List (see T6 in the previous list) is specified.

The following is an example of Erlang code that assigns values for the types in the previous list:

T1value = 0,
T2value = 6,
T6value1 = blue,
T6value2 = 0,
T6value3 = white

These Erlang variables are now bound to valid instances of ASN.1 defined types. This style of value can be passed directly to the encoder for transformation into a series of bytes.

The decoder returns an atom if the value corresponds to a symbol in the Named Number List.

REAL

The following ASN.1 type is used for real numbers:

R1 ::= REAL

It is assigned a value in Erlang as follows:

R1value1 = "2.14",
R1value2 = {256,10,-2}

In the last line, notice that the tuple {256,10,-2} is the real number 2.56 in a special notation, which encodes faster than simply stating the number as "2.56". The arity three tuple is {Mantissa,Base,Exponent}, that is, Mantissa * Base^Exponent.

The following special values are also recognized:

R1value3 = 0,
R1value4 = 'PLUS-INFINITY',
R1value5 = 'MINUS-INFINITY'

NULL

The type NULL is suitable where supply and recognition of a value is important but the actual value is not.

Notype ::= NULL

This type is assigned in Erlang as follows:

N1 = 'NULL',

The actual value is the quoted atom 'NULL'.

ENUMERATED

The type ENUMERATED can be used when the value you want to describe can only take one of a set of predefined values. Example:

DaysOfTheWeek ::= ENUMERATED {
    sunday(1),monday(2),tuesday(3),
    wednesday(4),thursday(5),friday(6),saturday(7) }

For example, to assign a weekday value in Erlang, use the same atom as in the Enumerations of the type definition:

Day1 = saturday,

The enumerated type is similar to an integer type, when defined with a set of predefined values. The difference is that an enumerated type can only have specified values, whereas an integer can have any value.

BIT STRING

The type BIT STRING can be used to model information that is made up of arbitrary length series of bits. It is intended to be used for selection of flags, not for binary files.

In ASN.1, BIT STRING definitions can look as follows:

Bits1 ::= BIT STRING
Bits2 ::= BIT STRING {foo(0),bar(1),gnu(2),gnome(3),punk(14)}

The following two notations are available for representation of BIT STRING values in Erlang and as input to the encode functions:

A bitstring. By default, a BIT STRING with no symbolic names is decoded to an Erlang bitstring.

A list of atoms corresponding to atoms in the NamedBitList in the BIT STRING definition. A BIT STRING with symbolic names is always decoded to the format shown in the following example:

Bits1Val1 = <<0:1,1:1,0:1,1:1,1:1>>,
Bits2Val1 = [gnu,punk],
Bits2Val2 = <<2#1110:4>>,
Bits2Val3 = [bar,gnu,gnome],

Bits2Val2 and Bits2Val3 denote the same value.

Bits2Val1 is assigned symbolic values. The assignment means that the bits corresponding to gnu and punk, that is, bits 2 and 14 are set to 1, and the rest are set to 0. The symbolic values are shown as a list of values. If a named value, which is not specified in the type definition, is shown, a runtime error occurs.

BIT STRINGs can also be subtyped with, for example, a SIZE specification:

Bits3 ::= BIT STRING (SIZE(0..31))

This means that no bit higher than 31 can be set.

Deprecated Representations for BIT STRING

In addition to the representations described earlier, the following deprecated representations are available if the specification has been compiled with option legacy_erlang_types:

Aa a list of binary digits (0 or 1). This format is accepted as input to the encode functions, and a BIT STRING is decoded to this format if option legacy_bit_string is given.

As {Unused,Binary} where Unused denotes how many trailing zero-bits 0-7 that are unused in the least significant byte in Binary. This format is accepted as input to the encode functions, and a BIT STRING is decoded to this format if compact_bit_string has been given.

As a hexadecimal number (or an integer). Avoid this as it is easy to misinterpret a BIT STRING value in this format.

OCTET STRING

OCTET STRING is the simplest of all ASN.1 types. OCTET STRING only moves or transfers, for example, binary files or other unstructured information complying with two rules: the bytes consist of octets and encoding is not required.

It is possible to have the following ASN.1 type definitions:

O1 ::= OCTET STRING
O2 ::= OCTET STRING (SIZE(28))

With the following example assignments in Erlang:

O1Val = <<17,13,19,20,0,0,255,254>>,
O2Val = <<"must be exactly 28 chars....">>,

By default, an OCTET STRING is always represented as an Erlang binary. If the specification has been compiled with option legacy_erlang_types, the encode functions accept both lists and binaries, and the decode functions decode an OCTET STRING to a list.

Character Strings

ASN.1 supports a wide variety of character sets. The main difference between an OCTET STRING and a character string is that the OCTET STRING has no imposed semantics on the bytes delivered.

However, when using, for example, IA5String (which closely resembles ASCII), byte 65 (in decimal notation) means character 'A'.

For example, if a defined type is to be a VideotexString and an octet is received with the unsigned integer value X, the octet is to be interpreted as specified in standard ITU-T T.100, T.101.

The ASN.1 compiler does not determine the correct interpretation of each BER string octet value with different character strings. The application is responsible for interpretation of octets. Therefore, from the BER string point of view, octets are very similar to character strings and are compiled in the same way.

When PER is used, there is a significant difference in the encoding scheme for OCTET STRINGs and other strings. The constraints specified for a type are especially important for PER, because they affect the encoding.

Examples:

Digs ::= NumericString (SIZE(1..3))
TextFile ::= IA5String (SIZE(0..64000))

The corresponding Erlang assignments:

DigsVal1 = "456",
DigsVal2 = "123",
TextFileVal1 = "abc...xyz...",
TextFileVal2 = [88,76,55,44,99,121 .......... a lot of characters here ....]

The Erlang representation for BMPString and UniversalString is either a list of ASCII values or a list of quadruples. The quadruple representation associates to the Unicode standard representation of characters. The ASCII characters are all represented by quadruples beginning with three zeros like {0,0,0,65} for character 'A'. When decoding a value for these strings, the result is a list of quadruples, or integers when the value is an ASCII character.

The following example shows how it works. Assume the following specification is in file PrimStrings.asn1:

PrimStrings DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
   BMP ::= BMPString
END

Encoding and decoding some strings:

1> asn1ct:compile('PrimStrings', [ber]).
ok
2> {ok,Bytes1} = 'PrimStrings':encode('BMP', [{0,0,53,53},{0,0,45,56}]).
{ok,<<30,4,53,54,45,56>>}
3> 'PrimStrings':decode('BMP', Bytes1).
{ok,[{0,0,53,53},{0,0,45,56}]}
4> {ok,Bytes2} = 'PrimStrings':encode('BMP', [{0,0,53,53},{0,0,0,65}]).
{ok,<<30,4,53,53,0,65>>}
5> 'PrimStrings':decode('BMP', Bytes2).
{ok,[{0,0,53,53},65]}
6> {ok,Bytes3} = 'PrimStrings':encode('BMP', "BMP string").
{ok,<<30,20,0,66,0,77,0,80,0,32,0,115,0,116,0,114,0,105,0,110,0,103>>}
7> 'PrimStrings':decode('BMP', Bytes3).
{ok,"BMP string"}

Type UTF8String is represented as a UTF-8 encoded binary in Erlang. Such binaries can be created directly using the binary syntax or by converting from a list of Unicode code points using function unicode:characters_to_binary/1.

The following shows examples of how UTF-8 encoded binaries can be created and manipulated:

1> Gs = "Мой маленький Гном".
[1052,1086,1081,32,1084,1072,1083,1077,1085,1100,1082,1080,
 1081,32,1043,1085,1086,1084]
2> Gbin = unicode:characters_to_binary(Gs).
<<208,156,208,190,208,185,32,208,188,208,176,208,187,208,
  181,208,189,209,140,208,186,208,184,208,185,32,208,147,
  208,...>>
3> Gbin = <<"Мой маленький Гном"/utf8>>.
<<208,156,208,190,208,185,32,208,188,208,176,208,187,208,
  181,208,189,209,140,208,186,208,184,208,185,32,208,147,
  208,...>>
4> Gs = unicode:characters_to_list(Gbin).
[1052,1086,1081,32,1084,1072,1083,1077,1085,1100,1082,1080,
 1081,32,1043,1085,1086,1084]

For details, see the unicode module in STDLIB.

In the following example, this ASN.1 specification is used:

UTF DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
   UTF ::= UTF8String
END

Encoding and decoding a string with Unicode characters:

5> asn1ct:compile('UTF', [ber]).
ok
6> {ok,Bytes1} = 'UTF':encode('UTF', <<"Гном"/utf8>>).
{ok,<<12,8,208,147,208,189,208,190,208,188>>}
7> {ok,Bin1} = 'UTF':decode('UTF', Bytes1).
{ok,<<208,147,208,189,208,190,208,188>>}
8> io:format("~ts\n", [Bin1]).
Гном
ok
9> unicode:characters_to_list(Bin1).
[1043,1085,1086,1084]

OBJECT IDENTIFIER

The type OBJECT IDENTIFIER is used whenever a unique identity is required. An ASN.1 module, a transfer syntax, and so on, is identified with an OBJECT IDENTIFIER. Assume the following example:

Oid ::= OBJECT IDENTIFIER

Therefore, the following example is a valid Erlang instance of type Oid:

OidVal1 = {1,2,55},

The OBJECT IDENTIFIER value is a tuple with the consecutive integer values.

The first value is limited to the values 0, 1, or 2. The second value must be in the range 0 through 39 when the first value is 0 or 1.

The OBJECT IDENTIFIER is an important type and it is widely used within different standards to identify various objects uniquely. Dubuisson: ASN.1 - Communication Between Heterogeneous Systems includes an easy-to-understand description of the use of OBJECT IDENTIFIER.

Object Descriptor

Values of this type can be assigned a value as an ordinary string as follows:

"This is the value of an Object descriptor"

TIME Types

Two time types are defined within ASN.1: Generalized Time and Universal Time Coordinated (UTC). Both are assigned a value as an ordinary string within double quotes, for example, "19820102070533.8".

For DER encoding, the compiler does not check the validity of the time values. The DER requirements upon those strings are regarded as a matter for the application to fulfill.

SEQUENCE

The structured types of ASN.1 are constructed from other types in a manner similar to the concepts of arrays and structs in C.

A SEQUENCE in ASN.1 is comparable with a struct in C and a record in Erlang. A SEQUENCE can be defined as follows:

Pdu ::= SEQUENCE {
   a INTEGER,
   b REAL,
   c OBJECT IDENTIFIER,
   d NULL }

This is a 4-component structure called Pdu. By default, a SEQUENCE is represented by a record in Erlang. It can also be represented as a map; see Map representation for SEQUENCE and SET. For each SEQUENCE and SET in an ASN.1 module an Erlang record declaration is generated. For Pdu, a record like the following is defined:

-record('Pdu', {a, b, c, d}).

The record declarations for a module M are placed in a separate M.hrl file.

Values can be assigned in Erlang as follows:

MyPdu = #'Pdu'{a=22,b=77.99,c={0,1,2,3,4},d='NULL'}.

The decode functions return a record as result when decoding a SEQUENCE or a SET.

A SEQUENCE and a SET can contain a component with a DEFAULT keyword followed by the actual value, which is the default value. The DEFAULT keyword means that the application doing the encoding can omit encoding of the value, which results in fewer bytes to send to the receiving application.

An application can use the atom asn1_DEFAULT to indicate that the encoding is to be omitted for that position in the SEQUENCE.

Depending on the encoding rules, the encoder can also compare the given value to the default value and automatically omit the encoding if the values are equal. How much effort the encoder makes to compare the values depends on the encoding rules. The DER encoding rules forbid encoding a value equal to the default value, so it has a more thorough and time-consuming comparison than the encoders for the other encoding rules.

In the following example, this ASN.1 specification is used:

File DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
Seq1 ::= SEQUENCE {
    a INTEGER DEFAULT 1,
    b Seq2 DEFAULT {aa TRUE, bb 15}
}

Seq2 ::= SEQUENCE {
    aa BOOLEAN,
    bb INTEGER
}

Seq3 ::= SEQUENCE {
    bs BIT STRING {a(0), b(1), c(2)} DEFAULT {a, c}
}
END

Example where the BER encoder is able to omit encoding of the default values:

1> asn1ct:compile('File', [ber]).
ok
2> 'File':encode('Seq1', {'Seq1',asn1_DEFAULT,asn1_DEFAULT}).
{ok,<<48,0>>}
3> 'File':encode('Seq1', {'Seq1',1,{'Seq2',true,15}}).
{ok,<<48,0>>}

Example with a named BIT STRING where the BER encoder does not omit the encoding:

4> 'File':encode('Seq3', {'Seq3',asn1_DEFAULT).
{ok,<<48,0>>}
5> 'File':encode('Seq3', {'Seq3',<<16#101:3>>).
{ok,<<48,4,128,2,5,160>>}

The DER encoder omits the encoding for the same BIT STRING:

6> asn1ct:compile('File', [ber,der]).
ok
7> 'File':encode('Seq3', {'Seq3',asn1_DEFAULT).
{ok,<<48,0>>}
8> 'File':encode('Seq3', {'Seq3',<<16#101:3>>).
{ok,<<48,0>>}

SET

In Erlang, the SET type is used exactly as SEQUENCE. Notice that if BER or DER encoding rules are used, decoding a SET is slower than decoding a SEQUENCE because the components must be sorted.

Extensibility for SEQUENCE and SET

When a SEQUENCE or SET contains an extension marker and extension components as the following, the type can get more components in newer versions of the ASN.1 spec:

SExt ::= SEQUENCE {
           a INTEGER,
           ...,
           b BOOLEAN }

In this case it has got a new component b. Thus, incoming messages that are decoded can have more or fever components than this one.

The component b is treated as an original component when encoding a message. In this case, as it is not an optional element, it must be encoded.

During decoding, the b field of the record gets the decoded value of the b component, if present, otherwise the value asn1_NOVALUE.

Map representation for SEQUENCE and SET

If the ASN.1 module has been compiled with option maps, the types SEQUENCE and SET are represented as maps.

In the following example, this ASN.1 specification is used:

File DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
Seq1 ::= SEQUENCE {
    a INTEGER DEFAULT 42,
    b BOOLEAN OPTIONAL,
    c IA5String
}
END

Optional fields are to be omitted from the map if they have no value:

1> asn1ct:compile('File', [per,maps]).
ok
2> {ok,E} = 'File':encode('Seq1', #{a=>0,c=>"string"}).
{ok,<<128,1,0,6,115,116,114,105,110,103>>}

When decoding, optional fields will be omitted from the map:

3> 'File':decode('Seq1', E).
{ok,#{a => 0,c => "string"}}

Default values can be omitted from the map:

4> {ok,E2} = 'File':encode('Seq1', #{c=>"string"}).
{ok,<<0,6,115,116,114,105,110,103>>}
5> 'File':decode('Seq1', E2).
{ok,#{a => 42,c => "string"}}

Note

It is not allowed to use the atoms asn1_VALUE and asn1_DEFAULT with maps.

CHOICE

The type CHOICE is a space saver and is similar to the concept of union in C.

Assume the following:

SomeModuleName DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
T ::= CHOICE {
        x REAL,
        y INTEGER,
        z OBJECT IDENTIFIER }
END

It is then possible to assign values as follows:

TVal1 = {y,17},
TVal2 = {z,{0,1,2}},

A CHOICE value is always represented as the tuple {ChoiceAlternative, Val} where ChoiceAlternative is an atom denoting the selected choice alternative.

Extensible CHOICE

When a CHOICE contains an extension marker and the decoder detects an unknown alternative of the CHOICE, the value is represented as follows:

{asn1_ExtAlt, BytesForOpenType}

Here BytesForOpenType is a list of bytes constituting the encoding of the "unknown" CHOICE alternative.

SET OF and SEQUENCE OF

The types SET OF and SEQUENCE OF correspond to the concept of an array in several programming languages. The Erlang syntax for both types is straightforward, for example:

Arr1 ::= SET SIZE (5) OF INTEGER (4..9)
Arr2 ::= SEQUENCE OF OCTET STRING

In Erlang the following can apply:

Arr1Val = [4,5,6,7,8],
Arr2Val = ["abc",[14,34,54],"Octets"],

Notice that the definition of type SET OF implies that the order of the components is undefined, but in practice there is no difference between SET OF and SEQUENCE OF. The ASN.1 compiler for Erlang does not randomize the order of the SET OF components before encoding.

However, for a value of type SET OF, the DER encoding format requires the elements to be sent in ascending order of their encoding, which implies an expensive sorting procedure in runtime. Therefore it is recommended to use SEQUENCE OF instead of SET OF if possible.

ANY and ANY DEFINED BY

The types ANY and ANY DEFINED BY have been removed from the standard since 1994. It is recommended not to use these types any more. They can, however, exist in some old ASN.1 modules. The idea with this type was to leave a "hole" in a definition where it was possible to put unspecified data of any kind, even non-ASN.1 data.

A value of this type is encoded as an open type.

Instead of ANY and ANY DEFINED BY, it is recommended to use information object classes, table constraints, and parameterization. In particular the construct TYPE-IDENTIFIER.@Type accomplishes the same as the deprecated ANY.

Also see Information objects.

EXTERNAL, EMBEDDED PDV, and CHARACTER STRING

The types EXTERNAL, EMBEDDED PDV, and CHARACTER STRING are used in presentation layer negotiation. They are encoded according to their associated type, see X.680.

The type EXTERNAL had a slightly different associated type before 1994. X.691 states that encoding must follow the older associated type. So, generated encode/decode functions convert values of the newer format to the older format before encoding. This implies that it is allowed to use EXTERNAL type values of either format for encoding. Decoded values are always returned in the newer format.

Embedded Named Types

The structured types previously described can have other named types as their components. The general syntax to assign a value to component C of a named ASN.1 type T in Erlang is the record syntax #'T'{'C'=Value}. Here Value can be a value of yet another type T2, for example:

EmbeddedExample DEFINITIONS AUTOMATIC TAGS ::=
BEGIN
B ::= SEQUENCE {
        a Arr1,
        b T }

Arr1 ::= SET SIZE (5) OF INTEGER (4..9)

T ::= CHOICE {
        x REAL,
        y INTEGER,
        z OBJECT IDENTIFIER }
        END

SEQUENCE b can be encoded as follows in Erlang:

1> 'EmbeddedExample':encode('B', {'B',[4,5,6,7,8],{x,"7.77"}}).
{ok,<<5,56,0,8,3,55,55,55,46,69,45,50>>}

Naming of Records in .hrl Files

When the option maps is given, no .hrl files will be generated. The rest of this section describes the behavior of the compiler when maps is not used.

When an ASN.1 specification is compiled, all defined types of type SET or SEQUENCE result in a corresponding record in the generated .hrl file. This is because the values for SET and SEQUENCE are represented as records by default.

Some special cases of this functionality are presented in the next section.

Embedded Structured Types

In ASN.1 it is also possible to have components that are themselves structured types. For example, it is possible to have the following:

Emb ::= SEQUENCE {
    a SEQUENCE OF OCTET STRING,
    b SET {
       a INTEGER,
       b INTEGER DEFAULT 66},
    c CHOICE {
       a INTEGER,
       b FooType } }

FooType ::= [3] VisibleString

The following records are generated because of type Emb:

-record('Emb,{a, b, c}).
-record('Emb_b',{a, b = asn1_DEFAULT}). % the embedded SET type

Values of type Emb can be assigned as follows:

V = #'Emb'{a=["qqqq",[1,2,255]],
           b = #'Emb_b'{a=99},
           c ={b,"Can you see this"}}.

For an embedded type of type SEQUENCE/SET in a SEQUENCE/SET, the record name is extended with an underscore and the component name. If the embedded structure is deeper with the SEQUENCE, SET, or CHOICE types in the line, each component name/alternative name is added to the record name.

Example:

Seq ::= SEQUENCE{
    a CHOICE{
        b SEQUENCE {
           c  INTEGER
        }
    }
}

This results in the following record:

-record('Seq_a_b',{c}).

If the structured type has a component with an embedded SEQUENCE OF/SET OF which embedded type in turn is a SEQUENCE/SET, it gives a record with the SEQUENCE OF/SET OF addition as in the following example:

Seq ::= SEQUENCE {
    a SEQUENCE OF SEQUENCE {
           b
               }
    c SET OF SEQUENCE {
           d
               }
}

This results in the following records:

-record('Seq_a_SEQOF'{b}).
-record('Seq_c_SETOF'{d}).

A parameterized type is to be considered as an embedded type. Each time such a type is referenced, an instance of it is defined. Thus, in the following example a record with name 'Seq_b' is generated in the .hrl file and is used to hold values:

Seq ::= SEQUENCE {
    b PType{INTEGER}
}

PType{T} ::= SEQUENCE{
    id T
}

Recursive Types

Types that refer to themselves are called recursive types. Example:

Rec ::= CHOICE {
     nothing NULL,
     something SEQUENCE {
          a INTEGER,
          b OCTET STRING,
          c Rec }}

This is allowed in ASN.1 and the ASN.1-to-Erlang compiler supports this recursive type. A value for this type is assigned in Erlang as follows:

V = {something,#'Rec_something'{a = 77,
                                b = "some octets here",
                                c = {nothing,'NULL'}}}.

ASN.1 Values

Values can be assigned to an ASN.1 type within the ASN.1 code itself, as opposed to the actions in the previous section where a value was assigned to an ASN.1 type in Erlang. The full value syntax of ASN.1 is supported and X.680 describes in detail how to assign values in ASN.1. A short example:

TT ::= SEQUENCE {
   a INTEGER,
   b SET OF OCTET STRING }

tt TT ::= {a 77,b {"kalle","kula"}}

The value defined here can be used in several ways. It can, for example, be used as the value in some DEFAULT component:

SS ::= SET {
    s OBJECT IDENTIFIER,
    val TT DEFAULT tt }

It can also be used from inside an Erlang program. If this ASN.1 code is defined in ASN.1 module Values, the ASN.1 value tt can be reached from Erlang as a function call to 'Values':tt() as in the following example:

1> Val = 'Values':tt().
{'TT',77,["kalle","kula"]}
2> {ok,Bytes} = 'Values':encode('TT',Val).
{ok,<<48,18,128,1,77,161,13,4,5,107,97,108,108,101,4,4,
      107,117,108,97>>}
4> 'Values':decode('TT',Bytes).
{ok,{'TT',77,["kalle","kula"]}}
5>

This example shows that a function is generated by the compiler that returns a valid Erlang representation of the value, although the value is of a complex type.

Furthermore, if the option maps is not used, a macro is generated for each value in the .hrl file. So, the defined value tt can also be extracted by ?tt in application code.

Macros

The type MACRO is not supported. It is no longer part of the ASN.1 standard.

ASN.1 Information Objects (X.681)

Information Object Classes, Information Objects, and Information Object Sets (in the following called classes, objects, and object sets, respectively) are defined in the standard definition X.681. Only a brief explanation is given here.

These constructs makes it possible to define open types, that is, values of that type can be of any ASN.1 type. Also, relationships can be defined between different types and values, as classes can hold types, values, objects, object sets, and other classes in their fields. A class can be defined in ASN.1 as follows:

GENERAL-PROCEDURE ::= CLASS {
      &Message,
      &Reply               OPTIONAL,
      &Error               OPTIONAL,
      &id          PrintableString UNIQUE
}
WITH SYNTAX {
      NEW MESSAGE     &Message
      [REPLY           &Reply]
      [ERROR           &Error]
      ADDRESS          &id
}

An object is an instance of a class. An object set is a set containing objects of a specified class. A definition can look as follows:

object1 GENERAL-PROCEDURE ::= {
    NEW MESSAGE      PrintableString
    ADDRESS          "home"
}

object2 GENERAL-PROCEDURE ::= {
    NEW MESSAGE INTEGER
    ERROR INTEGER
    ADDRESS "remote"
}

The object object1 is an instance of the class GENERAL-PROCEDURE and has one type field and one fixed type value field. The object object2 has also an optional field ERROR, which is a type field. The field ADDRESS is a UNIQUE field. Objects in an object set must have unique values in their UNIQUE field, as in GENERAL-PROCEDURES:

GENERAL-PROCEDURES GENERAL-PROCEDURE ::= {
    object1 | object2}

You cannot encode a class, object, or object set, only refer to it when defining other ASN.1 entities. Typically you refer to a class as well as to object sets by table constraints and component relation constraints (X.682) in ASN.1 types, as in the following:

StartMessage  ::= SEQUENCE {
    msgId  GENERAL-PROCEDURE.&id  ({GENERAL-PROCEDURES}),
    content GENERAL-PROCEDURE.&Message ({GENERAL-PROCEDURES}{@msgId}),
    }

In type StartMessage, the constraint following field content tells that in a value of type StartMessage the value in field content must come from the same object that is chosen by field msgId.

So, the value #'StartMessage'{msgId="home",content="Any Printable String"} is legal to encode as a StartMessage value. However, the value #'StartMessage'{msgId="remote", content="Some String"} is illegal as the constraint in StartMessage tells that when you have chosen a value from a specific object in object set GENERAL-PROCEDURES in field msgId, you must choose a value from that same object in the content field too. In this second case, it is to be any INTEGER value.

StartMessage can in field content be encoded with a value of any type that an object in object set GENERAL-PROCEDURES has in its NEW MESSAGE field. This field refers to a type field &Message in the class. Field msgId is always encoded as a PrintableString, as the field refers to a fixed type in the class.

In practice, object sets are usually declared to be extensible so that more objects can be added to the set later. Extensibility is indicated as follows:

GENERAL-PROCEDURES GENERAL-PROCEDURE ::= {
    object1 | object2, ...}

When decoding a type that uses an extensible set constraint, it is always possible that the value in field UNIQUE is unknown (that is, the type has been encoded with a later version of the ASN.1 specification). The unencoded data is then returned wrapped in a tuple as follows:

{asn1_OPENTYPE,Binary}

Here Binary is an Erlang binary that contains the encoded data. (If option legacy_erlang_types has been given, only the binary is returned.)

Parameterization (X.683)

Parameterization, which is defined in X.683, can be used when defining types, values, value sets, classes, objects, or object sets. A part of a definition can be supplied as a parameter. For example, if a Type is used in a definition with a certain purpose, you want the type name to express the intention. This can be done with parameterization.

When many types (or another ASN.1 entity) only differ in some minor cases, but the structure of the types is similar, only one general type can be defined and the differences can be supplied through parameters.

Example of use of parameterization:

General{Type} ::= SEQUENCE
{
     number     INTEGER,
     string     Type
}

T1 ::= General{PrintableString}

T2 ::= General{BIT STRING}

An example of a value that can be encoded as type T1 is {12,"hello"}.

Notice that the compiler does not generate encode/decode functions for parameterized types, only for the instances of the parameterized types. Therefore, if a file contains the types General{}, T1, and T2 as in the previous example, encode/decode functions are only generated for T1 and T2.

Specialized Decodes

When performance is of highest priority and one is interested in a limited part of the ASN.1 encoded message before deciding what to do with the rest of it, an option is to decode only a part of the message. This situation can be a server that has to decide the addressee of a message. The addressee can be interested in the entire message, but the server can be a bottleneck that you want to spare any unnecessary load.

Instead of making two complete decodes (the normal case of decode), one in the server and one in the addressee, it is only necessary to make one specialized decode (in the server) and another complete decode (in the addressee). This section describes the following specialized decode functionality:

Exclusive decode

Selected decode

This functionality is only provided when using BER (option ber).

Exclusive Decode

The basic idea with exclusive decode is to specify which parts of the message you want to exclude from being decoded. These parts remain encoded and are returned in the value structure as binaries. The undecoded parts can be decoded later by calling the decode_part/2 function.

Procedure

To perform an exclusive decode:

Step 1: Decide the name of the function for the exclusive decode.

Step 2: Include the following instructions in a configuration file:

The name of the exclusive decode function

The name of the ASN.1 specification

A notation that tells which parts of the message structure to be excluded from decode

Step 3 Compile with the additional option asn1config. The compiler searches for a configuration file with the same name as the ASN.1 specification but with extension .asn1config. This configuration file is not the same as used for compilation of a set of files. See section Writing an Exclusive Decode Instruction.

User Interface

The runtime user interface for exclusive decode comprises the following two functions:

A function for an exclusive decode, whose name the user decides in the configuration file

A decode_part/2 function generated by the ASN.1 compiler when exclusive decode is enabled. This function decodes the parts that were left undecoded during the exclusive decode.

Both functions are described in the following.

If the exclusive decode function has, for example, the name decode_exclusive and an ASN.1 encoded message Bin is to be exclusive decoded, the call is as follows:

{ok,ExclMessage} = 'MyModule':decode_exclusive(Bin)

The result ExclMessage has the same structure as a complete decode would have, except for the parts of the top type that were not decoded. The undecoded parts are on their places in the structure on format {TypeKey,UndecodedValue}.

Each undecoded part that is to be decoded must be fed into function decode_part/2 as follows:

{ok,PartMessage} = 'MyModule':decode_part(TypeKey, UndecodedValue)

Writing an Exclusive Decode Instruction

This instruction is written in the configuration file in the following format:

ExclusiveDecodeInstruction = {exclusive_decode,{ModuleName,DecodeInstructions}}.

ModuleName = atom()

DecodeInstructions = [DecodeInstruction]+

DecodeInstruction = {ExclusiveDecodeFunctionName,TypeList}

ExclusiveDecodeFunctionName = atom()

TypeList = [TopType,ElementList]

ElementList = [Element]+

Element = {Name,parts} |
          {Name,undecoded} |
          {Name,ElementList}

TopType = atom()

Name = atom()

The instruction must be a valid Erlang term terminated by a dot.

In TypeList the path from the top type to each undecoded subcomponent is described. TopType is the name of a top-level type in the ASN.1 specification. The action for each component in ElementList is described by one of:

{Name,parts}

{Name,undecoded}

{Name,ElementList}

The use and effect of the actions are as follows:

{Name,undecoded} - Leaves the element undecoded. The type of Name can be any ASN.1 type. The value of element Name is returned as a tuple (as mentioned in the previous section) in the value structure of the top type.

{Name,parts} - The type of Name must be either SEQUENCE OF or SET OF. The action implies that the different components of Name are left undecoded. The value of Name is returned as a tuple (as mentioned in the previous section) where the second element is a list of binaries. This is because the representation of a SEQUENCE OF or a SET OF in Erlang is a list of its internal type. Any of the elements in this list or the entire list can be decoded by function decodepart.

{Name,ElementList} - This action is used when one or more of the subtypes of Name is exclusively decoded.

Name in these actions can be a component name of a SEQUENCE OF or a SET OF, or a name of an alternative in a CHOICE.

Example

In this examples, the definitions from the following ASN.1 specification are used:

GUI DEFINITIONS AUTOMATIC TAGS ::= BEGIN

  Action ::= SEQUENCE {
    number  INTEGER DEFAULT 15,
    handle  Handle DEFAULT {number 12, on TRUE}
  }

  Key ::= Button
  Handle ::= Key

  Button ::= SEQUENCE {
    number INTEGER,
    on     BOOLEAN
  }

  Window ::= CHOICE {
    vsn INTEGER,
    status Status
  }

  Status ::= SEQUENCE {
    state INTEGER,
    buttonList SEQUENCE OF Button,
    enabled BOOLEAN OPTIONAL,
    actions CHOICE {
      possibleActions SEQUENCE OF Action,
      noOfActions INTEGER
    }
  }

END

If Button is a top type and it is needed to exclude component number from decode, TypeList in the instruction in the configuration file is ['Button',[{number,undecoded}]]. If you call the decode function decode_Button_exclusive, DecodeInstruction is {decode_Button_exclusive,['Button',[{number,undecoded}]]}.

Another top type is Window whose subcomponent actions in type Status and the parts of component buttonList are to be left undecoded. For this type, the function is named decode__Window_exclusive. The complete Exclusive_Decode_Instruction configuration is as follows:

{exclusive_decode,
 {'GUI',
  [{decode_Window_exclusive,
    ['Window',[{status,[{buttonList,parts},{actions,undecoded}]}]]},
   {decode_Button_exclusive,
    ['Button',[{number,undecoded}]]}]}}.

The following figure shows the bytes of a Window:status message. The components buttonList and actions are excluded from decode. Only state and enabled are decoded when decode__Window_exclusive is called.

Here follows an example of how the module. Note that option no_ok_wrapper is used to make the example more concise.

1> asn1ct:compile('GUI', [ber,asn1config,no_ok_wrapper]).
ok
2> rr('GUI').
['Action','Button','Status']
3> ButtonMsg = #'Button'{number=123,on=true}.
#'Button'{number = 123,on = true}
4> ButtonBytes = 'GUI':encode('Button', ButtonMsg).
<<48,6,128,1,123,129,1,255>>
5> ExclusiveMsgButton = 'GUI':decode_Button_exclusive(ButtonBytes).
#'Button'{number = {'Button_number',<<128,1,123>>},
          on = true}
6> {UndecKey,UndecBytes} = ExclusiveMsgButton#'Button'.number.
{'Button_number',<<128,1,123>>}
7> 'GUI':decode_part(UndecKey, UndecBytes).
123
8> WindowMsg =
{status,{'Status',35,
   [{'Button',3,true},
    {'Button',4,false},
    {'Button',5,true},
    {'Button',6,true},
    {'Button',7,false}],
   false,
   {possibleActions,[{'Action',16,{'Button',17,true}}]}}}.
{status,#'Status'{state = 35,
        buttonList = [#'Button'{number = 3,on = true},
                      #'Button'{number = 4,on = false},
                      #'Button'{number = 5,on = true},
                      #'Button'{number = 6,on = true},
                      #'Button'{number = 7,on = false}],
        enabled = false,
        actions = {possibleActions,[#'Action'{number = 16,
                                              handle = #'Button'{number = 17,on = true}}]}}}
9> WindowBytes = 'GUI':encode('Window', WindowMsg).
<<161,65,128,1,35,161,40,48,6,128,1,3,129,1,255,48,6,128,
  1,4,129,1,0,48,6,128,1,5,129,...>>
10> {status,#'Status'{buttonList={UndecWindowKey,UndecWindowParts}}} =
'GUI':decode_Window_exclusive(WindowBytes).
{status,#'Status'{state = 35,
                  buttonList = {'Status_buttonList',[<<48,6,128,1,3,129,1,
                                                       255>>,
                                                     <<48,6,128,1,4,129,1,0>>,
                                                     <<48,6,128,1,5,129,1,255>>,
                                                     <<48,6,128,1,6,129,1,255>>,
                                                     <<48,6,128,1,7,129,1,0>>]},
                  enabled = false,
                  actions = {'Status_actions',<<163,15,160,13,48,11,128,
                                                1,16,161,6,128,1,17,129,
                                                1,255>>}}}
11> 'GUI':decode_part(UndecWindowKey, UndecWindowParts).
[#'Button'{number = 3,on = true},
 #'Button'{number = 4,on = false},
 #'Button'{number = 5,on = true},
 #'Button'{number = 6,on = true},
 #'Button'{number = 7,on = false}]
12> 'GUI':decode_part(UndecWindowKey, hd(UndecWindowParts)).
#'Button'{number = 3,on = true}
13> {status,#'Status'{actions={ChoiceKey,ChoiceUndec}}} = v(10).
{status,#'Status'{state = 35,
                  buttonList = {'Status_buttonList',[<<48,6,128,1,3,129,1,
                                                       255>>,
                                                     <<48,6,128,1,4,129,1,0>>,
                                                     <<48,6,128,1,5,129,1,255>>,
                                                     <<48,6,128,1,6,129,1,255>>,
                                                     <<48,6,128,1,7,129,1,0>>]},
                  enabled = false,
                  actions = {'Status_actions',<<163,15,160,13,48,11,128,
                                                1,16,161,6,128,1,17,129,
                                                1,255>>}}}
14> 'GUI':decode_part(ChoiceKey, ChoiceUndec).
{possibleActions,[#'Action'{number = 16,
                            handle = #'Button'{number = 17,on = true}}]}

Selective Decode

Selective decode decodes a single subtype of a constructed value. This is the fastest method to extract a subvalue. Selective decode is typically used when one want to inspect, for example, a version number to be able to decide how to handle the entire value.

Procedure

To perform a selective decode:

Step 1: Include the following instructions in the configuration file:

The name of the user function

The name of the ASN.1 specification

A notation that tells which part of the type to be decoded

Step 2: Compile with the additional option asn1config. The compiler searches for a configuration file with the same name as the ASN.1 specification, but with extension .asn1config. In the same file you can also provide configuration specifications for exclusive decode. The generated Erlang module has the usual functionality for encode/decode preserved and the specialized decode functionality added.

User Interface

The only new user interface function is the one provided by the user in the configuration file.

For example, if the configuration file includes the specification {selective_decode,{'ModuleName',[{selected_decode_Window,TypeList}]}} do the selective decode by {ok,Result} = 'ModuleName':selected_decode_Window(EncodedBinary).

Writing a Selective Decode Instruction

One or more selective decode functions can be described in a configuration file. Use the following notation:

SelectiveDecodeInstruction = {selective_decode,{ModuleName,DecodeInstructions}}.

ModuleName = atom()

DecodeInstructions = [DecodeInstruction]+

DecodeInstruction = {SelectiveDecodeFunctionName,TypeList}

SelectiveDecodeFunctionName = atom()

TypeList = [TopType|ElementList]

ElementList = Name|ListSelector

Name = atom()

ListSelector = [integer()]

The instruction must be a valid Erlang term terminated by a dot.

ModuleName is the same as the name of the ASN.1 specification, but without the extension.

DecodeInstruction is a tuple with your chosen function name and the components from the top type that leads to the single type you want to decode. Make sure to choose a name of your function that is not the same as any of the generated functions.

The first element of TypeList is the top type of the encoded message. In ElementList, it is followed by each of the component names that leads to selected type.

Each name in ElementList must be a constructed type except the last name, which can be any type.

ListSelector makes it possible to choose one of the encoded components in a SEQUENCE OF or a SET OF. It is also possible to go further in that component and pick a subtype of that to decode. So, in the TypeList: ['Window',status,buttonList,[1],number], component buttonList must be of type SEQUENCE OF or SET OF.

In the example, component number of the first of the encoded elements in the SEQUENCE OF buttonList is selected. This applies on the ASN.1 specification in section Writing an Exclusive Decode Instruction.

Example

In this example, the same ASN.1 specification as in section Writing an Exclusive Decode Instruction is used. The following is a valid selective decode instruction:

{selective_decode,
    {'GUI',
        [{selected_decode_Window1,
            ['Window',status,buttonList,
             [1],
             number]},
 {selected_decode_Action,
     ['Action',handle,number]},
 {selected_decode_Window2,
     ['Window',
      status,
      actions,
      possibleActions,
      [1],
      handle,number]}]}}.

The first instruction, {selected_decode_Window1,['Window',status,buttonList,[1],number]} is described in the previous section.

The second instruction, {selected_decode_Action,['Action',handle,number]}, takes component number in the handle component of type Action. If the value is ValAction = {'Action',17,{'Button',4711,false}}, the internal value 4711 is to be picked by selected_decode_Action. In an Erlang terminal it looks as follows:

1> asn1ct:compile('GUI', [ber,asn1config,no_ok_wrapper]).
ok
2> ValAction = {'Action',17,{'Button',4711,false}}.
{'Action',17,{'Button',4711,false}}
3> Bytes = 'GUI':encode('Action',ValAction).
<<48,18,2,1,17,160,13,172,11,171,9,48,7,128,2,18,103,129,1,0>>
4> 'GUI':selected_decode_Action(Bytes).
4711

The third instruction, ['Window',status,actions,possibleActions,[1],handle,number], works as follows:

Step 1: Starts with type Window.

Step 2: Takes component status of Window that is of type Status.

Step 3: Takes actions of type Status.

Step 4: Takes possibleActions of the internally defined CHOICE type.

Step 5: Goes into the first component of SEQUENCE OF by [1]. That component is of type Action.

Step 6: Takes component handle.

Step 7: Takes component number of type Button.

The following figure shows which components are in TypeList ['Window',status,actions,possibleActions,[1],handle,number]:

In the following figure, only the marked element is decoded by selected_decode_Window2:

With the following example, you can examine that both selected_decode_Window2 and selected_decode_Window1 decodes the intended subvalue of value Val:

1> Val = {status,{'Status',12,
                    [{'Button',13,true},
                     {'Button',14,false},
                     {'Button',15,true},
                     {'Button',16,false}],
                    true,
                    {possibleActions,[{'Action',17,{'Button',18,false}},
                                      {'Action',19,{'Button',20,true}},
                                      {'Action',21,{'Button',22,false}}]}}}.
2> Bin = 'GUI':encode('Window',Val).
<<161,89,128,1,12,161,32,48,6,128,1,13,129,1,255,48,6,128,
  1,14,129,1,0,48,6,128,1,15,129,...>>
4> 'GUI':selected_decode_Window1(Bin).
13
5> 'GUI':selected_decode_Window2(Bin).
18

asn1ct

ASN.1 compiler and compile-time support functions

The ASN.1 compiler takes an ASN.1 module as input and generates a corresponding Erlang module, which can encode and decode the specified data types. Alternatively, the compiler takes a specification module specifying all input modules, and generates a module with encode/decode functions. In addition, some generic functions can be used during development of applications that handles ASN.1 data (encoded as BER or PER).

Note

By default in Erlang/OTP 17, the representation of the BIT STRING and OCTET STRING types as Erlang terms were changed. BIT STRING values are now Erlang bit strings and OCTET STRING values are binaries. Also, an undecoded open type is now wrapped in an asn1_OPENTYPE tuple. For details, see BIT STRING, OCTET STRING, and ASN.1 Information Objects in the User's Guide.

To revert to the old representation of the types, use option legacy_erlang_types.

Summary

Functions

compile(Asn1Module)

Equivalent to compile(Asn1Module, []).

compile(Asn1Module, Options)

Compiles the ASN.1 module Asn1Module and generates an Erlang module Asn1Module.erl with encode and decode functions for all types defined in the ASN.1 module.

test(Module)

Tests encoding and decoding of all types in Module.

test/2

Tests encoding and decoding of Module.

test/3

Performs a test of encode and decode of types in Module.

value(Module, Type)

Returns an Erlang term that is an example of a valid Erlang representation of a value of the ASN.1 type Type.

Functions

compile(Asn1Module)

-spec compile(Asn1Module) -> ok | {error, Reason} when Asn1Module :: atom() | string(), Reason :: term().

Equivalent to compile(Asn1Module, []).

compile(Asn1Module, Options)

-spec compile(Asn1Module, Options) -> ok | {error, Reason}
                 when
                     Asn1Module :: atom() | string(),
                     Options :: [Option | OldOption],
                     Option ::
                         ber | per | uper | jer | der | compact_bit_string | legacy_bit_string |
                         legacy_erlang_types | noobj |
                         {n2n, EnumTypeName :: term()} |
                         {outdir, Dir :: term()} |
                         {i, IncludeDir :: term()} |
                         asn1config | undec_rest | no_ok_wrapper |
                         {macro_name_prefix, Prefix} |
                         {record_name_prefix, Prefix} |
                         verbose | warnings_as_errors | deterministic,
                     OldOption :: ber | per,
                     Reason :: term(),
                     Prefix :: string().

Compiles the ASN.1 module Asn1Module and generates an Erlang module Asn1Module.erl with encode and decode functions for all types defined in the ASN.1 module.

For each ASN.1 value defined in the module, an Erlang function that returns the value in Erlang representation is generated.

If Asn1Module is a filename without extension, first ".asn1" is assumed, then ".asn", and finally ".py" (to be compatible with the old ASN.1 compiler). Asn1Module can be a full pathname (relative or absolute) including filename with (or without) extension.

If it is needed to compile a set of ASN.1 modules into an Erlang file with encode/decode functions, list all involved files in a configuration file, one line per file. This configuration file must have a double extension ".set.asn1" (".asn1" can alternatively be ".asn" or ".py"). If the input files are File1.asn1, File2.asn1, and File3.asn1, the configuration file should look as follows:

File1.asn1
File2.asn1
File3.asn1

The output files in this case get their names from the configuration file. If the configuration file is named SetOfFiles.set.asn1, the names of the output files are SetOfFiles.hrl, SetOfFiles.erl, and SetOfFiles.asn1db.

Sometimes in a system of ASN.1 modules, different modules can have different default tag modes, for example, one uses AUTOMATIC and another IMPLICIT. The multi-file compilation resolves the default tagging as if the modules were compiled separately.

Name collisions is an unwanted effect that can occur in multi-file compilation. The compiler solves this problem in one of two ways:

If the definitions are identical, the output module keeps only one definition with the original name.

If the definitions have the same name and differs in the definition, they are renamed. The new names are the definition name and the original module name concatenated.

If a name collision occurs, the compiler reports a "NOTICE: ..." message that tells if a definition was renamed, and the new name that must be used to encode/decode data.

Options is a list with options specific for the ASN.1 compiler and options that are applied to the Erlang compiler. The ASN.1 compiler passes on any unrecognized options to the Erlang compiler. The available options are as follows:

ber | per | uper | jer - The encoding rule to be used. The supported encoding rules are Basic Encoding Rules (ber), Packed Encoding Rules (per) aligned, PER unaligned (uper), and JSON Encoding Rules (jer). The jer option can be used by itself to generate a module that only supports encoding/decoding of JER, or it can be used as a supplementary option to ber, per, and uper, in which case a module that handles both the main encoding rules and JER will be generated. In that case, the exported functions for JER will be jer_encode(Type, Value) and jer_decode(Type, Bytes).

JER (ITU-T X.697) are experimental in OTP 22. There is support for a subset of the X.697 standard, for example there is no support for:

JER encoding instructions

the REAL type

Change

In Erlang/OTP 27 and later, module json in STDLIB is used for encoding and decoding JSON. Before Erlang/OTP 27, it was necessary to provide an external JSON library.

If the encoding rule option is omitted, ber is the default.

The generated Erlang module always gets the same name as the ASN.1 module. Therefore, only one encoding rule per ASN.1 module can be used at runtime.

der - With this option the Distinguished Encoding Rules (der) is chosen. DER is regarded as a specialized variant of the BER encoding rule. Therefore, this option only makes sense together with option ber. This option sometimes adds sorting and value checks when encoding, which implies slower encoding. The decoding routines are the same as for ber.

maps - This option changes the representation of the types SEQUENCE and SET to use maps (instead of records). This option also suppresses the generation of .hrl files.

For details, see section Map representation for SEQUENCE and SET in the User's Guide.

compact_bit_string - The BIT STRING type is decoded to "compact notation".

This option is not recommended for new code.

For details, see section BIT STRING in the User's Guide.

This option implies option legacy_erlang_types, and it cannot be combined with option maps.

legacy_bit_string - The BIT STRING type is decoded to the legacy format, that is, a list of zeroes and ones.

This option is not recommended for new code.

For details, see section BIT STRING in the User's Guide

This option implies option legacy_erlang_types, and it cannot be combined with option maps.

legacy_erlang_types - Use the same Erlang types to represent BIT STRING and OCTET STRING as in Erlang/OTP R16.

This option is not recommended for new code.

For details, see section BIT STRING and section OCTET STRING in the User's Guide.

This option cannot be combined with option maps.

{n2n, EnumTypeName} - Tells the compiler to generate functions for conversion between names (as atoms) and numbers and conversely for the specified EnumTypeName. There can be multiple occurrences of this option to specify several type names. The type names must be declared as ENUMERATIONS in the ASN.1 specification.

If EnumTypeName does not exist in the ASN.1 specification, the compilation stops with an error code.

The generated conversion functions are named name2num_EnumTypeName/1 and num2name_EnumTypeName/1.

noobj - Do not compile (that is, do not produce object code) the generated .erl file. If this option is omitted, the generated Erlang module is compiled.

{i, IncludeDir} - Adds IncludeDir to the search-path for .asn1db and ASN.1 source files. The compiler tries to open an .asn1db file when a module imports definitions from another ASN.1 module. If no .asn1db file is found, the ASN.1 source file is parsed. Several {i, IncludeDir} can be given.

{outdir, Dir} - Specifies directory Dir where all generated files are to be placed. If this option is omitted, the files are placed in the current directory.

asn1config - When using one of the specialized decodes, exclusive or selective decode, instructions must be given in a configuration file. Option asn1config enables specialized decodes and takes the configuration file in concern. The configuration file has the same name as the ASN.1 specification, but with extension .asn1config.

For instructions for exclusive decode, see section Exclusive Decode in the User's Guide.

For instructions for selective decode, see section Selective Decode in the User's Guide.

undec_rest - By default when decoding, any bytes following the end of an ASN.1 data structure are discarded. If an ASN.1 module is compiled with option undec_rest, the decode function returns a tuple {ok, Value, Rest}, where Rest is the bytes following the ASN.1 data structure. Rest can be a list or a binary.

no_ok_wrapper - With this option, the generated encode/2 and decode/2 functions do not wrap a successful return value in an {ok,...} tuple. If any error occurs, an exception will be raised.

{macro_name_prefix, Prefix} - All macro names generated by the compiler are prefixed with Prefix. This is useful when multiple protocols that contain macros with identical names are included in a single module.

{record_name_prefix, Prefix} - All record names generated by the compiler are prefixed with Prefix. This is useful when multiple protocols that contain records with identical names are included in a single module.

verbose - Causes more verbose information from the compiler describing what it is doing.

warnings_as_errors - Causes warnings to be treated as errors.

deterministic - Causes all non-deterministic options to be stripped from the -asn1_info() attribute.

Unrecognized options are passed on to the Erlang compiler when the generated .erl file is compiled.

The compiler generates the following files:

Asn1Module.hrl (if any SET or SEQUENCE is defined)

Asn1Module.erl - Erlang module with encode, decode, and value functions

Asn1Module.asn1db - Intermediate format used by the compiler when modules IMPORT definitions from each other.

test(Module)

-spec test(Module) -> ok | {error, Reason} when Module :: module(), Reason :: term().

Tests encoding and decoding of all types in Module.

For more details, see test/3.

test/2

-spec test(Module, Type | Options) -> ok | {error, Reason}
              when
                  Module :: module(),
                  Type :: atom(),
                  Options :: [{i, IncludeDir :: term()}],
                  Reason :: term().

Tests encoding and decoding of Module.

If the second argument is given as atom Type, that type is tested.

If the second argument is given as list Options, that are the options that are used for testing all types in the module.

For more details, see test/3.

test/3

-spec test(Module, Type, Value | Options) -> ok | {error, Reason}
              when
                  Module :: module(),
                  Type :: atom(),
                  Value :: term(),
                  Options :: [{i, IncludeDir :: term()}],
                  Reason :: term().

Performs a test of encode and decode of types in Module.

The generated functions are called by this function. This function is useful for testing to ensure that the generated encode and decode functions as well as the general runtime support work as expected.

Note

Currently, the test functions have many limitations. Essentially, they will mostly work for old specifications based on the 1997 standard for ASN.1, but not for most modern-style applications. Another limitation is that the test functions may not work if options that change code generations strategies such as the options macro_name_prefix and record_name_prefix have been used.

test/1 iterates over all types in Module.

test/2 tests type Type with a random value.

test/3 tests type Type with Value.

Schematically, the following occurs for each type in the module:

{ok, Value} = asn1ct:value(Module, Type),
{ok, Bytes} = Module:encode(Type, Value),
{ok, Value} = Module:decode(Type, Bytes).

The test functions use the *.asn1db files for all included modules. If they are located in a different directory than the current working directory, use the include option to add paths. This is only needed when automatically generating values. For static values using Value no options are needed.

value(Module, Type)

-spec value(Module, Type) -> {ok, Value} | {error, Reason}
               when Module :: module(), Type :: atom(), Value :: term(), Reason :: term().

Returns an Erlang term that is an example of a valid Erlang representation of a value of the ASN.1 type Type.

The value is a random value and subsequent calls to this function will for most types return different values.

Note

Currently, the value function has many limitations. Essentially, it will mostly work for old specifications based on the 1997 standard for ASN.1, but not for most modern-style applications. Another limitation is that the value function may not work if options that change code generations strategies such as the options macro_name_prefix and record_name_prefix have been used.