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