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