coding-guidelines.rst 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  1. Coding Guidelines
  2. =================
  3. This document provides some additional guidelines to consider when writing
  4. |TF-A| code. These are not intended to be strictly-enforced rules like the
  5. contents of the :ref:`Coding Style`.
  6. Automatic Editor Configuration
  7. ------------------------------
  8. Many of the rules given below (such as indentation size, use of tabs, and
  9. newlines) can be set automatically using the `EditorConfig`_ configuration file
  10. in the root of the repository: ``.editorconfig``. With a supported editor, the
  11. rules set out in this file can be automatically applied when you are editing
  12. files in the |TF-A| repository.
  13. Several editors include built-in support for EditorConfig files, and many others
  14. support its functionality through plugins.
  15. Use of the EditorConfig file is suggested but is not required.
  16. .. _automatic-compliance-checking:
  17. Automatic Compliance Checking
  18. -----------------------------
  19. To assist with coding style compliance, the project Makefile contains two
  20. targets which both utilise the `checkpatch.pl` script that ships with the Linux
  21. source tree. The project also defines certain *checkpatch* options in the
  22. ``.checkpatch.conf`` file in the top-level directory.
  23. .. note::
  24. Checkpatch errors will gate upstream merging of pull requests.
  25. Checkpatch warnings will not gate merging but should be reviewed and fixed if
  26. possible.
  27. To check the entire source tree, you must first download copies of
  28. ``checkpatch.pl``, ``spelling.txt`` and ``const_structs.checkpatch`` available
  29. in the `Linux master tree`_ *scripts* directory, then set the ``CHECKPATCH``
  30. environment variable to point to ``checkpatch.pl`` (with the other 2 files in
  31. the same directory) and build the `checkcodebase` target:
  32. .. code:: shell
  33. make CHECKPATCH=<path-to-linux>/linux/scripts/checkpatch.pl checkcodebase
  34. To just check the style on the files that differ between your local branch and
  35. the remote master, use:
  36. .. code:: shell
  37. make CHECKPATCH=<path-to-linux>/linux/scripts/checkpatch.pl checkpatch
  38. If you wish to check your patch against something other than the remote master,
  39. set the ``BASE_COMMIT`` variable to your desired branch. By default,
  40. ``BASE_COMMIT`` is set to ``origin/master``.
  41. Ignored Checkpatch Warnings
  42. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  43. Some checkpatch warnings in the TF codebase are deliberately ignored. These
  44. include:
  45. - ``**WARNING: line over 80 characters**``: Although the codebase should
  46. generally conform to the 80 character limit this is overly restrictive in some
  47. cases.
  48. - ``**WARNING: Use of volatile is usually wrong``: see
  49. `Why the “volatile” type class should not be used`_ . Although this document
  50. contains some very useful information, there are several legimate uses of the
  51. volatile keyword within the TF codebase.
  52. Performance considerations
  53. --------------------------
  54. Avoid printf and use logging macros
  55. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  56. ``debug.h`` provides logging macros (for example, ``WARN`` and ``ERROR``)
  57. which wrap ``tf_log`` and which allow the logging call to be compiled-out
  58. depending on the ``make`` command. Use these macros to avoid print statements
  59. being compiled unconditionally into the binary.
  60. Each logging macro has a numerical log level:
  61. .. code:: c
  62. #define LOG_LEVEL_NONE 0
  63. #define LOG_LEVEL_ERROR 10
  64. #define LOG_LEVEL_NOTICE 20
  65. #define LOG_LEVEL_WARNING 30
  66. #define LOG_LEVEL_INFO 40
  67. #define LOG_LEVEL_VERBOSE 50
  68. By default, all logging statements with a log level ``<= LOG_LEVEL_INFO`` will
  69. be compiled into debug builds and all statements with a log level
  70. ``<= LOG_LEVEL_NOTICE`` will be compiled into release builds. This can be
  71. overridden from the command line or by the platform makefile (although it may be
  72. necessary to clean the build directory first).
  73. For example, to enable ``VERBOSE`` logging on FVP:
  74. .. code:: shell
  75. make PLAT=fvp LOG_LEVEL=50 all
  76. Use const data where possible
  77. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  78. For example, the following code:
  79. .. code:: c
  80. struct my_struct {
  81. int arg1;
  82. int arg2;
  83. };
  84. void init(struct my_struct *ptr);
  85. void main(void)
  86. {
  87. struct my_struct x;
  88. x.arg1 = 1;
  89. x.arg2 = 2;
  90. init(&x);
  91. }
  92. is better written as:
  93. .. code:: c
  94. struct my_struct {
  95. int arg1;
  96. int arg2;
  97. };
  98. void init(const struct my_struct *ptr);
  99. void main(void)
  100. {
  101. const struct my_struct x = { 1, 2 };
  102. init(&x);
  103. }
  104. This allows the linker to put the data in a read-only data section instead of a
  105. writeable data section, which may result in a smaller and faster binary. Note
  106. that this may require dependent functions (``init()`` in the above example) to
  107. have ``const`` arguments, assuming they don't need to modify the data.
  108. Libc functions that are banned or to be used with caution
  109. ---------------------------------------------------------
  110. Below is a list of functions that present security risks and either must not be
  111. used (Banned) or are discouraged from use and must be used with care (Caution).
  112. +------------------------+-----------+--------------------------------------+
  113. | libc function | Status | Comments |
  114. +========================+===========+======================================+
  115. | ``strcpy, wcscpy``, | Banned | use strlcpy instead |
  116. | ``strncpy`` | | |
  117. +------------------------+-----------+--------------------------------------+
  118. | ``strcat, wcscat``, | Banned | use strlcat instead |
  119. | ``strncat`` | | |
  120. +------------------------+-----------+--------------------------------------+
  121. | ``sprintf, vsprintf`` | Banned | use snprintf, vsnprintf |
  122. | | | instead |
  123. +------------------------+-----------+--------------------------------------+
  124. | ``snprintf`` | Caution | ensure result fits in buffer |
  125. | | | i.e : snprintf(buf,size...) < size |
  126. +------------------------+-----------+--------------------------------------+
  127. | ``vsnprintf`` | Caution | inspect va_list match types |
  128. | | | specified in format string |
  129. +------------------------+-----------+--------------------------------------+
  130. | ``strtok`` | Banned | use strtok_r or strsep instead |
  131. +------------------------+-----------+--------------------------------------+
  132. | ``strtok_r, strsep`` | Caution | inspect for terminated input buffer |
  133. +------------------------+-----------+--------------------------------------+
  134. | ``ato*`` | Banned | use equivalent strto* functions |
  135. +------------------------+-----------+--------------------------------------+
  136. | ``*toa`` | Banned | Use snprintf instead |
  137. +------------------------+-----------+--------------------------------------+
  138. The `libc` component in the codebase will not add support for the banned APIs.
  139. Error handling and robustness
  140. -----------------------------
  141. Using CASSERT to check for compile time data errors
  142. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  143. Where possible, use the ``CASSERT`` macro to check the validity of data known at
  144. compile time instead of checking validity at runtime, to avoid unnecessary
  145. runtime code.
  146. For example, this can be used to check that the assembler's and compiler's views
  147. of the size of an array is the same.
  148. .. code:: c
  149. #include <cassert.h>
  150. define MY_STRUCT_SIZE 8 /* Used by assembler source files */
  151. struct my_struct {
  152. uint32_t arg1;
  153. uint32_t arg2;
  154. };
  155. CASSERT(MY_STRUCT_SIZE == sizeof(struct my_struct), assert_my_struct_size_mismatch);
  156. If ``MY_STRUCT_SIZE`` in the above example were wrong then the compiler would
  157. emit an error like this:
  158. ::
  159. my_struct.h:10:1: error: size of array ‘assert_my_struct_size_mismatch’ is negative
  160. Using assert() to check for programming errors
  161. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  162. In general, each secure world TF image (BL1, BL2, BL31 and BL32) should be
  163. treated as a tightly integrated package; the image builder should be aware of
  164. and responsible for all functionality within the image, even if code within that
  165. image is provided by multiple entities. This allows us to be more aggressive in
  166. interpreting invalid state or bad function arguments as programming errors using
  167. ``assert()``, including arguments passed across platform porting interfaces.
  168. This is in contrast to code in a Linux environment, which is less tightly
  169. integrated and may attempt to be more defensive by passing the error back up the
  170. call stack.
  171. Where possible, badly written TF code should fail early using ``assert()``. This
  172. helps reduce the amount of untested conditional code. By default these
  173. statements are not compiled into release builds, although this can be overridden
  174. using the ``ENABLE_ASSERTIONS`` build flag.
  175. Examples:
  176. - Bad argument supplied to library function
  177. - Bad argument provided by platform porting function
  178. - Internal secure world image state is inconsistent
  179. Handling integration errors
  180. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  181. Each secure world image may be provided by a different entity (for example, a
  182. Trusted Boot vendor may provide the BL2 image, a TEE vendor may provide the BL32
  183. image and the OEM/SoC vendor may provide the other images).
  184. An image may contain bugs that are only visible when the images are integrated.
  185. The system integrator may not even have access to the debug variants of all the
  186. images in order to check if asserts are firing. For example, the release variant
  187. of BL1 may have already been burnt into the SoC. Therefore, TF code that detects
  188. an integration error should _not_ consider this a programming error, and should
  189. always take action, even in release builds.
  190. If an integration error is considered non-critical it should be treated as a
  191. recoverable error. If the error is considered critical it should be treated as
  192. an unexpected unrecoverable error.
  193. Handling recoverable errors
  194. ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  195. The secure world **must not** crash when supplied with bad data from an external
  196. source. For example, data from the normal world or a hardware device. Similarly,
  197. the secure world **must not** crash if it detects a non-critical problem within
  198. itself or the system. It must make every effort to recover from the problem by
  199. emitting a ``WARN`` message, performing any necessary error handling and
  200. continuing.
  201. Examples:
  202. - Secure world receives SMC from normal world with bad arguments.
  203. - Secure world receives SMC from normal world at an unexpected time.
  204. - BL31 receives SMC from BL32 with bad arguments.
  205. - BL31 receives SMC from BL32 at unexpected time.
  206. - Secure world receives recoverable error from hardware device. Retrying the
  207. operation may help here.
  208. - Non-critical secure world service is not functioning correctly.
  209. - BL31 SPD discovers minor configuration problem with corresponding SP.
  210. Handling unrecoverable errors
  211. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  212. In some cases it may not be possible for the secure world to recover from an
  213. error. This situation should be handled in one of the following ways:
  214. 1. If the unrecoverable error is unexpected then emit an ``ERROR`` message and
  215. call ``panic()``. This will end up calling the platform-specific function
  216. ``plat_panic_handler()``.
  217. 2. If the unrecoverable error is expected to occur in certain circumstances,
  218. then emit an ``ERROR`` message and call the platform-specific function
  219. ``plat_error_handler()``.
  220. Cases 1 and 2 are subtly different. A platform may implement
  221. ``plat_panic_handler`` and ``plat_error_handler`` in the same way (for example,
  222. by waiting for a secure watchdog to time-out or by invoking an interface on the
  223. platform's power controller to reset the platform). However,
  224. ``plat_error_handler`` may take additional action for some errors (for example,
  225. it may set a flag so the platform resets into a different mode). Also,
  226. ``plat_panic_handler()`` may implement additional debug functionality (for
  227. example, invoking a hardware breakpoint).
  228. Examples of unexpected unrecoverable errors:
  229. - BL32 receives an unexpected SMC response from BL31 that it is unable to
  230. recover from.
  231. - BL31 Trusted OS SPD code discovers that BL2 has not loaded the corresponding
  232. Trusted OS, which is critical for platform operation.
  233. - Secure world discovers that a critical hardware device is an unexpected and
  234. unrecoverable state.
  235. - Secure world receives an unexpected and unrecoverable error from a critical
  236. hardware device.
  237. - Secure world discovers that it is running on unsupported hardware.
  238. Examples of expected unrecoverable errors:
  239. - BL1/BL2 fails to load the next image due to missing/corrupt firmware on disk.
  240. - BL1/BL2 fails to authenticate the next image due to an invalid certificate.
  241. - Secure world continuously receives recoverable errors from a hardware device
  242. but is unable to proceed without a valid response.
  243. Handling critical unresponsiveness
  244. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  245. If the secure world is waiting for a response from an external source (for
  246. example, the normal world or a hardware device) which is critical for continued
  247. operation, it must not wait indefinitely. It must have a mechanism (for example,
  248. a secure watchdog) for resetting itself and/or the external source to prevent
  249. the system from executing in this state indefinitely.
  250. Examples:
  251. - BL1 is waiting for the normal world to raise an SMC to proceed to the next
  252. stage of the secure firmware update process.
  253. - A Trusted OS is waiting for a response from a proxy in the normal world that
  254. is critical for continued operation.
  255. - Secure world is waiting for a hardware response that is critical for continued
  256. operation.
  257. Use of built-in *C* and *libc* data types
  258. -----------------------------------------
  259. The |TF-A| codebase should be kept as portable as possible, especially since
  260. both 64-bit and 32-bit platforms are supported. To help with this, the following
  261. data type usage guidelines should be followed:
  262. - Where possible, use the built-in *C* data types for variable storage (for
  263. example, ``char``, ``int``, ``long long``, etc) instead of the standard *C99*
  264. types. Most code is typically only concerned with the minimum size of the
  265. data stored, which the built-in *C* types guarantee.
  266. - Avoid using the exact-size standard *C99* types in general (for example,
  267. ``uint16_t``, ``uint32_t``, ``uint64_t``, etc) since they can prevent the
  268. compiler from making optimizations. There are legitimate uses for them,
  269. for example to represent data of a known structure. When using them in struct
  270. definitions, consider how padding in the struct will work across architectures.
  271. For example, extra padding may be introduced in |AArch32| systems if a struct
  272. member crosses a 32-bit boundary.
  273. - Use ``int`` as the default integer type - it's likely to be the fastest on all
  274. systems. Also this can be assumed to be 32-bit as a consequence of the
  275. `Procedure Call Standard for the Arm Architecture`_ and the `Procedure Call
  276. Standard for the Arm 64-bit Architecture`_ .
  277. - Avoid use of ``short`` as this may end up being slower than ``int`` in some
  278. systems. If a variable must be exactly 16-bit, use ``int16_t`` or
  279. ``uint16_t``.
  280. - Avoid use of ``long``. This is guaranteed to be at least 32-bit but, given
  281. that `int` is 32-bit on Arm platforms, there is no use for it. For integers of
  282. at least 64-bit, use ``long long``.
  283. - Use ``char`` for storing text. Use ``uint8_t`` for storing other 8-bit data.
  284. - Use ``unsigned`` for integers that can never be negative (counts,
  285. indices, sizes, etc). TF intends to comply with MISRA "essential type" coding
  286. rules (10.X), where signed and unsigned types are considered different
  287. essential types. Choosing the correct type will aid this. MISRA static
  288. analysers will pick up any implicit signed/unsigned conversions that may lead
  289. to unexpected behaviour.
  290. - For pointer types:
  291. - If an argument in a function declaration is pointing to a known type then
  292. simply use a pointer to that type (for example: ``struct my_struct *``).
  293. - If a variable (including an argument in a function declaration) is pointing
  294. to a general, memory-mapped address, an array of pointers or another
  295. structure that is likely to require pointer arithmetic then use
  296. ``uintptr_t``. This will reduce the amount of casting required in the code.
  297. Avoid using ``unsigned long`` or ``unsigned long long`` for this purpose; it
  298. may work but is less portable.
  299. - For other pointer arguments in a function declaration, use ``void *``. This
  300. includes pointers to types that are abstracted away from the known API and
  301. pointers to arbitrary data. This allows the calling function to pass a
  302. pointer argument to the function without any explicit casting (the cast to
  303. ``void *`` is implicit). The function implementation can then do the
  304. appropriate casting to a specific type.
  305. - Avoid pointer arithmetic generally (as this violates MISRA C 2012 rule
  306. 18.4) and especially on void pointers (as this is only supported via
  307. language extensions and is considered non-standard). In TF-A, setting the
  308. ``W`` build flag to ``W=3`` enables the *-Wpointer-arith* compiler flag and
  309. this will emit warnings where pointer arithmetic is used.
  310. - Use ``ptrdiff_t`` to compare the difference between 2 pointers.
  311. - Use ``size_t`` when storing the ``sizeof()`` something.
  312. - Use ``ssize_t`` when returning the ``sizeof()`` something from a function that
  313. can also return an error code; the signed type allows for a negative return
  314. code in case of error. This practice should be used sparingly.
  315. - Use ``u_register_t`` when it's important to store the contents of a register
  316. in its native size (32-bit in |AArch32| and 64-bit in |AArch64|). This is not a
  317. standard *C99* type but is widely available in libc implementations,
  318. including the FreeBSD version included with the TF codebase. Where possible,
  319. cast the variable to a more appropriate type before interpreting the data. For
  320. example, the following struct in ``ep_info.h`` could use this type to minimize
  321. the storage required for the set of registers:
  322. .. code:: c
  323. typedef struct aapcs64_params {
  324. u_register_t arg0;
  325. u_register_t arg1;
  326. u_register_t arg2;
  327. u_register_t arg3;
  328. u_register_t arg4;
  329. u_register_t arg5;
  330. u_register_t arg6;
  331. u_register_t arg7;
  332. } aapcs64_params_t;
  333. If some code wants to operate on ``arg0`` and knows that it represents a 32-bit
  334. unsigned integer on all systems, cast it to ``unsigned int``.
  335. These guidelines should be updated if additional types are needed.
  336. Favor C language over assembly language
  337. ---------------------------------------
  338. Generally, prefer code written in C over assembly. Assembly code is less
  339. portable, harder to understand, maintain and audit security wise. Also, static
  340. analysis tools generally don't analyze assembly code.
  341. If specific system-level instructions must be used (like cache maintenance
  342. operations), please consider using inline assembly. The ``arch_helpers.h`` files
  343. already define inline functions for a lot of these.
  344. There are, however, legitimate uses of assembly language. These are usually
  345. early boot (eg. cpu reset sequences) and exception handling code before the C
  346. runtime environment is set up.
  347. When writing assembly please note that a wide variety of common instruction
  348. sequences have helper macros in ``asm_macros.S`` which are preferred over
  349. writing them directly. This is especially important for debugging purposes as
  350. debug symbols must manually be included. Please use the ``func_prologue`` and
  351. ``func_epilogue`` macros if you need to use the stack. Also, obeying the
  352. Procedure Call Standard (PCS) is generally recommended.
  353. Do not use weak functions
  354. -------------------------
  355. .. note::
  356. The following guideline applies more strongly to common, platform-independent
  357. code. For plaform code (under ``plat/`` directory), it is up to each platform
  358. maintainer to decide whether this should be striclty enforced or not.
  359. The use of weak functions is highly discouraged in the TF-A codebase. Newly
  360. introduced platform interfaces should be strongly defined, wherever possible. In
  361. the rare cases where this is not possible or where weak functions appear as the
  362. best tool to solve the problem at hand, this should be discussed with the
  363. project's maintainers and justified in the code.
  364. For the purpose of providing a default implementation of a platform interface,
  365. an alternative to weak functions is to provide a strongly-defined implementation
  366. under the ``plat/common/`` directory. Then platforms have two options to pull
  367. in this implementation:
  368. - They can include the source file through the platform's makefile. Note that
  369. this method is suitable only if the platform wants *all* default
  370. implementations defined in this file, else either the file should be
  371. refactored or the next approach should be used.
  372. - They access the platform interface through a **constant** function pointer.
  373. In both cases, what matters is that platforms include the default implementation
  374. as a conscious decision.
  375. .. rubric:: Rationale
  376. Weak functions may sound useful to simplify the initial porting effort to a
  377. new platform, such that one can quickly get the firmware to build and link,
  378. without implementing all platform interfaces from the beginning. For this
  379. reason, the TF-A project used to make heavy use of weak functions and there
  380. are still many outstanding usages of them across the code base today. We
  381. intend to convert them to strongly-defined functions over time.
  382. However, weak functions also have major drawbacks, which we consider
  383. outweighing their benefits. They can make it hard to identify which
  384. implementation gets built into the firmware, especially when using multiple
  385. levels of "weakness". This has resulted in bugs in the past.
  386. Weak functions are also forbidden by MISRA coding guidelines, which TF-A aims to
  387. comply with.
  388. --------------
  389. *Copyright (c) 2020 - 2023, Arm Limited and Contributors. All rights reserved.*
  390. .. _`Linux master tree`: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/
  391. .. _`Procedure Call Standard for the Arm Architecture`: https://github.com/ARM-software/abi-aa/blob/main/aapcs32/aapcs32.rst
  392. .. _`Procedure Call Standard for the Arm 64-bit Architecture`: https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst
  393. .. _`EditorConfig`: http://editorconfig.org/
  394. .. _`Why the “volatile” type class should not be used`: https://www.kernel.org/doc/html/latest/process/volatile-considered-harmful.html