Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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