| 1 | .. _coding-style: |
| 2 | |
| 3 | ================= |
| 4 | QEMU Coding Style |
| 5 | ================= |
| 6 | |
| 7 | .. contents:: Table of Contents |
| 8 | |
| 9 | Please use the script checkpatch.pl in the scripts directory to check |
| 10 | patches before submitting. |
| 11 | |
| 12 | Formatting and style |
| 13 | ******************** |
| 14 | |
| 15 | The repository includes a ``.editorconfig`` file which can help with |
| 16 | getting the right settings for your preferred $EDITOR. See |
| 17 | `<https://editorconfig.org/>`_ for details. |
| 18 | |
| 19 | Whitespace |
| 20 | ========== |
| 21 | |
| 22 | Of course, the most important aspect in any coding style is whitespace. |
| 23 | Crusty old coders who have trouble spotting the glasses on their noses |
| 24 | can tell the difference between a tab and eight spaces from a distance |
| 25 | of approximately fifteen parsecs. Many a flamewar has been fought and |
| 26 | lost on this issue. |
| 27 | |
| 28 | QEMU indents are four spaces. Tabs are never used, except in Makefiles |
| 29 | where they have been irreversibly coded into the syntax. |
| 30 | Spaces of course are superior to tabs because: |
| 31 | |
| 32 | * You have just one way to specify whitespace, not two. Ambiguity breeds |
| 33 | mistakes. |
| 34 | * The confusion surrounding 'use tabs to indent, spaces to justify' is gone. |
| 35 | * Tab indents push your code to the right, making your screen seriously |
| 36 | unbalanced. |
| 37 | * Tabs will be rendered incorrectly on editors who are misconfigured not |
| 38 | to use tab stops of eight positions. |
| 39 | * Tabs are rendered badly in patches, causing off-by-one errors in almost |
| 40 | every line. |
| 41 | * It is the QEMU coding style. |
| 42 | |
| 43 | Do not leave whitespace dangling off the ends of lines. |
| 44 | |
| 45 | Multiline Indent |
| 46 | ---------------- |
| 47 | |
| 48 | There are several places where indent is necessary: |
| 49 | |
| 50 | * if/else |
| 51 | * while/for |
| 52 | * function definition & call |
| 53 | |
| 54 | When breaking up a long line to fit within line width, we need a proper indent |
| 55 | for the following lines. |
| 56 | |
| 57 | In case of if/else, while/for, align the secondary lines just after the |
| 58 | opening parenthesis of the first. |
| 59 | |
| 60 | For example: |
| 61 | |
| 62 | .. code-block:: c |
| 63 | |
| 64 | if (a == 1 && |
| 65 | b == 2) { |
| 66 | |
| 67 | while (a == 1 && |
| 68 | b == 2) { |
| 69 | |
| 70 | In case of function, there are several variants: |
| 71 | |
| 72 | * 4 spaces indent from the beginning |
| 73 | * align the secondary lines just after the opening parenthesis of the first |
| 74 | |
| 75 | For example: |
| 76 | |
| 77 | .. code-block:: c |
| 78 | |
| 79 | do_something(x, y, |
| 80 | z); |
| 81 | |
| 82 | do_something(x, y, |
| 83 | z); |
| 84 | |
| 85 | do_something(x, do_another(y, |
| 86 | z)); |
| 87 | |
| 88 | Line width |
| 89 | ========== |
| 90 | |
| 91 | Lines should be 80 characters; try not to make them longer. |
| 92 | |
| 93 | Sometimes it is hard to do, especially when dealing with QEMU subsystems |
| 94 | that use long function or symbol names. If wrapping the line at 80 columns |
| 95 | is obviously less readable and more awkward, prefer not to wrap it; better |
| 96 | to have an 85 character line than one which is awkwardly wrapped. |
| 97 | |
| 98 | Even in that case, try not to make lines much longer than 80 characters. |
| 99 | (The checkpatch script will warn at 100 characters, but this is intended |
| 100 | as a guard against obviously-overlength lines, not a target.) |
| 101 | |
| 102 | Rationale: |
| 103 | |
| 104 | * Some people like to tile their 24" screens with a 6x4 matrix of 80x24 |
| 105 | xterms and use vi in all of them. The best way to punish them is to |
| 106 | let them keep doing it. |
| 107 | * Code and especially patches is much more readable if limited to a sane |
| 108 | line length. Eighty is traditional. |
| 109 | * The four-space indentation makes the most common excuse ("But look |
| 110 | at all that white space on the left!") moot. |
| 111 | * It is the QEMU coding style. |
| 112 | |
| 113 | Naming |
| 114 | ====== |
| 115 | |
| 116 | Variables are lower_case_with_underscores; easy to type and read. Structured |
| 117 | type names are in CamelCase; harder to type but standing out. Enum type |
| 118 | names and function type names should also be in CamelCase. Scalar type |
| 119 | names are lower_case_with_underscores_ending_with_a_t, like the POSIX |
| 120 | uint64_t and family. Note that this last convention contradicts POSIX |
| 121 | and is therefore likely to be changed. |
| 122 | |
| 123 | Variable Naming Conventions |
| 124 | --------------------------- |
| 125 | |
| 126 | A number of short naming conventions exist for variables that use |
| 127 | common QEMU types. For example, the architecture independent CPUState |
| 128 | is often held as a ``cs`` pointer variable, whereas the concrete |
| 129 | CPUArchState is usually held in a pointer called ``env``. |
| 130 | |
| 131 | Likewise, in device emulation code the common DeviceState is usually |
| 132 | called ``dev``. |
| 133 | |
| 134 | Function Naming Conventions |
| 135 | --------------------------- |
| 136 | |
| 137 | Wrapped version of standard library or GLib functions use a ``qemu_`` |
| 138 | prefix to alert readers that they are seeing a wrapped version, for |
| 139 | example ``qemu_strtol`` or ``qemu_mutex_lock``. Other utility functions |
| 140 | that are widely called from across the codebase should not have any |
| 141 | prefix, for example ``pstrcpy`` or bit manipulation functions such as |
| 142 | ``find_first_bit``. |
| 143 | |
| 144 | The ``qemu_`` prefix is also used for functions that modify global |
| 145 | emulator state, for example ``qemu_add_vm_change_state_handler``. |
| 146 | However, if there is an obvious subsystem-specific prefix it should be |
| 147 | used instead. |
| 148 | |
| 149 | Public functions from a file or subsystem (declared in headers) tend |
| 150 | to have a consistent prefix to show where they came from. For example, |
| 151 | ``tlb_`` for functions from ``cputlb.c`` or ``cpu_`` for functions |
| 152 | from cpus.c. |
| 153 | |
| 154 | If there are two versions of a function to be called with or without a |
| 155 | lock held, the function that expects the lock to be already held |
| 156 | usually uses the suffix ``_locked``. |
| 157 | |
| 158 | If a function is a shim designed to deal with compatibility |
| 159 | workarounds we use the suffix ``_compat``. These are generally not |
| 160 | called directly and aliased to the plain function name via the |
| 161 | pre-processor. Another common suffix is ``_impl``; it is used for the |
| 162 | concrete implementation of a function that will not be called |
| 163 | directly, but rather through a macro or an inline function. |
| 164 | |
| 165 | Block structure |
| 166 | =============== |
| 167 | |
| 168 | Every indented statement is braced; even if the block contains just one |
| 169 | statement. The opening brace is on the line that contains the control |
| 170 | flow statement that introduces the new block; the closing brace is on the |
| 171 | same line as the else keyword, or on a line by itself if there is no else |
| 172 | keyword. Example: |
| 173 | |
| 174 | .. code-block:: c |
| 175 | |
| 176 | if (a == 5) { |
| 177 | printf("a was 5.\n"); |
| 178 | } else if (a == 6) { |
| 179 | printf("a was 6.\n"); |
| 180 | } else { |
| 181 | printf("a was something else entirely.\n"); |
| 182 | } |
| 183 | |
| 184 | Note that 'else if' is considered a single statement; otherwise a long if/ |
| 185 | else if/else if/.../else sequence would need an indent for every else |
| 186 | statement. |
| 187 | |
| 188 | An exception is the opening brace for a function; for reasons of tradition |
| 189 | and clarity it comes on a line by itself: |
| 190 | |
| 191 | .. code-block:: c |
| 192 | |
| 193 | void a_function(void) |
| 194 | { |
| 195 | do_something(); |
| 196 | } |
| 197 | |
| 198 | Rationale: a consistent (except for functions...) bracing style reduces |
| 199 | ambiguity and avoids needless churn when lines are added or removed. |
| 200 | Furthermore, it is the QEMU coding style. |
| 201 | |
| 202 | Declarations |
| 203 | ============ |
| 204 | |
| 205 | Mixed declarations (interleaving statements and declarations within |
| 206 | blocks) are generally not allowed; declarations should be at the beginning |
| 207 | of blocks. To avoid accidental re-use it is permissible to declare |
| 208 | loop variables inside for loops: |
| 209 | |
| 210 | .. code-block:: c |
| 211 | |
| 212 | for (int i = 0; i < ARRAY_SIZE(thing); i++) { |
| 213 | /* do something loopy */ |
| 214 | } |
| 215 | |
| 216 | Every now and then, an exception is made for declarations inside a |
| 217 | #ifdef or #ifndef block: if the code looks nicer, such declarations can |
| 218 | be placed at the top of the block even if there are statements above. |
| 219 | On the other hand, however, it's often best to move that #ifdef/#ifndef |
| 220 | block to a separate function altogether. |
| 221 | |
| 222 | Conditional statements |
| 223 | ====================== |
| 224 | |
| 225 | When comparing a variable for (in)equality with a constant, list the |
| 226 | constant on the right, as in: |
| 227 | |
| 228 | .. code-block:: c |
| 229 | |
| 230 | if (a == 1) { |
| 231 | /* Reads like: "If a equals 1" */ |
| 232 | do_something(); |
| 233 | } |
| 234 | |
| 235 | Rationale: Yoda conditions (as in 'if (1 == a)') are awkward to read. |
| 236 | Besides, good compilers already warn users when '==' is mis-typed as '=', |
| 237 | even when the constant is on the right. |
| 238 | |
| 239 | Comment style |
| 240 | ============= |
| 241 | |
| 242 | We use traditional C-style /``*`` ``*``/ comments and avoid // comments. |
| 243 | |
| 244 | Rationale: The // form is valid in C99, so this is purely a matter of |
| 245 | consistency of style. The checkpatch script will warn you about this. |
| 246 | |
| 247 | Multiline comment blocks should have a row of stars on the left, |
| 248 | and the initial /``*`` and terminating ``*``/ both on their own lines: |
| 249 | |
| 250 | .. code-block:: c |
| 251 | |
| 252 | /* |
| 253 | * like |
| 254 | * this |
| 255 | */ |
| 256 | |
| 257 | This is the same format required by the Linux kernel coding style. |
| 258 | |
| 259 | (Some of the existing comments in the codebase use the GNU Coding |
| 260 | Standards form which does not have stars on the left, or other |
| 261 | variations; avoid these when writing new comments, but don't worry |
| 262 | about converting to the preferred form unless you're editing that |
| 263 | comment anyway.) |
| 264 | |
| 265 | Rationale: Consistency, and ease of visually picking out a multiline |
| 266 | comment from the surrounding code. |
| 267 | |
| 268 | Language usage |
| 269 | ************** |
| 270 | |
| 271 | Preprocessor |
| 272 | ============ |
| 273 | |
| 274 | Variadic macros |
| 275 | --------------- |
| 276 | |
| 277 | For variadic macros, stick with this C99-like syntax: |
| 278 | |
| 279 | .. code-block:: c |
| 280 | |
| 281 | #define DPRINTF(fmt, ...) \ |
| 282 | do { printf("IRQ: " fmt, ## __VA_ARGS__); } while (0) |
| 283 | |
| 284 | Include directives |
| 285 | ------------------ |
| 286 | |
| 287 | Order include directives as follows: |
| 288 | |
| 289 | .. code-block:: c |
| 290 | |
| 291 | #include "qemu/osdep.h" /* Always first... */ |
| 292 | #include <...> /* then system headers... */ |
| 293 | #include "..." /* and finally QEMU headers. */ |
| 294 | |
| 295 | The "qemu/osdep.h" header contains preprocessor macros that affect the behavior |
| 296 | of core system headers like <stdint.h>. It must be the first include so that |
| 297 | core system headers included by external libraries get the preprocessor macros |
| 298 | that QEMU depends on. |
| 299 | |
| 300 | Do not include "qemu/osdep.h" from header files since the .c file will have |
| 301 | already included it. |
| 302 | |
| 303 | Headers should normally include everything they need beyond osdep.h. |
| 304 | If exceptions are needed for some reason, they must be documented in |
| 305 | the header. If all that's needed from a header is typedefs, consider |
| 306 | putting those into qemu/typedefs.h instead of including the header. |
| 307 | |
| 308 | Cyclic inclusion is forbidden. |
| 309 | |
| 310 | Generative Includes |
| 311 | ------------------- |
| 312 | |
| 313 | QEMU makes fairly extensive use of the macro pre-processor to |
| 314 | instantiate multiple similar functions. While such abuse of the macro |
| 315 | processor isn't discouraged it can make debugging and code navigation |
| 316 | harder. You should consider carefully if the same effect can be |
| 317 | achieved by making it easy for the compiler to constant fold or using |
| 318 | python scripting to generate grep friendly code. |
| 319 | |
| 320 | If you do use template header files they should be named with the |
| 321 | ``.c.inc`` or ``.h.inc`` suffix to make it clear they are being |
| 322 | included for expansion. |
| 323 | |
| 324 | C types |
| 325 | ======= |
| 326 | |
| 327 | It should be common sense to use the right type, but we have collected |
| 328 | a few useful guidelines here. |
| 329 | |
| 330 | Scalars |
| 331 | ------- |
| 332 | |
| 333 | If you're using "int" or "long", odds are good that there's a better type. |
| 334 | If a variable is counting something, it should be declared with an |
| 335 | unsigned type. |
| 336 | |
| 337 | If it's host memory-size related, size_t should be a good choice (use |
| 338 | ssize_t only if required). Guest RAM memory offsets must use ram_addr_t, |
| 339 | but only for RAM, it may not cover whole guest address space. |
| 340 | |
| 341 | If it's file-size related, use off_t. |
| 342 | If it's file-offset related (i.e., signed), use off_t. |
| 343 | If it's just counting small numbers use "unsigned int"; |
| 344 | (on all but oddball embedded systems, you can assume that that |
| 345 | type is at least four bytes wide). |
| 346 | |
| 347 | In the event that you require a specific width, use a standard type |
| 348 | like int32_t, uint32_t, uint64_t, etc. The specific types are |
| 349 | mandatory for VMState fields. |
| 350 | |
| 351 | Don't use Linux kernel internal types like u32, __u32 or __le32. |
| 352 | |
| 353 | Use hwaddr for guest physical addresses except pcibus_t |
| 354 | for PCI addresses. In addition, ram_addr_t is a QEMU internal address |
| 355 | space that maps guest RAM physical addresses into an intermediate |
| 356 | address space that can map to host virtual address spaces. Generally |
| 357 | speaking, the size of guest memory can always fit into ram_addr_t but |
| 358 | it would not be correct to store an actual guest physical address in a |
| 359 | ram_addr_t. |
| 360 | |
| 361 | For CPU virtual addresses there are several possible types. |
| 362 | vaddr is the best type to use to hold a CPU virtual address in |
| 363 | target-independent code. It is guaranteed to be large enough to hold a |
| 364 | virtual address for any target, and it does not change size from target |
| 365 | to target. It is always unsigned. |
| 366 | target_ulong is a type the size of a virtual address on the CPU; this means |
| 367 | it may be 32 or 64 bits depending on which target is being built. It should |
| 368 | therefore be used only in target-specific code, and in some |
| 369 | performance-critical built-per-target core code such as the TLB code. |
| 370 | There is also a signed version, target_long. |
| 371 | abi_ulong is for the ``*``-user targets, and represents a type the size of |
| 372 | 'void ``*``' in that target's ABI. (This may not be the same as the size of a |
| 373 | full CPU virtual address in the case of target ABIs which use 32 bit pointers |
| 374 | on 64 bit CPUs, like sparc32plus.) Definitions of structures that must match |
| 375 | the target's ABI must use this type for anything that on the target is defined |
| 376 | to be an 'unsigned long' or a pointer type. |
| 377 | There is also a signed version, abi_long. |
| 378 | |
| 379 | Of course, take all of the above with a grain of salt. If you're about |
| 380 | to use some system interface that requires a type like size_t, pid_t or |
| 381 | off_t, use matching types for any corresponding variables. |
| 382 | |
| 383 | Also, if you try to use e.g., "unsigned int" as a type, and that |
| 384 | conflicts with the signedness of a related variable, sometimes |
| 385 | it's best just to use the *wrong* type, if "pulling the thread" |
| 386 | and fixing all related variables would be too invasive. |
| 387 | |
| 388 | Finally, while using descriptive types is important, be careful not to |
| 389 | go overboard. If whatever you're doing causes warnings, or requires |
| 390 | casts, then reconsider or ask for help. |
| 391 | |
| 392 | Pointers |
| 393 | -------- |
| 394 | |
| 395 | Ensure that all of your pointers are "const-correct". |
| 396 | Unless a pointer is used to modify the pointed-to storage, |
| 397 | give it the "const" attribute. That way, the reader knows |
| 398 | up-front that this is a read-only pointer. Perhaps more |
| 399 | importantly, if we're diligent about this, when you see a non-const |
| 400 | pointer, you're guaranteed that it is used to modify the storage |
| 401 | it points to, or it is aliased to another pointer that is. |
| 402 | |
| 403 | Typedefs |
| 404 | -------- |
| 405 | |
| 406 | Typedefs are used to eliminate the redundant 'struct' keyword, since type |
| 407 | names have a different style than other identifiers ("CamelCase" versus |
| 408 | "snake_case"). Each named struct type should have a CamelCase name and a |
| 409 | corresponding typedef. |
| 410 | |
| 411 | Since certain C compilers choke on duplicated typedefs, you should avoid |
| 412 | them and declare a typedef only in one header file. For common types, |
| 413 | you can use "include/qemu/typedefs.h" for example. However, as a matter |
| 414 | of convenience it is also perfectly fine to use forward struct |
| 415 | definitions instead of typedefs in headers and function prototypes; this |
| 416 | avoids problems with duplicated typedefs and reduces the need to include |
| 417 | headers from other headers. |
| 418 | |
| 419 | Bitfields |
| 420 | --------- |
| 421 | |
| 422 | C bitfields can be a cause of non-portability issues, especially under windows |
| 423 | where `MSVC has a different way to lay them out than GCC |
| 424 | <https://gcc.gnu.org/onlinedocs/gcc/x86-Type-Attributes.html>`_, or where |
| 425 | endianness matters. |
| 426 | |
| 427 | For this reason, we disallow usage of bitfields in packed structures and in any |
| 428 | structures which are supposed to exactly match a specific layout in guest |
| 429 | memory. Some existing code may use it, and we carefully ensured the layout was |
| 430 | the one expected. |
| 431 | |
| 432 | We also suggest avoiding bitfields even in structures where the exact |
| 433 | layout does not matter, unless you can show that they provide a significant |
| 434 | usability benefit. |
| 435 | |
| 436 | We encourage the usage of ``include/hw/core/registerfields.h`` as a safe replacement |
| 437 | for bitfields. |
| 438 | |
| 439 | Reserved namespaces in C and POSIX |
| 440 | ---------------------------------- |
| 441 | |
| 442 | Underscore capital, double underscore, and underscore 't' suffixes should be |
| 443 | avoided. |
| 444 | |
| 445 | Low level memory management |
| 446 | =========================== |
| 447 | |
| 448 | Use of the ``malloc/free/realloc/calloc/valloc/memalign/posix_memalign`` |
| 449 | or ``alloca/g_alloca/g_newa/g_newa0`` APIs is not allowed in the QEMU codebase. |
| 450 | Instead of these routines, use the GLib memory allocation routines |
| 451 | ``g_malloc/g_malloc0/g_new/g_new0/g_realloc/g_free`` |
| 452 | or QEMU's ``qemu_memalign/qemu_blockalign/qemu_vfree`` APIs. |
| 453 | |
| 454 | Please note that ``g_malloc`` will exit on allocation failure, so |
| 455 | there is no need to test for failure (as you would have to with |
| 456 | ``malloc``). Generally using ``g_malloc`` on start-up is fine as the |
| 457 | result of a failure to allocate memory is going to be a fatal exit |
| 458 | anyway. There may be some start-up cases where failing is unreasonable |
| 459 | (for example speculatively loading a large debug symbol table). |
| 460 | |
| 461 | Care should be taken to avoid introducing places where the guest could |
| 462 | trigger an exit by causing a large allocation. For small allocations, |
| 463 | of the order of 4k, a failure to allocate is likely indicative of an |
| 464 | overloaded host and allowing ``g_malloc`` to ``exit`` is a reasonable |
| 465 | approach. However for larger allocations where we could realistically |
| 466 | fall-back to a smaller one if need be we should use functions like |
| 467 | ``g_try_new`` and check the result. For example this is valid approach |
| 468 | for a time/space trade-off like ``tlb_mmu_resize_locked`` in the |
| 469 | SoftMMU TLB code. |
| 470 | |
| 471 | If the lifetime of the allocation is within the function and there are |
| 472 | multiple exit paths you can also improve the readability of the code |
| 473 | by using ``g_autofree`` and related annotations. See :ref:`autofree-ref` |
| 474 | for more details. |
| 475 | |
| 476 | Calling ``g_malloc`` with a zero size is valid and will return NULL. |
| 477 | |
| 478 | Prefer ``g_new(T, n)`` instead of ``g_malloc(sizeof(T) * n)`` for the following |
| 479 | reasons: |
| 480 | |
| 481 | * It catches multiplication overflowing size_t; |
| 482 | * It returns T ``*`` instead of void ``*``, letting compiler catch more type errors. |
| 483 | |
| 484 | Declarations like |
| 485 | |
| 486 | .. code-block:: c |
| 487 | |
| 488 | T *v = g_malloc(sizeof(*v)) |
| 489 | |
| 490 | are acceptable, though. |
| 491 | |
| 492 | Memory allocated by ``qemu_memalign`` or ``qemu_blockalign`` must be freed with |
| 493 | ``qemu_vfree``, since breaking this will cause problems on Win32. |
| 494 | |
| 495 | String manipulation |
| 496 | =================== |
| 497 | |
| 498 | Do not use the strncpy function. As mentioned in the man page, it does *not* |
| 499 | guarantee a NULL-terminated buffer, which makes it extremely dangerous to use. |
| 500 | It also zeros trailing destination bytes out to the specified length. Instead, |
| 501 | use this similar function when possible, but note its different signature: |
| 502 | |
| 503 | .. code-block:: c |
| 504 | |
| 505 | void pstrcpy(char *dest, int dest_buf_size, const char *src) |
| 506 | |
| 507 | Don't use strcat because it can't check for buffer overflows, but: |
| 508 | |
| 509 | .. code-block:: c |
| 510 | |
| 511 | char *pstrcat(char *buf, int buf_size, const char *s) |
| 512 | |
| 513 | The same limitation exists with sprintf and vsprintf, so use snprintf and |
| 514 | vsnprintf. |
| 515 | |
| 516 | QEMU provides other useful string functions: |
| 517 | |
| 518 | .. code-block:: c |
| 519 | |
| 520 | int strstart(const char *str, const char *val, const char **ptr) |
| 521 | int stristart(const char *str, const char *val, const char **ptr) |
| 522 | |
| 523 | There are also replacement character processing macros for isxyz and toxyz, |
| 524 | so instead of e.g. isalnum you should use qemu_isalnum. |
| 525 | |
| 526 | Because of the memory management rules, you must use g_strdup/g_strndup |
| 527 | instead of plain strdup/strndup. |
| 528 | |
| 529 | Printf-style functions |
| 530 | ====================== |
| 531 | |
| 532 | Whenever you add a new printf-style function, i.e., one with a format |
| 533 | string argument and following "..." in its prototype, be sure to use |
| 534 | gcc's printf attribute directive in the prototype. |
| 535 | |
| 536 | This makes it so gcc's -Wformat and -Wformat-security options can do |
| 537 | their jobs and cross-check format strings with the number and types |
| 538 | of arguments. |
| 539 | |
| 540 | C standard, implementation defined and undefined behaviors |
| 541 | ========================================================== |
| 542 | |
| 543 | C code in QEMU should be written to the C11 language specification. A |
| 544 | copy of the final version of the C11 standard formatted as a draft, |
| 545 | can be downloaded from: |
| 546 | |
| 547 | `<http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1548.pdf>`_ |
| 548 | |
| 549 | The C language specification defines regions of undefined behavior and |
| 550 | implementation defined behavior (to give compiler authors enough leeway to |
| 551 | produce better code). In general, code in QEMU should follow the language |
| 552 | specification and avoid both undefined and implementation defined |
| 553 | constructs. ("It works fine on the gcc I tested it with" is not a valid |
| 554 | argument...) However there are a few areas where we allow ourselves to |
| 555 | assume certain behaviors because in practice all the platforms we care about |
| 556 | behave in the same way and writing strictly conformant code would be |
| 557 | painful. These are: |
| 558 | |
| 559 | * you may assume that integers are 2s complement representation |
| 560 | * you may assume that right shift of a signed integer duplicates |
| 561 | the sign bit (ie it is an arithmetic shift, not a logical shift) |
| 562 | |
| 563 | In addition, QEMU assumes that the compiler does not use the latitude |
| 564 | given in C99 and C11 to treat aspects of signed '<<' as undefined, as |
| 565 | documented in the GNU Compiler Collection manual starting at version 4.0. |
| 566 | |
| 567 | .. _autofree-ref: |
| 568 | |
| 569 | Automatic memory deallocation |
| 570 | ============================= |
| 571 | |
| 572 | QEMU has a mandatory dependency on either the GCC or the Clang compiler. As |
| 573 | such it has the freedom to make use of a C language extension for |
| 574 | automatically running a cleanup function when a stack variable goes |
| 575 | out of scope. This can be used to simplify function cleanup paths, |
| 576 | often allowing many goto jumps to be eliminated, through automatic |
| 577 | free'ing of memory. |
| 578 | |
| 579 | The GLib2 library provides a number of functions/macros for enabling |
| 580 | automatic cleanup: |
| 581 | |
| 582 | `<https://developer.gnome.org/glib/stable/glib-Miscellaneous-Macros.html>`_ |
| 583 | |
| 584 | Most notably: |
| 585 | |
| 586 | * g_autofree - will invoke g_free() on the variable going out of scope |
| 587 | |
| 588 | * g_autoptr - for structs / objects, will invoke the cleanup func created |
| 589 | by a previous use of G_DEFINE_AUTOPTR_CLEANUP_FUNC. This is |
| 590 | supported for most GLib data types and GObjects |
| 591 | |
| 592 | For example, instead of |
| 593 | |
| 594 | .. code-block:: c |
| 595 | |
| 596 | int somefunc(void) |
| 597 | { |
| 598 | int ret = -1; |
| 599 | char *foo = g_strdup_printf("foo%", "wibble"); |
| 600 | GList *bar = ..... |
| 601 | |
| 602 | if (eek) { |
| 603 | goto cleanup; |
| 604 | } |
| 605 | |
| 606 | ret = 0; |
| 607 | |
| 608 | cleanup: |
| 609 | g_free(foo); |
| 610 | g_list_free(bar); |
| 611 | return ret; |
| 612 | } |
| 613 | |
| 614 | Using g_autofree/g_autoptr enables the code to be written as: |
| 615 | |
| 616 | .. code-block:: c |
| 617 | |
| 618 | int somefunc(void) |
| 619 | { |
| 620 | g_autofree char *foo = g_strdup_printf("foo%", "wibble"); |
| 621 | g_autoptr (GList) bar = ..... |
| 622 | |
| 623 | if (eek) { |
| 624 | return -1; |
| 625 | } |
| 626 | |
| 627 | return 0; |
| 628 | } |
| 629 | |
| 630 | While this generally results in simpler, less leak-prone code, there |
| 631 | are still some caveats to beware of |
| 632 | |
| 633 | * Variables declared with g_auto* MUST always be initialized, |
| 634 | otherwise the cleanup function will use uninitialized stack memory |
| 635 | |
| 636 | * If a variable declared with g_auto* holds a value which must |
| 637 | live beyond the life of the function, that value must be saved |
| 638 | and the original variable NULL'd out. This can be simpler using |
| 639 | g_steal_pointer |
| 640 | |
| 641 | |
| 642 | .. code-block:: c |
| 643 | |
| 644 | char *somefunc(void) |
| 645 | { |
| 646 | g_autofree char *foo = g_strdup_printf("foo%", "wibble"); |
| 647 | g_autoptr (GList) bar = ..... |
| 648 | |
| 649 | if (eek) { |
| 650 | return NULL; |
| 651 | } |
| 652 | |
| 653 | return g_steal_pointer(&foo); |
| 654 | } |
| 655 | |
| 656 | |
| 657 | QEMU Specific Idioms |
| 658 | ******************** |
| 659 | |
| 660 | QEMU Object Model Declarations |
| 661 | ============================== |
| 662 | |
| 663 | The QEMU Object Model (QOM) provides a framework for handling objects |
| 664 | in the base C language. The first declaration of a storage or class |
| 665 | structure should always be the parent and leave a visual space between |
| 666 | that declaration and the new code. It is also useful to separate |
| 667 | backing for properties (options driven by the user) and internal state |
| 668 | to make navigation easier. |
| 669 | |
| 670 | For a storage structure the first declaration should always be called |
| 671 | "parent_obj" and for a class structure the first member should always |
| 672 | be called "parent_class" as below: |
| 673 | |
| 674 | .. code-block:: c |
| 675 | |
| 676 | struct MyDeviceState { |
| 677 | DeviceState parent_obj; |
| 678 | |
| 679 | /* Properties */ |
| 680 | int prop_a; |
| 681 | char *prop_b; |
| 682 | /* Other stuff */ |
| 683 | int internal_state; |
| 684 | }; |
| 685 | |
| 686 | struct MyDeviceClass { |
| 687 | DeviceClass parent_class; |
| 688 | |
| 689 | void (*new_fn1)(void); |
| 690 | bool (*new_fn2)(CPUState *); |
| 691 | }; |
| 692 | |
| 693 | Note that there is no need to provide typedefs for QOM structures |
| 694 | since these are generated automatically by the QOM declaration macros. |
| 695 | See :ref:`qom` for more details. |
| 696 | |
| 697 | QEMU GUARD macros |
| 698 | ================= |
| 699 | |
| 700 | QEMU provides a number of ``_GUARD`` macros intended to make the |
| 701 | handling of multiple exit paths easier. For example using |
| 702 | ``QEMU_LOCK_GUARD`` to take a lock will ensure the lock is released on |
| 703 | exit from the function. |
| 704 | |
| 705 | .. code-block:: c |
| 706 | |
| 707 | static int my_critical_function(SomeState *s, void *data) |
| 708 | { |
| 709 | QEMU_LOCK_GUARD(&s->lock); |
| 710 | do_thing1(data); |
| 711 | if (check_state2(data)) { |
| 712 | return -1; |
| 713 | } |
| 714 | do_thing3(data); |
| 715 | return 0; |
| 716 | } |
| 717 | |
| 718 | will ensure s->lock is released however the function is exited. The |
| 719 | equivalent code without _GUARD macro makes us to carefully put |
| 720 | qemu_mutex_unlock() on all exit points: |
| 721 | |
| 722 | .. code-block:: c |
| 723 | |
| 724 | static int my_critical_function(SomeState *s, void *data) |
| 725 | { |
| 726 | qemu_mutex_lock(&s->lock); |
| 727 | do_thing1(data); |
| 728 | if (check_state2(data)) { |
| 729 | qemu_mutex_unlock(&s->lock); |
| 730 | return -1; |
| 731 | } |
| 732 | do_thing3(data); |
| 733 | qemu_mutex_unlock(&s->lock); |
| 734 | return 0; |
| 735 | } |
| 736 | |
| 737 | There are often ``WITH_`` forms of macros which more easily wrap |
| 738 | around a block inside a function. |
| 739 | |
| 740 | .. code-block:: c |
| 741 | |
| 742 | WITH_RCU_READ_LOCK_GUARD() { |
| 743 | QTAILQ_FOREACH_RCU(kid, &bus->children, sibling) { |
| 744 | err = do_the_thing(kid->child); |
| 745 | if (err < 0) { |
| 746 | return err; |
| 747 | } |
| 748 | } |
| 749 | } |
| 750 | |
| 751 | Error handling and reporting |
| 752 | ============================ |
| 753 | |
| 754 | Reporting errors to the human user |
| 755 | ---------------------------------- |
| 756 | |
| 757 | Do not use printf(), fprintf() or monitor_hmp_printf(). Instead, use |
| 758 | error_report() or error_vreport() from error-report.h. This ensures the |
| 759 | error is reported in the right place (current monitor or stderr), and in |
| 760 | a uniform format. |
| 761 | |
| 762 | Use error_printf() & friends to print additional information. |
| 763 | |
| 764 | error_report() prints the current location. In certain common cases |
| 765 | like command line parsing, the current location is tracked |
| 766 | automatically. To manipulate it manually, use the loc_``*``() from |
| 767 | error-report.h. |
| 768 | |
| 769 | Propagating errors |
| 770 | ------------------ |
| 771 | |
| 772 | An error can't always be reported to the user right where it's detected, |
| 773 | but often needs to be propagated up the call chain to a place that can |
| 774 | handle it. This can be done in various ways. |
| 775 | |
| 776 | The most flexible one is Error objects. See error.h for usage |
| 777 | information. |
| 778 | |
| 779 | Use the simplest suitable method to communicate success / failure to |
| 780 | callers. Stick to common methods: non-negative on success / -1 on |
| 781 | error, non-negative / -errno, non-null / null, or Error objects. |
| 782 | |
| 783 | Example: when a function returns a non-null pointer on success, and it |
| 784 | can fail only in one way (as far as the caller is concerned), returning |
| 785 | null on failure is just fine, and certainly simpler and a lot easier on |
| 786 | the eyes than propagating an Error object through an ``Error **`` parameter. |
| 787 | |
| 788 | Example: when a function's callers need to report details on failure |
| 789 | only the function really knows, use ``Error **``, and set suitable errors. |
| 790 | |
| 791 | Do not report an error to the user when you're also returning an error |
| 792 | for somebody else to handle. Leave the reporting to the place that |
| 793 | consumes the error returned. |
| 794 | |
| 795 | Handling errors |
| 796 | --------------- |
| 797 | |
| 798 | Calling exit() is fine when handling configuration errors during |
| 799 | startup. It's problematic during normal operation. In particular, |
| 800 | monitor commands should never exit(). |
| 801 | |
| 802 | Do not call exit() or abort() to handle an error that can be triggered |
| 803 | by the guest (e.g., some unimplemented corner case in guest code |
| 804 | translation or device emulation). Guests should not be able to |
| 805 | terminate QEMU. |
| 806 | |
| 807 | Note that &error_fatal is just another way to exit(1), and &error_abort |
| 808 | is just another way to abort(). |
| 809 | |
| 810 | |
| 811 | trace-events style |
| 812 | ================== |
| 813 | |
| 814 | 0x prefix |
| 815 | --------- |
| 816 | |
| 817 | In trace-events files, use a '0x' prefix to specify hex numbers, as in: |
| 818 | |
| 819 | .. code-block:: c |
| 820 | |
| 821 | some_trace(unsigned x, uint64_t y) "x 0x%x y 0x" PRIx64 |
| 822 | |
| 823 | An exception is made for groups of numbers that are hexadecimal by |
| 824 | convention and separated by the symbols '.', '/', ':', or ' ' (such as |
| 825 | PCI bus id): |
| 826 | |
| 827 | .. code-block:: c |
| 828 | |
| 829 | another_trace(int cssid, int ssid, int dev_num) "bus id: %x.%x.%04x" |
| 830 | |
| 831 | However, you can use '0x' for such groups if you want. Anyway, be sure that |
| 832 | it is obvious that numbers are in hex, ex.: |
| 833 | |
| 834 | .. code-block:: c |
| 835 | |
| 836 | data_dump(uint8_t c1, uint8_t c2, uint8_t c3) "bytes (in hex): %02x %02x %02x" |
| 837 | |
| 838 | Rationale: hex numbers are hard to read in logs when there is no 0x prefix, |
| 839 | especially when (occasionally) the representation doesn't contain any letters |
| 840 | and especially in one line with other decimal numbers. Number groups are allowed |
| 841 | to not use '0x' because for some things notations like %x.%x.%x are used not |
| 842 | only in QEMU. Also dumping raw data bytes with '0x' is less readable. |
| 843 | |
| 844 | '#' printf flag |
| 845 | --------------- |
| 846 | |
| 847 | Do not use printf flag '#', like '%#x'. |
| 848 | |
| 849 | Rationale: there are two ways to add a '0x' prefix to printed number: '0x%...' |
| 850 | and '%#...'. For consistency the only one way should be used. Arguments for |
| 851 | '0x%' are: |
| 852 | |
| 853 | * it is more popular |
| 854 | * '%#' omits the 0x for the value 0 which makes output inconsistent |