blob: 28800bfe7d1764a04a688b6419bddc7675147141 [file] [log] [blame]
Soby Mathewb4c6df42022-11-09 11:13:29 +00001.. SPDX-License-Identifier: BSD-3-Clause
2.. SPDX-FileCopyrightText: Copyright TF-RMM Contributors.
3
4Coding Standard
5===============
6
7This document describes the coding rules to follow to contribute to the project.
8
9General
10-------
11
12The following coding standard is derived from `MISRA C:2012 Guidelines`_,
13`TF-A coding style`_ and `Linux kernel coding style`_ coding standards.
14
15File Encoding
16-------------
17
18The source code must use the **UTF-8** character encoding. Comments and
19documentation may use non-ASCII characters when required (e.g. Greek letters
20used for units) but code itself is still limited to ASCII characters.
21
22Language
23--------
24
25The primary language for comments and naming must be International English. In
26cases where there is a conflict between the American English and British English
27spellings of a word, the American English spelling is used.
28
29Exceptions are made when referring directly to something that does not use
30international style, such as the name of a company. In these cases the existing
31name should be used as-is.
32
33C Language Standard
34-------------------
35
36The C language mode used for |RMM| is *GNU11*. This is the "GNU dialect of ISO
37C11", which implies the *ISO C11* standard with GNU extensions.
38
39Both GCC and Clang compilers have support for *GNU11* mode, though
40Clang does lack support for a small number of GNU extensions. These
41missing extensions are rarely used, however, and should not pose a problem.
42
43Length
44------
45
46- Each file, function and scopes should have a logical uniting theme.
47
48 No length limit is set for a file.
49
50- A function should be 24 lines maximum.
51
52 This will not be enforced, any function being longer should trigger a
53 discussion during the review process.
54
Soby Mathew01f03142023-11-24 14:12:37 +000055- The recommended maximum line length is 80 characters, except for string literals
56 as it would make any search for it more difficult. A maximum length of 100
57 characters is enforced by the coding guidelines static check.
Soby Mathewb4c6df42022-11-09 11:13:29 +000058
59- A variable should not be longer than 31 characters.
60
61 Although the `C11 specification`_ specifies that the number of signitificant
62 characters in an identifier is implementation defined it sets the translation
63 limit to the 31 initial characters.
64
65+--------------+-----------------------------------+
66| TYPE | LIMIT |
67+==============+===================================+
68| function | 24 lines (not enforced) |
69+--------------+-----------------------------------+
Soby Mathew01f03142023-11-24 14:12:37 +000070| line | 100 characters |
Soby Mathewb4c6df42022-11-09 11:13:29 +000071+--------------+-----------------------------------+
72| identifier | 31 characters |
73+--------------+-----------------------------------+
74
75
76Headers/Footers
77---------------
78
79- Include guards:
80
81.. code:: c
82
83 #ifndef FILE_NAME_H
84 #define FILE_NAME_H
85
86 <header content>
87
88 #endif /* FILE_NAME_H */
89
90- Include statement variant is <>:
91
92.. code:: c
93
94 #include <file.h>
95
96
97- Include files should be alphabetically ordered:
98
99.. code:: c
100
101 #include <axxxx.h>
102 #include <bxxxx.h>
103 [...]
104 #include <zxxxx.h>
105
106- If possible, use forward declaration of struct types in public headers.
107 This will reduce interdependence of header file inclusion.
108
109.. code:: c
110
111 #include <axxxx.h>
112 #include <bxxxx.h>
113 [...]
114 /* forward declaration */
115 struct x;
116 void foo(struct *x);
117
118
119Naming conventions
120------------------
121
122- Case:
123 Functions and variables must be in Snake Case
124
125.. code:: c
126
127 unsigned int my_snake_case_variable = 0U;
128
129 void my_snake_case_function(void)
130 {
131 [...]
132 }
133
134
135- Local variables should be declared at the top of the closest opening scope
136 and should be short.
137
138 We won't enforce a length, and defining short is difficult, this motto
139 (from Linux) catches the spirit
140
141 +---------------------------------------------------------------------------+
142 | LOCAL variable names should be short, and to the point. |
143 | |
144 | If you have some random integer loop counter, |
145 | it should probably be called i. |
146 | |
147 | Calling it loop_counter is non-productive, |
148 | if there is no chance of it being mis-understood. |
149 | |
150 | Similarly, tmp can be just about any type of variable that is |
151 | used to hold a temporary value. |
152 | |
153 | If you are afraid to mix up your local variable names, |
154 | you have another problem. |
155 +---------------------------------------------------------------------------+
156
157.. code:: c
158
159 int foo(const int a)
160 {
161 int c; /* needed in the function */
162 c = a; /* MISRA-C rules recommend to not modify arguments variables */
163
164 if (c == 42) {
165 int b; /* needed only in this "if" statment */
166
167 b = bar(); /* bar will return an int */
168 if (b != -1) {
169 c += b;
170 }
171 }
172 return c;
173 }
174
175- Use an appropraite prefix for public API of a component. For example,
176 if the component name is `bar`, then the init API of the component
177 should be called `bar_init()`.
178
179Indentation
180-----------
181
182Use **tabs** for indentation. The use of spaces for indentation is forbidden
183except in the case where a term is being indented to a boundary that cannot be
184achieved using tabs alone.
185
186Tab spacing should be set to **8 characters**.
187
188Trailing whitespaces or tabulations are not allowed and must be trimmed.
189
190Spacing
191-------
192
193Single spacing should be used around most operators, including:
194
195- Arithmetic operators (``+``, ``-``, ``/``, ``*``, ``%``)
196- Assignment operators (``=``, ``+=``, etc)
197- Boolean operators (``&&``, ``||``)
198- Comparison operators (``<``, ``>``, ``==``, etc)
199- Shift operators (``>>``, ``<<``)
200- Logical operators (``&``, ``|``, etc)
201- Flow control (``if``, ``else``, ``switch``, ``while``, ``return``, etc)
202
203No spacing should be used around the following operators
204
205- Cast (``()``)
206- Indirection (``*``)
207
208Braces
209------
210
211- Use K&R style for statements.
212
213- Function opening braces are on a new line.
214
215- Use braces even for singled line.
216
217
218.. code:: c
219
220 void function(void)
221 {
222 /* if statement */
223 if (my_test) {
224 do_this();
225 do_that();
226 }
227
228 /* if/else statement */
229 if (my_Test) {
230 do_this();
231 do_that();
232 } else {
233 do_other_this();
234 }
235 }
236
237Commenting
238----------
239
240Double-slash style of comments (//) is not allowed, below are examples of
241correct commenting.
242
243.. code:: c
244
245 /*
246 * This example illustrates the first allowed style for multi-line comments.
247 *
248 * Blank lines within multi-lines are allowed when they add clarity or when
249 * they separate multiple contexts.
250 */
251
252.. code:: c
253
254 /**************************************************************************
255 * This is the second allowed style for multi-line comments.
256 *
257 * In this style, the first and last lines use asterisks that run the full
258 * width of the comment at its widest point.
259 *
260 * This style can be used for additional emphasis.
261 *************************************************************************/
262
263.. code:: c
264
265 /* Single line comments can use this format */
266
267.. code:: c
268
269 /***************************************************************************
270 * This alternative single-line comment style can also be used for emphasis.
271 **************************************************************************/
272
273
274Error return values and Exception handling
275------------------------------------------
276
277- Function return type must be explicitly defined.
278
279- Unless specifed otherwise by an official specification, return values must be
280 used to return success or failure (Standard Posix error codes).
281
282 Return an integer if the function is an action or imperative command
283 Failure: -Exxx (STD posix error codes, unless specified otherwise)
284
285 Success: 0
286
287 Return a boolean if the function is as predicate
288 Failure: false
289
290 Success: true
291
292- If a function returns error information, then that error information shall
293 be tested.
294
295 Exceptions are allowed for STDLIB functions (memcpy/printf/...) in which case
296 it must be void casted.
297
298.. code:: c
299
300 #define MY_TRANSFORMED_ERROR (-1)
301
302 void my_print_function(struct my_struct in_mystruct)
303 {
304 long long transformed_a = my_transform_a(in_mystruct.a);
305
306 if (transform_a != MY_TRANSFORMED_ERROR) {
307 (void)printf("STRUCT\n\tfield(a): %ll\n", transformed_a);
308 } else {
309 (void)printf("STRUCT\n\tERROR %ll\n", transformed_a);
310 }
311 }
312
313
314Use of asserts and panic
315------------------------
316
317Assertions, as a general rule, are only used to catch errors during
318development cycles and are removed from production binaries. They are
319useful to document pre-conditions for a function or impossible conditions
320in code. They are not substitutes for proper error checking and any
321expression used to test an assertion must not have a side-effect.
322
323For example,
324
325.. code:: c
326
327 assert(--i == 0);
328
329should not be used in code.
330
331Assertions can be used to validate input arguments to an API as long as
332the caller and callee are within the same trust boundary.
333
334``panic()`` is used in places wherein it is not possible to continue the
335execution of program sensibly. It should be used sparingly within code
336and, if possible, instead of panic(), components should return error
337back to the caller and the caller can decide on the appropriate action.
338This is particularly useful to build resilence to the program wherein
339non-functional part of the program can be disabled and, if possible,
340other functional aspects of the program can be kept running.
341
342Using COMPILER_ASSERT to check for compile time data errors
343-----------------------------------------------------------
344
345Where possible, use the ``COMPILER_ASSERT`` macro to check the validity of
346data known at compile time instead of checking validity at runtime, to avoid
347unnecessary runtime code.
348
349For example, this can be used to check that the assembler's and compiler's views
350of the size of an array is the same.
351
352.. code:: c
353
354 #include <utils_def.h>
355
356 define MY_STRUCT_SIZE 8 /* Used by assembler source files */
357
358 struct my_struct {
359 uint32_t arg1;
360 uint32_t arg2;
361 };
362
363 COMPILER_ASSERT(MY_STRUCT_SIZE == sizeof(struct my_struct));
364
365
366If ``MY_STRUCT_SIZE`` in the above example were wrong then the compiler would
367emit an error like this:
368
369::
370
371 my_struct.h:10:1: note: in expansion of macro 'COMPILER_ASSERT'
372 10 | COMPILER_ASSERT(MY_STRUCT_SIZE == sizeof(struct my_struct));
373 | ^~~~~~~~~~~~~~~
374
375Data types, structures and typedefs
376-----------------------------------
377
378- Data Types:
379
380The |RMM| codebase should be kept as portable as possible for 64-bits platforms.
381To help with this, the following data type usage guidelines should be followed:
382
383- Where possible, use the built-in *C* data types for variable storage (for
384 example, ``char``, ``int``, ``long long``, etc) instead of the standard *C11*
385 types. Most code is typically only concerned with the minimum size of the
386 data stored, which the built-in *C* types guarantee.
387
388- Avoid using the exact-size standard *C11* types in general (for example,
389 ``uint16_t``, ``uint32_t``, ``uint64_t``, etc) since they can prevent the
390 compiler from making optimizations. There are legitimate uses for them,
391 for example to represent data of a known structure. When using them in a
392 structure definition, consider how padding in the structure will work across
393 architectures.
394
395- Use ``int`` as the default integer type - it's likely to be the fastest on all
396 systems. Also this can be assumed to be 32-bit as a consequence of the
397 `Procedure Call Standard for the Arm 64-bit Architecture`_ .
398
399- Avoid use of ``short`` as this may end up being slower than ``int`` in some
400 systems. If a variable must be exactly 16-bit, use ``int16_t`` or
401 ``uint16_t``.
402
403- ``long`` are defined as LP64 (64-bit), this is guaranteed to be 64-bit.
404
405- Use ``char`` for storing text. Use ``uint8_t`` for storing other 8-bit data.
406
407- Use ``unsigned`` for integers that can never be negative (counts,
408 indices, sizes, etc). |RMM| intends to comply with MISRA "essential type"
409 coding rules (10.X), where signed and unsigned types are considered different
410 essential types. Choosing the correct type will aid this. MISRA static
411 analysers will pick up any implicit signed/unsigned conversions that may lead
412 to unexpected behaviour.
413
414- For pointer types:
415
416 - If an argument in a function declaration is pointing to a known type then
417 simply use a pointer to that type (for example: ``struct my_struct *``).
418
419 - If a variable (including an argument in a function declaration) is pointing
420 to a general, memory-mapped address, an array of pointers or another
421 structure that is likely to require pointer arithmetic then use
422 ``uintptr_t``. This will reduce the amount of casting required in the code.
Soby Mathew86693432023-05-11 16:04:26 +0100423 Avoid using ``unsigned long`` or ``unsigned long long`` for this purpose;
424 it may work but is less portable.
Soby Mathewb4c6df42022-11-09 11:13:29 +0000425
Soby Mathew86693432023-05-11 16:04:26 +0100426 - Use of ``void *`` is generally discouraged. Although it is useful to
427 represent pointers to types that are abstracted away from the callers and
428 has useful implicit cast properties, for the sake of a more uniform code
429 base, we encourage use of ``uintptr_t`` where possible.
Soby Mathewb4c6df42022-11-09 11:13:29 +0000430
431 - Avoid pointer arithmetic generally (as this violates MISRA C 2012 rule
432 18.4) and especially on void pointers (as this is only supported via
433 language extensions and is considered non-standard). In |RMM|, setting the
434 ``W`` build flag to ``W=3`` enables the *-Wpointer-arith* compiler flag and
435 this will emit warnings where pointer arithmetic is used.
436
437 - Use ``ptrdiff_t`` to compare the difference between 2 pointers.
438
439- Use ``size_t`` when storing the ``sizeof()`` something.
440
Soby Mathew86693432023-05-11 16:04:26 +0100441- Use ``ssize_t`` when returning the ``sizeof()`` something from a function
442 that can also return an error code; the signed type allows for a negative
443 return code in case of error. This practice should be used sparingly.
Soby Mathewb4c6df42022-11-09 11:13:29 +0000444
Soby Mathew86693432023-05-11 16:04:26 +0100445- Use ``uint64_t`` to store the contents of an AArch64 register or
446 represent a 64-bit value. Use of ``unsigned long`` or ``u_register_t``
447 for these purposes is discouraged.
Soby Mathewb4c6df42022-11-09 11:13:29 +0000448
449These guidelines should be updated if additional types are needed.
450
451- Typedefs:
452
453Typedef should be avoided and used only to create opaque types.
454An opaque data type is one whose concrete data structure is not publicly
455defined. Opaque data types can be used on handles to resources that the caller
456is not expected to address directly.
457
458.. code:: c
459
460 /* File main.c */
461 #include <my_lib.h>
462
463 int main(void)
464 {
465 context_t *context;
466 int res;
467
468 context = my_lib_init();
469
470 res = my_lib_compute(context, "2x2");
471 if (res == -EMYLIB_ERROR) {
472 return -1
473 }
474
475 return res;
476 }
477
478.. code:: c
479
480 /* File my_lib.h */
481 #ifndef MY_LIB_H
482 #define MY_LIB_H
483
484 typedef struct my_lib_context {
485 [...] /* whatever internal private variables you need in my_lib */
486 } context_t;
487
488 #endif /* MY_LIB_H */
489
490Macros and Enums
491----------------
492
493- Favor functions over macros.
494
495- Preprocessor macros and enums values are written in all uppercase text.
496
497- A numerical value shall be typed.
498
499.. code:: c
500
501 /* Common C usage​ */
502 #define MY_MACRO 4UL
503
504 /* If used in C and ASM (included from a .S file)​ */
505 #define MY_MACRO UL(4)
506
507- Expressions resulting from the expansion of macro parameters must be enclosed
508 in parentheses.
509
510- A macro parameter immediately following a # operator mustn't be immediately
511 followed by a ## operator.
512
513.. code:: c
514
515 #define SINGLE_HASH_OP(x) (#x) /* allowed */
516 #define SINGLE_DOUBLE_HASH_OP(x, y) (x ## y) /* allowed */
517 #define MIXED_HASH_OP(x, y) (#x ## y) /* not allowed */
518
519- Avoid defining macros that affect the control flow (i.e. avoid using
520 return/goto in a macro).
521
522- Macro with multiple statements can be enclosed in a do-while block or in a
523 expression statement.
524
525.. code:: c
526
527 int foo(char **b);
528
529 #define M1(a, b) \
530 do { \
531 if ((a) == 5) { \
532 foo((b)); \
533 } \
534 } while (false)
535
536 #define M2(a, b) \
537 ({ \
538 if ((a) == 5) { \
539 foo((b)); \
540 } \
541 })
542
543 int foo(char **b)
544 {
545 return 42;
546 }
547
548 int main(int ac, char **av)
549 {
550 if (ac == 1) {
551 M1(ac, av);
552 } else if (ac == 2) {
553 M2(ac, av);
554 } else {
555 return -1;
556 }
557
558 return ac;
559 }
560
561Switch statements
562-----------------
563
564- Return in a *case* are allowed.
565
566- Fallthrough are allowed as long as they are commented.
567
568- Do not rely on type promotion between the switch type and the case type.
569
570Inline assembly
571---------------
572
573- Favor C language over assembly language.
574
575- Document all usage of assembly.
576
577- Do not mix C and ASM in the same file.
578
579Libc functions that are banned or to be used with caution
580---------------------------------------------------------
581
582Below is a list of functions that present security risks.
583
584+------------------------+--------------------------------------+
585| libc function | Comments |
586+========================+======================================+
587| ``strcpy, wcscpy``, | use strlcpy instead |
588| ``strncpy`` | |
589+------------------------+--------------------------------------+
590| ``strcat, wcscat``, | use strlcat instead |
591| ``strncat`` | |
592+------------------------+--------------------------------------+
593| ``sprintf, vsprintf`` | use snprintf, vsnprintf |
594| | instead |
595+------------------------+--------------------------------------+
596| ``snprintf`` | if used, ensure result fits in buffer|
597| | i.e : snprintf(buf,size...) < size |
598+------------------------+--------------------------------------+
599| ``vsnprintf`` | if used, inspect va_list match types |
600| | specified in format string |
601+------------------------+--------------------------------------+
602| ``strtok, strtok_r``, | Should not be used |
603| ``strsep`` | |
604+------------------------+--------------------------------------+
605| ``ato*`` | Should not be used |
606+------------------------+--------------------------------------+
607| ``*toa`` | Should not be used |
608+------------------------+--------------------------------------+
609
610The use of above functions are discouraged and will only be allowed
611in justified cases after a discussion has been held either on the mailing
612list or during patch review and it is agreed that no alternative to their
613use is available. The code containing the banned APIs must properly justify
614their usage in the comments.
615
616The above restriction does not apply to Third Party IP code inside the ``ext/``
617directory.
618
619-----------
620
621.. _`Procedure Call Standard for the Arm 64-bit Architecture`: https://developer.arm.com/docs/ihi0055/latest/
622.. _`Linux kernel coding style`: https://www.kernel.org/doc/html/latest/process/coding-style.html
623.. _`MISRA C:2012 Guidelines`: https://www.misra.org.uk/Activities/MISRAC/tabid/160/Default.aspx
624.. _`TF-A coding style`: https://trustedfirmware-a.readthedocs.io/en/latest/process/coding-style.html
625.. _`C11 specification`: https://en.wikipedia.org/wiki/C11_(C_standard_revision)