1# BoringSSL API Conventions
2
3This document describes conventions for BoringSSL APIs. The [style
4guide](/STYLE.md) also includes guidelines, but this document is targeted at
5both API consumers and developers.
6
7
8## Documentation
9
10All supported public APIs are documented in the public header files, found in
11`include/openssl`. The API documentation is also available
12[online](https://commondatastorage.googleapis.com/chromium-boringssl-docs/headers.html).
13
14Some headers lack documention comments. These are functions and structures from
15OpenSSL's legacy ASN.1, X.509, and PEM implementation. If possible, avoid using
16them. These are left largely unmodified from upstream and are retained only for
17compatibility with existing OpenSSL consumers.
18
19
20## Forward declarations
21
22Do not write `typedef struct foo_st FOO` or try otherwise to define BoringSSL's
23types. Including `openssl/base.h` (or `openssl/ossl_typ.h` for consumers who
24wish to be OpenSSL-compatible) will forward-declare each type without importing
25the rest of the library or invasive macros.
26
27
28## Error-handling
29
30Most functions in BoringSSL may fail, either due to allocation failures or input
31errors. Functions which return an `int` typically return one on success and zero
32on failure. Functions which return a pointer typically return `NULL` on failure.
33However, due to legacy constraints, some functions are more complex. Consult the
34API documentation before using a function.
35
36On error, most functions also push errors on the error queue, an `errno`-like
37mechanism. See the documentation for
38[err.h](https://commondatastorage.googleapis.com/chromium-boringssl-docs/err.h.html)
39for more details.
40
41As with `errno`, callers must test the function's return value, not the error
42queue to determine whether an operation failed. Some codepaths may not interact
43with the error queue, and the error queue may have state from a previous failed
44operation.
45
46When ignoring a failed operation, it is recommended to call `ERR_clear_error` to
47avoid the state interacting with future operations. Failing to do so should not
48affect the actual behavior of any functions, but may result in errors from both
49operations being mixed in error logging. We hope to
50[improve](https://bugs.chromium.org/p/boringssl/issues/detail?id=38) this
51situation in the future.
52
53Where possible, avoid conditioning on specific reason codes and limit usage to
54logging. The reason codes are very specific and may change over time.
55
56
57## Memory allocation
58
59BoringSSL allocates memory via `OPENSSL_malloc`, found in `mem.h`. Use
60`OPENSSL_free`, found in the same header file, to release it. BoringSSL
61functions will fail gracefully on allocation error, but it is recommended to use
62a `malloc` implementation that `abort`s on failure.
63
64
65## Object initialization and cleanup
66
67BoringSSL defines a number of structs for use in its APIs. It is a C library,
68so the caller is responsible for ensuring these structs are properly
69initialized and released. Consult the documentation for a module for the
70proper use of its types. Some general conventions are listed below.
71
72
73### Heap-allocated types
74
75Some types, such as `RSA`, are heap-allocated. All instances will be allocated
76and returned from BoringSSL's APIs. It is an error to instantiate a heap-
77allocated type on the stack or embedded within another object.
78
79Heap-allocated types may have functioned named like `RSA_new` which allocates a
80fresh blank `RSA`. Other functions may also return newly-allocated instances.
81For example, `RSA_parse_public_key` is documented to return a newly-allocated
82`RSA` object.
83
84Heap-allocated objects must be released by the corresponding free function,
85named like `RSA_free`. Like C's `free` and C++'s `delete`, all free functions
86internally check for `NULL`. Consumers are not required to check for `NULL`
87before calling.
88
89A heap-allocated type may be reference-counted. In this case, a function named
90like `RSA_up_ref` will be available to take an additional reference count. The
91free function must be called to decrement the reference count. It will only
92release resources when the final reference is released. For OpenSSL
93compatibility, these functions return `int`, but callers may assume they always
94successfully return one because reference counts use saturating arithmetic.
95
96C++ consumers are recommended to use `bssl::UniquePtr` to manage heap-allocated
97objects. `bssl::UniquePtr<T>`, like other types, is forward-declared in
98`openssl/base.h`. Code that needs access to the free functions, such as code
99which destroys a `bssl::UniquePtr`, must include the corresponding module's
100header. (This matches `std::unique_ptr`'s relationship with forward
101declarations.)
102
103
104### Stack-allocated types
105
106Other types in BoringSSL are stack-allocated, such as `EVP_MD_CTX`. These
107types may be allocated on the stack or embedded within another object.
108However, they must still be initialized before use.
109
110Every stack-allocated object in BoringSSL has a *zero state*, analogous to
111initializing a pointer to `NULL`. In this state, the object may not be
112completely initialized, but it is safe to call cleanup functions. Entering the
113zero state cannot fail. (It is usually `memset(0)`.)
114
115The function to enter the zero state is named like `EVP_MD_CTX_init` or
116`CBB_zero` and will always return `void`. To release resources associated with
117the type, call the cleanup function, named like `EVP_MD_CTX_cleanup`. The
118cleanup function must be called on all codepaths, regardless of success or
119failure. For example:
120
121    uint8_t md[EVP_MAX_MD_SIZE];
122    unsigned md_len;
123    EVP_MD_CTX ctx;
124    EVP_MD_CTX_init(&ctx);  /* Enter the zero state. */
125    int ok = EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL) &&
126             EVP_DigestUpdate(&ctx, "hello ", 6) &&
127             EVP_DigestUpdate(&ctx, "world", 5) &&
128             EVP_DigestFinal_ex(&ctx, md, &md_len);
129    EVP_MD_CTX_cleanup(&ctx);  /* Release |ctx|. */
130
131Note that `EVP_MD_CTX_cleanup` is called whether or not the `EVP_Digest*`
132operations succeeded. More complex C functions may use the `goto err` pattern:
133
134      int ret = 0;
135      EVP_MD_CTX ctx;
136      EVP_MD_CTX_init(&ctx);
137
138      if (!some_other_operation()) {
139        goto err;
140      }
141
142      uint8_t md[EVP_MAX_MD_SIZE];
143      unsigned md_len;
144      if (!EVP_DigestInit_ex(&ctx, EVP_sha256(), NULL) ||
145          !EVP_DigestUpdate(&ctx, "hello ", 6) ||
146          !EVP_DigestUpdate(&ctx, "world", 5) ||
147          !EVP_DigestFinal_ex(&ctx, md, &md_len) {
148        goto err;
149      }
150
151      ret = 1;
152
153    err:
154      EVP_MD_CTX_cleanup(&ctx);
155      return ret;
156
157Note that, because `ctx` is set to the zero state before any failures,
158`EVP_MD_CTX_cleanup` is safe to call even if the first operation fails before
159`EVP_DigestInit_ex`. However, it would be illegal to move the `EVP_MD_CTX_init`
160below the `some_other_operation` call.
161
162As a rule of thumb, enter the zero state of stack-allocated structs in the
163same place they are declared.
164
165C++ consumers are recommended to use the wrappers named like
166`bssl::ScopedEVP_MD_CTX`, defined in the corresponding module's header. These
167wrappers are automatically initialized to the zero state and are automatically
168cleaned up.
169
170
171### Data-only types
172
173A few types, such as `SHA_CTX`, are data-only types and do not require cleanup.
174These are usually for low-level cryptographic operations. These types may be
175used freely without special cleanup conventions.
176
177
178## Thread safety
179
180BoringSSL is internally aware of the platform threading library and calls into
181it as needed. Consult the API documentation for the threading guarantees of
182particular objects. In general, stateless reference-counted objects like `RSA`
183or `EVP_PKEY` which represent keys may typically be used from multiple threads
184simultaneously, provided no thread mutates the key.
185