coding-style.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. Coding Style
  2. ============
  3. The following sections outline the |TF-A| coding style for *C* code. The style
  4. is based on the `Linux kernel coding style`_, with a few modifications.
  5. The style should not be considered *set in stone*. Feel free to provide feedback
  6. and suggestions.
  7. .. note::
  8. You will almost certainly find code in the |TF-A| repository that does not
  9. follow the style. The intent is for all code to do so eventually.
  10. File Encoding
  11. -------------
  12. The source code must use the **UTF-8** character encoding. Comments and
  13. documentation may use non-ASCII characters when required (e.g. Greek letters
  14. used for units) but code itself is still limited to ASCII characters.
  15. Newlines must be in **Unix** style, which means that only the Line Feed (``LF``)
  16. character is used to break a line and reset to the first column.
  17. Language
  18. --------
  19. The primary language for comments and naming must be International English. In
  20. cases where there is a conflict between the American English and British English
  21. spellings of a word, the American English spelling is used.
  22. Exceptions are made when referring directly to something that does not use
  23. international style, such as the name of a company. In these cases the existing
  24. name should be used as-is.
  25. C Language Standard
  26. -------------------
  27. The C language mode used for TF-A is *GNU99*. This is the "GNU dialect of ISO
  28. C99", which implies the *ISO C99* standard with GNU extensions.
  29. Both GCC and Clang compiler toolchains have support for *GNU99* mode, though
  30. Clang does lack support for a small number of GNU extensions. These
  31. missing extensions are rarely used, however, and should not pose a problem.
  32. .. _misra-compliance:
  33. MISRA Compliance
  34. ----------------
  35. TF-A attempts to comply with the `MISRA C:2012 Guidelines`_. `ECLAIR` static
  36. analysis is used to regularly generate a report of current MISRA defects and to
  37. prevent the addition of new ones.
  38. It is not possible for the project to follow all MISRA guidelines. Table 1
  39. below lists all rules and directives and whether we aim to comply with them or
  40. not. A rationale is given for each deviation.
  41. .. note::
  42. Enforcing a rule does not mean that the codebase is free of defects
  43. of that rule, only that they would ideally be removed.
  44. .. note::
  45. Third-party libraries are not considered in our MISRA analysis and we do not
  46. intend to modify them to make them MISRA compliant.
  47. .. csv-table:: Table 1: MISRA compliance in TF-A code base
  48. :file: misra-compliance.csv
  49. Indentation
  50. -----------
  51. Use **tabs** for indentation. The use of spaces for indentation is forbidden
  52. except in the case where a term is being indented to a boundary that cannot be
  53. achieved using tabs alone.
  54. Tab spacing should be set to **8 characters**.
  55. Trailing whitespace is not allowed and must be trimmed.
  56. Spacing
  57. -------
  58. Single spacing should be used around most operators, including:
  59. - Arithmetic operators (``+``, ``-``, ``/``, ``*``)
  60. - Assignment operators (``=``, ``+=``, etc)
  61. - Boolean operators (``&&``, ``||``)
  62. - Comparison operators (``<``, ``>``, ``==``, etc)
  63. A space should also be used to separate parentheses and braces when they are not
  64. already separated by a newline, such as for the ``if`` statement in the
  65. following example:
  66. .. code:: c
  67. int function_foo(bool bar)
  68. {
  69. if (bar) {
  70. function_baz();
  71. }
  72. }
  73. Note that there is no space between the name of a function and the following
  74. parentheses.
  75. Control statements (``if``, ``for``, ``switch``, ``while``, etc) must be
  76. separated from the following open parenthesis by a single space. The previous
  77. example illustrates this for an ``if`` statement.
  78. Line Length
  79. -----------
  80. Line length *should* be at most **80 characters**. This limit does not include
  81. non-printing characters such as the line feed.
  82. This rule is a *should*, not a must, and it is acceptable to exceed the limit
  83. **slightly** where the readability of the code would otherwise be significantly
  84. reduced. Use your judgement in these cases.
  85. Blank Lines
  86. -----------
  87. Functions are usually separated by a single blank line. In certain cases it is
  88. acceptable to use additional blank lines for clarity, if required.
  89. The file must end with a single newline character. Many editors have the option
  90. to insert this automatically and to trim multiple blank lines at the end of the
  91. file.
  92. Braces
  93. ------
  94. Opening Brace Placement
  95. ^^^^^^^^^^^^^^^^^^^^^^^
  96. Braces follow the **Kernighan and Ritchie (K&R)** style, where the opening brace
  97. is **not** placed on a new line.
  98. Example for a ``while`` loop:
  99. .. code:: c
  100. while (condition) {
  101. foo();
  102. bar();
  103. }
  104. This style applies to all blocks except for functions which, following the Linux
  105. style, **do** place the opening brace on a new line.
  106. Example for a function:
  107. .. code:: c
  108. int my_function(void)
  109. {
  110. int a;
  111. a = 1;
  112. return a;
  113. }
  114. Conditional Statement Bodies
  115. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  116. Where conditional statements (such as ``if``, ``for``, ``while`` and ``do``) are
  117. used, braces must be placed around the statements that form the body of the
  118. conditional. This is the case regardless of the number of statements in the
  119. body.
  120. .. note::
  121. This is a notable departure from the Linux coding style that has been
  122. adopted to follow MISRA guidelines more closely and to help prevent errors.
  123. For example, use the following style:
  124. .. code:: c
  125. if (condition) {
  126. foo++;
  127. }
  128. instead of omitting the optional braces around a single statement:
  129. .. code:: c
  130. /* This is violating MISRA C 2012: Rule 15.6 */
  131. if (condition)
  132. foo++;
  133. The reason for this is to prevent accidental changes to control flow when
  134. modifying the body of the conditional. For example, at a quick glance it is easy
  135. to think that the value of ``bar`` is only incremented if ``condition``
  136. evaluates to ``true`` but this is not the case - ``bar`` will always be
  137. incremented regardless of the condition evaluation. If the developer forgets to
  138. add braces around the conditional body when adding the ``bar++;`` statement then
  139. the program execution will not proceed as intended.
  140. .. code:: c
  141. /* This is violating MISRA C 2012: Rule 15.6 */
  142. if (condition)
  143. foo++;
  144. bar++;
  145. Naming
  146. ------
  147. Functions
  148. ^^^^^^^^^
  149. Use lowercase for function names, separating multiple words with an underscore
  150. character (``_``). This is sometimes referred to as *Snake Case*. An example is
  151. given below:
  152. .. code:: c
  153. void bl2_arch_setup(void)
  154. {
  155. ...
  156. }
  157. Local Variables and Parameters
  158. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  159. Local variables and function parameters use the same format as function names:
  160. lowercase with underscore separation between multiple words. An example is
  161. given below:
  162. .. code:: c
  163. static void set_scr_el3_from_rm(uint32_t type,
  164. uint32_t interrupt_type_flags,
  165. uint32_t security_state)
  166. {
  167. uint32_t flag, bit_pos;
  168. ...
  169. }
  170. Preprocessor Macros
  171. ^^^^^^^^^^^^^^^^^^^
  172. Identifiers that are defined using preprocessor macros are written in all
  173. uppercase text.
  174. .. code:: c
  175. #define BUFFER_SIZE_BYTES 64
  176. Function Attributes
  177. -------------------
  178. Place any function attributes after the function type and before the function
  179. name.
  180. .. code:: c
  181. void __init plat_arm_interconnect_init(void);
  182. Alignment
  183. ---------
  184. Alignment should be performed primarily with tabs, adding spaces if required to
  185. achieve a granularity that is smaller than the tab size. For example, with a tab
  186. size of eight columns it would be necessary to use one tab character and two
  187. spaces to indent text by ten columns.
  188. Switch Statement Alignment
  189. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  190. When using ``switch`` statements, align each ``case`` statement with the
  191. ``switch`` so that they are in the same column.
  192. .. code:: c
  193. switch (condition) {
  194. case A:
  195. foo();
  196. case B:
  197. bar();
  198. default:
  199. baz();
  200. }
  201. Pointer Alignment
  202. ^^^^^^^^^^^^^^^^^
  203. The reference and dereference operators (ampersand and *pointer star*) must be
  204. aligned with the name of the object on which they are operating, as opposed to
  205. the type of the object.
  206. .. code:: c
  207. uint8_t *foo;
  208. foo = &bar;
  209. Comments
  210. --------
  211. The general rule for comments is that the double-slash style of comment (``//``)
  212. is not allowed. Examples of the allowed comment formats are shown below:
  213. .. code:: c
  214. /*
  215. * This example illustrates the first allowed style for multi-line comments.
  216. *
  217. * Blank lines within multi-lines are allowed when they add clarity or when
  218. * they separate multiple contexts.
  219. *
  220. */
  221. .. code:: c
  222. /**************************************************************************
  223. * This is the second allowed style for multi-line comments.
  224. *
  225. * In this style, the first and last lines use asterisks that run the full
  226. * width of the comment at its widest point.
  227. *
  228. * This style can be used for additional emphasis.
  229. *
  230. *************************************************************************/
  231. .. code:: c
  232. /* Single line comments can use this format */
  233. .. code:: c
  234. /***************************************************************************
  235. * This alternative single-line comment style can also be used for emphasis.
  236. **************************************************************************/
  237. Headers and inclusion
  238. ---------------------
  239. Header guards
  240. ^^^^^^^^^^^^^
  241. For a header file called "some_driver.h" the style used by |TF-A| is:
  242. .. code:: c
  243. #ifndef SOME_DRIVER_H
  244. #define SOME_DRIVER_H
  245. <header content>
  246. #endif /* SOME_DRIVER_H */
  247. Include statement ordering
  248. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  249. All header files that are included by a source file must use the following,
  250. grouped ordering. This is to improve readability (by making it easier to quickly
  251. read through the list of headers) and maintainability.
  252. #. *System* includes: Header files from the standard *C* library, such as
  253. ``stddef.h`` and ``string.h``.
  254. #. *Project* includes: Header files under the ``include/`` directory within
  255. |TF-A| are *project* includes.
  256. #. *Platform* includes: Header files relating to a single, specific platform,
  257. and which are located under the ``plat/<platform_name>`` directory within
  258. |TF-A|, are *platform* includes.
  259. Within each group, ``#include`` statements must be in alphabetical order,
  260. taking both the file and directory names into account.
  261. Groups must be separated by a single blank line for clarity.
  262. The example below illustrates the ordering rules using some contrived header
  263. file names; this type of name reuse should be otherwise avoided.
  264. .. code:: c
  265. #include <string.h>
  266. #include <a_dir/example/a_header.h>
  267. #include <a_dir/example/b_header.h>
  268. #include <a_dir/test/a_header.h>
  269. #include <b_dir/example/a_header.h>
  270. #include "a_header.h"
  271. The preferred approach for third-party headers is to include them immediately
  272. following system header files like in the example below, where the
  273. ``version.h`` header from the Mbed TLS library immediately follows the
  274. ``stddef.h`` system header.
  275. .. code:: c
  276. /* system header files */
  277. #include <stddef.h>
  278. /* Mbed TLS header files */
  279. #include <mbedtls/version.h>
  280. /* project header files */
  281. #include <drivers/auth/auth_mod.h>
  282. #include <drivers/auth/tbbr_cot_common.h>
  283. /* platform header files */
  284. #include <platform_def.h>
  285. Include statement variants
  286. ^^^^^^^^^^^^^^^^^^^^^^^^^^
  287. Two variants of the ``#include`` directive are acceptable in the |TF-A|
  288. codebase. Correct use of the two styles improves readability by suggesting the
  289. location of the included header and reducing ambiguity in cases where generic
  290. and platform-specific headers share a name.
  291. For header files that are in the same directory as the source file that is
  292. including them, use the ``"..."`` variant.
  293. For header files that are **not** in the same directory as the source file that
  294. is including them, use the ``<...>`` variant.
  295. Example (bl1_fwu.c):
  296. .. code:: c
  297. #include <assert.h>
  298. #include <errno.h>
  299. #include <string.h>
  300. #include "bl1_private.h"
  301. Typedefs
  302. --------
  303. Avoid anonymous typedefs of structs/enums in headers
  304. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  305. For example, the following definition:
  306. .. code:: c
  307. typedef struct {
  308. int arg1;
  309. int arg2;
  310. } my_struct_t;
  311. is better written as:
  312. .. code:: c
  313. struct my_struct {
  314. int arg1;
  315. int arg2;
  316. };
  317. This allows function declarations in other header files that depend on the
  318. struct/enum to forward declare the struct/enum instead of including the
  319. entire header:
  320. .. code:: c
  321. struct my_struct;
  322. void my_func(struct my_struct *arg);
  323. instead of:
  324. .. code:: c
  325. #include <my_struct.h>
  326. void my_func(my_struct_t *arg);
  327. Some TF definitions use both a struct/enum name **and** a typedef name. This
  328. is discouraged for new definitions as it makes it difficult for TF to comply
  329. with MISRA rule 8.3, which states that "All declarations of an object or
  330. function shall use the same names and type qualifiers".
  331. The Linux coding standards also discourage new typedefs and checkpatch emits
  332. a warning for this.
  333. Existing typedefs will be retained for compatibility.
  334. --------------
  335. *Copyright (c) 2020-2023, Arm Limited. All rights reserved.*
  336. .. _`Linux kernel coding style`: https://www.kernel.org/doc/html/latest/process/coding-style.html
  337. .. _`MISRA C:2012 Guidelines`: https://en.wikipedia.org/wiki/MISRA_C#MISRA_C:2012