1Coding Style & Guidelines 2========================= 3 4The following sections contain TF coding guidelines. They are continually 5evolving and should not be considered "set in stone". Feel free to question them 6and provide feedback. 7 8Some of the guidelines may also apply to other codebases. 9 10**Note:** the existing TF codebase does not necessarily comply with all the 11below guidelines but the intent is for it to do so eventually. 12 13Checkpatch overrides 14-------------------- 15 16Some checkpatch warnings in the TF codebase are deliberately ignored. These 17include: 18 19- ``**WARNING: line over 80 characters**``: Although the codebase should 20 generally conform to the 80 character limit this is overly restrictive in some 21 cases. 22 23- ``**WARNING: Use of volatile is usually wrong``: see 24 `Why the “volatile” type class should not be used`_ . Although this document 25 contains some very useful information, there are several legimate uses of the 26 volatile keyword within the TF codebase. 27 28Headers and inclusion 29--------------------- 30 31Header guards 32^^^^^^^^^^^^^ 33 34For a header file called "some_driver.h" the style used by the Trusted Firmware 35is: 36 37.. code:: c 38 39 #ifndef SOME_DRIVER_H 40 #define SOME_DRIVER_H 41 42 <header content> 43 44 #endif /* SOME_DRIVER_H */ 45 46Include statement ordering 47^^^^^^^^^^^^^^^^^^^^^^^^^^ 48 49All header files that are included by a source file must use the following, 50grouped ordering. This is to improve readability (by making it easier to quickly 51read through the list of headers) and maintainability. 52 53#. *System* includes: Header files from the standard *C* library, such as 54 ``stddef.h`` and ``string.h``. 55 56#. *Project* includes: Header files under the ``include/`` directory within TF 57 are *project* includes. 58 59#. *Platform* includes: Header files relating to a single, specific platform, 60 and which are located under the ``plat/<platform_name>`` directory within TF, 61 are *platform* includes. 62 63Within each group, ``#include`` statements must be in alphabetical order, 64taking both the file and directory names into account. 65 66Groups must be separated by a single blank line for clarity. 67 68The example below illustrates the ordering rules using some contrived header 69file names; this type of name reuse should be otherwise avoided. 70 71.. code:: c 72 73 #include <string.h> 74 75 #include <a_dir/example/a_header.h> 76 #include <a_dir/example/b_header.h> 77 #include <a_dir/test/a_header.h> 78 #include <b_dir/example/a_header.h> 79 80 #include "./a_header.h" 81 82Include statement variants 83^^^^^^^^^^^^^^^^^^^^^^^^^^ 84 85Two variants of the ``#include`` directive are acceptable in the TF codebase. 86Correct use of the two styles improves readability by suggesting the location 87of the included header and reducing ambiguity in cases where generic and 88platform-specific headers share a name. 89 90For header files that are in the same directory as the source file that is 91including them, use the ``"..."`` variant. 92 93For header files that are **not** in the same directory as the source file that 94is including them, use the ``<...>`` variant. 95 96Example (bl1_fwu.c): 97 98.. code:: c 99 100 #include <assert.h> 101 #include <errno.h> 102 #include <string.h> 103 104 #include "bl1_private.h" 105 106Platform include paths 107^^^^^^^^^^^^^^^^^^^^^^ 108 109Platforms are allowed to add more include paths to be passed to the compiler. 110The ``PLAT_INCLUDES`` variable is used for this purpose. This is needed in 111particular for the file ``platform_def.h``. 112 113Example: 114 115.. code:: c 116 117 PLAT_INCLUDES += -Iinclude/plat/myplat/include 118 119Types and typedefs 120------------------ 121 122Use of built-in *C* and *libc* data types 123^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 124 125The TF codebase should be kept as portable as possible, especially since both 12664-bit and 32-bit platforms are supported. To help with this, the following data 127type usage guidelines should be followed: 128 129- Where possible, use the built-in *C* data types for variable storage (for 130 example, ``char``, ``int``, ``long long``, etc) instead of the standard *C99* 131 types. Most code is typically only concerned with the minimum size of the 132 data stored, which the built-in *C* types guarantee. 133 134- Avoid using the exact-size standard *C99* types in general (for example, 135 ``uint16_t``, ``uint32_t``, ``uint64_t``, etc) since they can prevent the 136 compiler from making optimizations. There are legitimate uses for them, 137 for example to represent data of a known structure. When using them in struct 138 definitions, consider how padding in the struct will work across architectures. 139 For example, extra padding may be introduced in AArch32 systems if a struct 140 member crosses a 32-bit boundary. 141 142- Use ``int`` as the default integer type - it's likely to be the fastest on all 143 systems. Also this can be assumed to be 32-bit as a consequence of the 144 `Procedure Call Standard for the Arm Architecture`_ and the `Procedure Call 145 Standard for the Arm 64-bit Architecture`_ . 146 147- Avoid use of ``short`` as this may end up being slower than ``int`` in some 148 systems. If a variable must be exactly 16-bit, use ``int16_t`` or 149 ``uint16_t``. 150 151- Avoid use of ``long``. This is guaranteed to be at least 32-bit but, given 152 that `int` is 32-bit on Arm platforms, there is no use for it. For integers of 153 at least 64-bit, use ``long long``. 154 155- Use ``char`` for storing text. Use ``uint8_t`` for storing other 8-bit data. 156 157- Use ``unsigned`` for integers that can never be negative (counts, 158 indices, sizes, etc). TF intends to comply with MISRA "essential type" coding 159 rules (10.X), where signed and unsigned types are considered different 160 essential types. Choosing the correct type will aid this. MISRA static 161 analysers will pick up any implicit signed/unsigned conversions that may lead 162 to unexpected behaviour. 163 164- For pointer types: 165 166 - If an argument in a function declaration is pointing to a known type then 167 simply use a pointer to that type (for example: ``struct my_struct *``). 168 169 - If a variable (including an argument in a function declaration) is pointing 170 to a general, memory-mapped address, an array of pointers or another 171 structure that is likely to require pointer arithmetic then use 172 ``uintptr_t``. This will reduce the amount of casting required in the code. 173 Avoid using ``unsigned long`` or ``unsigned long long`` for this purpose; it 174 may work but is less portable. 175 176 - For other pointer arguments in a function declaration, use ``void *``. This 177 includes pointers to types that are abstracted away from the known API and 178 pointers to arbitrary data. This allows the calling function to pass a 179 pointer argument to the function without any explicit casting (the cast to 180 ``void *`` is implicit). The function implementation can then do the 181 appropriate casting to a specific type. 182 183 - Use ``ptrdiff_t`` to compare the difference between 2 pointers. 184 185- Use ``size_t`` when storing the ``sizeof()`` something. 186 187- Use ``ssize_t`` when returning the ``sizeof()`` something from a function that 188 can also return an error code; the signed type allows for a negative return 189 code in case of error. This practice should be used sparingly. 190 191- Use ``u_register_t`` when it's important to store the contents of a register 192 in its native size (32-bit in AArch32 and 64-bit in AArch64). This is not a 193 standard *C99* type but is widely available in libc implementations, 194 including the FreeBSD version included with the TF codebase. Where possible, 195 cast the variable to a more appropriate type before interpreting the data. For 196 example, the following struct in ``ep_info.h`` could use this type to minimize 197 the storage required for the set of registers: 198 199.. code:: c 200 201 typedef struct aapcs64_params { 202 u_register_t arg0; 203 u_register_t arg1; 204 u_register_t arg2; 205 u_register_t arg3; 206 u_register_t arg4; 207 u_register_t arg5; 208 u_register_t arg6; 209 u_register_t arg7; 210 } aapcs64_params_t; 211 212If some code wants to operate on ``arg0`` and knows that it represents a 32-bit 213unsigned integer on all systems, cast it to ``unsigned int``. 214 215These guidelines should be updated if additional types are needed. 216 217Avoid anonymous typedefs of structs/enums in headers 218^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 219 220For example, the following definition: 221 222.. code:: c 223 224 typedef struct { 225 int arg1; 226 int arg2; 227 } my_struct_t; 228 229 230is better written as: 231 232.. code:: c 233 234 struct my_struct { 235 int arg1; 236 int arg2; 237 }; 238 239This allows function declarations in other header files that depend on the 240struct/enum to forward declare the struct/enum instead of including the 241entire header: 242 243.. code:: c 244 245 #include <my_struct.h> 246 void my_func(my_struct_t *arg); 247 248instead of: 249 250.. code:: c 251 252 struct my_struct; 253 void my_func(struct my_struct *arg); 254 255Some TF definitions use both a struct/enum name **and** a typedef name. This 256is discouraged for new definitions as it makes it difficult for TF to comply 257with MISRA rule 8.3, which states that "All declarations of an object or 258function shall use the same names and type qualifiers". 259 260The Linux coding standards also discourage new typedefs and checkpatch emits 261a warning for this. 262 263Existing typedefs will be retained for compatibility. 264 265Error handling and robustness 266----------------------------- 267 268Using CASSERT to check for compile time data errors 269^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 270 271Where possible, use the ``CASSERT`` macro to check the validity of data known at 272compile time instead of checking validity at runtime, to avoid unnecessary 273runtime code. 274 275For example, this can be used to check that the assembler's and compiler's views 276of the size of an array is the same. 277 278.. code:: c 279 280 #include <cassert.h> 281 282 define MY_STRUCT_SIZE 8 /* Used by assembler source files */ 283 284 struct my_struct { 285 uint32_t arg1; 286 uint32_t arg2; 287 }; 288 289 CASSERT(MY_STRUCT_SIZE == sizeof(struct my_struct), assert_my_struct_size_mismatch); 290 291 292If ``MY_STRUCT_SIZE`` in the above example were wrong then the compiler would 293emit an error like this: 294 295:: 296 297 my_struct.h:10:1: error: size of array ‘assert_my_struct_size_mismatch’ is negative 298 299 300Using assert() to check for programming errors 301^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 302 303In general, each secure world TF image (BL1, BL2, BL31 and BL32) should be 304treated as a tightly integrated package; the image builder should be aware of 305and responsible for all functionality within the image, even if code within that 306image is provided by multiple entities. This allows us to be more aggressive in 307interpreting invalid state or bad function arguments as programming errors using 308``assert()``, including arguments passed across platform porting interfaces. 309This is in contrast to code in a Linux environment, which is less tightly 310integrated and may attempt to be more defensive by passing the error back up the 311call stack. 312 313Where possible, badly written TF code should fail early using ``assert()``. This 314helps reduce the amount of untested conditional code. By default these 315statements are not compiled into release builds, although this can be overridden 316using the ``ENABLE_ASSERTIONS`` build flag. 317 318Examples: 319 320- Bad argument supplied to library function 321- Bad argument provided by platform porting function 322- Internal secure world image state is inconsistent 323 324 325Handling integration errors 326^^^^^^^^^^^^^^^^^^^^^^^^^^^ 327 328Each secure world image may be provided by a different entity (for example, a 329Trusted Boot vendor may provide the BL2 image, a TEE vendor may provide the BL32 330image and the OEM/SoC vendor may provide the other images). 331 332An image may contain bugs that are only visible when the images are integrated. 333The system integrator may not even have access to the debug variants of all the 334images in order to check if asserts are firing. For example, the release variant 335of BL1 may have already been burnt into the SoC. Therefore, TF code that detects 336an integration error should _not_ consider this a programming error, and should 337always take action, even in release builds. 338 339If an integration error is considered non-critical it should be treated as a 340recoverable error. If the error is considered critical it should be treated as 341an unexpected unrecoverable error. 342 343Handling recoverable errors 344^^^^^^^^^^^^^^^^^^^^^^^^^^^ 345 346The secure world **must not** crash when supplied with bad data from an external 347source. For example, data from the normal world or a hardware device. Similarly, 348the secure world **must not** crash if it detects a non-critical problem within 349itself or the system. It must make every effort to recover from the problem by 350emitting a ``WARN`` message, performing any necessary error handling and 351continuing. 352 353Examples: 354 355- Secure world receives SMC from normal world with bad arguments. 356- Secure world receives SMC from normal world at an unexpected time. 357- BL31 receives SMC from BL32 with bad arguments. 358- BL31 receives SMC from BL32 at unexpected time. 359- Secure world receives recoverable error from hardware device. Retrying the 360 operation may help here. 361- Non-critical secure world service is not functioning correctly. 362- BL31 SPD discovers minor configuration problem with corresponding SP. 363 364Handling unrecoverable errors 365^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 366 367In some cases it may not be possible for the secure world to recover from an 368error. This situation should be handled in one of the following ways: 369 3701. If the unrecoverable error is unexpected then emit an ``ERROR`` message and 371 call ``panic()``. This will end up calling the platform-specific function 372 ``plat_panic_handler()``. 3732. If the unrecoverable error is expected to occur in certain circumstances, 374 then emit an ``ERROR`` message and call the platform-specific function 375 ``plat_error_handler()``. 376 377Cases 1 and 2 are subtly different. A platform may implement ``plat_panic_handler`` 378and ``plat_error_handler`` in the same way (for example, by waiting for a secure 379watchdog to time-out or by invoking an interface on the platform's power 380controller to reset the platform). However, ``plat_error_handler`` may take 381additional action for some errors (for example, it may set a flag so the 382platform resets into a different mode). Also, ``plat_panic_handler()`` may 383implement additional debug functionality (for example, invoking a hardware 384breakpoint). 385 386Examples of unexpected unrecoverable errors: 387 388- BL32 receives an unexpected SMC response from BL31 that it is unable to 389 recover from. 390- BL31 Trusted OS SPD code discovers that BL2 has not loaded the corresponding 391 Trusted OS, which is critical for platform operation. 392- Secure world discovers that a critical hardware device is an unexpected and 393 unrecoverable state. 394- Secure world receives an unexpected and unrecoverable error from a critical 395 hardware device. 396- Secure world discovers that it is running on unsupported hardware. 397 398Examples of expected unrecoverable errors: 399 400- BL1/BL2 fails to load the next image due to missing/corrupt firmware on disk. 401- BL1/BL2 fails to authenticate the next image due to an invalid certificate. 402- Secure world continuously receives recoverable errors from a hardware device 403 but is unable to proceed without a valid response. 404 405Handling critical unresponsiveness 406^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 407 408If the secure world is waiting for a response from an external source (for 409example, the normal world or a hardware device) which is critical for continued 410operation, it must not wait indefinitely. It must have a mechanism (for example, 411a secure watchdog) for resetting itself and/or the external source to prevent 412the system from executing in this state indefinitely. 413 414Examples: 415 416- BL1 is waiting for the normal world to raise an SMC to proceed to the next 417 stage of the secure firmware update process. 418- A Trusted OS is waiting for a response from a proxy in the normal world that 419 is critical for continued operation. 420- Secure world is waiting for a hardware response that is critical for continued 421 operation. 422 423Security considerations 424----------------------- 425 426Part of the security of a platform is handling errors correctly, as described in 427the previous section. There are several other security considerations covered in 428this section. 429 430Do not leak secrets to the normal world 431^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 432 433The secure world **must not** leak secrets to the normal world, for example in 434response to an SMC. 435 436Handling Denial of Service attacks 437^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 438 439The secure world **should never** crash or become unusable due to receiving too 440many normal world requests (a *Denial of Service* or *DoS* attack). It should 441have a mechanism for throttling or ignoring normal world requests. 442 443Performance considerations 444-------------------------- 445 446Avoid printf and use logging macros 447^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 448 449``debug.h`` provides logging macros (for example, ``WARN`` and ``ERROR``) 450which wrap ``tf_log`` and which allow the logging call to be compiled-out 451depending on the ``make`` command. Use these macros to avoid print statements 452being compiled unconditionally into the binary. 453 454Each logging macro has a numerical log level: 455 456.. code:: c 457 458 #define LOG_LEVEL_NONE 0 459 #define LOG_LEVEL_ERROR 10 460 #define LOG_LEVEL_NOTICE 20 461 #define LOG_LEVEL_WARNING 30 462 #define LOG_LEVEL_INFO 40 463 #define LOG_LEVEL_VERBOSE 50 464 465 466By default, all logging statements with a log level ``<= LOG_LEVEL_INFO`` will 467be compiled into debug builds and all statements with a log level 468``<= LOG_LEVEL_NOTICE`` will be compiled into release builds. This can be 469overridden from the command line or by the platform makefile (although it may be 470necessary to clean the build directory first). For example, to enable 471``VERBOSE`` logging on FVP: 472 473``make PLAT=fvp LOG_LEVEL=50 all`` 474 475Use const data where possible 476^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 477 478For example, the following code: 479 480.. code:: c 481 482 struct my_struct { 483 int arg1; 484 int arg2; 485 }; 486 487 void init(struct my_struct *ptr); 488 489 void main(void) 490 { 491 struct my_struct x; 492 x.arg1 = 1; 493 x.arg2 = 2; 494 init(&x); 495 } 496 497is better written as: 498 499.. code:: c 500 501 struct my_struct { 502 int arg1; 503 int arg2; 504 }; 505 506 void init(const struct my_struct *ptr); 507 508 void main(void) 509 { 510 const struct my_struct x = { 1, 2 }; 511 init(&x); 512 } 513 514This allows the linker to put the data in a read-only data section instead of a 515writeable data section, which may result in a smaller and faster binary. Note 516that this may require dependent functions (``init()`` in the above example) to 517have ``const`` arguments, assuming they don't need to modify the data. 518 519Library and driver code 520----------------------- 521 522TF library code (under ``lib/`` and ``include/lib``) is any code that provides a 523reusable interface to other code, potentially even to code outside of TF. 524 525In some systems drivers must conform to a specific driver framework to provide 526services to the rest of the system. TF has no driver framework and the 527distinction between a driver and library is somewhat subjective. 528 529A driver (under ``drivers/`` and ``include/drivers/``) is defined as code that 530interfaces with hardware via a memory mapped interface. 531 532Some drivers (for example, the Arm CCI driver in ``include/drivers/arm/cci.h``) 533provide a general purpose API to that specific hardware. Other drivers (for 534example, the Arm PL011 console driver in ``drivers/arm/pl011/pl011_console.S``) 535provide a specific hardware implementation of a more abstract library API. In 536the latter case there may potentially be multiple drivers for the same hardware 537device. 538 539Neither libraries nor drivers should depend on platform-specific code. If they 540require platform-specific data (for example, a base address) to operate then 541they should provide an initialization function that takes the platform-specific 542data as arguments. 543 544TF common code (under ``common/`` and ``include/common/``) is code that is re-used 545by other generic (non-platform-specific) TF code. It is effectively internal 546library code. 547 548.. _`Why the “volatile” type class should not be used`: https://www.kernel.org/doc/html/latest/process/volatile-considered-harmful.html 549.. _`Procedure Call Standard for the Arm Architecture`: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0042f/IHI0042F_aapcs.pdf 550.. _`Procedure Call Standard for the Arm 64-bit Architecture`: http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055b/IHI0055B_aapcs64.pdf 551