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