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