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