docs: convert README, CODING_STYLE and HACKING to RST syntax
[qemu/ericb.git] / HACKING.rst
blob668fc420c3db47a66120e830258a49d651f7e5dd
1 ============
2 QEMU Hacking
3 ============
5 .. contents:: Table of Contents
7 Preprocessor
8 ============
10 Variadic macros
11 ---------------
13 For variadic macros, stick with this C99-like syntax:
15 .. code-block:: c
17     #define DPRINTF(fmt, ...)                                       \
18         do { printf("IRQ: " fmt, ## __VA_ARGS__); } while (0)
20 Include directives
21 ------------------
23 Order include directives as follows:
25 .. code-block:: c
27     #include "qemu/osdep.h"  /* Always first... */
28     #include <...>           /* then system headers... */
29     #include "..."           /* and finally QEMU headers. */
31 The "qemu/osdep.h" header contains preprocessor macros that affect the behavior
32 of core system headers like <stdint.h>.  It must be the first include so that
33 core system headers included by external libraries get the preprocessor macros
34 that QEMU depends on.
36 Do not include "qemu/osdep.h" from header files since the .c file will have
37 already included it.
39 C types
40 =======
42 It should be common sense to use the right type, but we have collected
43 a few useful guidelines here.
45 Scalars
46 -------
48 If you're using "int" or "long", odds are good that there's a better type.
49 If a variable is counting something, it should be declared with an
50 unsigned type.
52 If it's host memory-size related, size_t should be a good choice (use
53 ssize_t only if required). Guest RAM memory offsets must use ram_addr_t,
54 but only for RAM, it may not cover whole guest address space.
56 If it's file-size related, use off_t.
57 If it's file-offset related (i.e., signed), use off_t.
58 If it's just counting small numbers use "unsigned int";
59 (on all but oddball embedded systems, you can assume that that
60 type is at least four bytes wide).
62 In the event that you require a specific width, use a standard type
63 like int32_t, uint32_t, uint64_t, etc.  The specific types are
64 mandatory for VMState fields.
66 Don't use Linux kernel internal types like u32, __u32 or __le32.
68 Use hwaddr for guest physical addresses except pcibus_t
69 for PCI addresses.  In addition, ram_addr_t is a QEMU internal address
70 space that maps guest RAM physical addresses into an intermediate
71 address space that can map to host virtual address spaces.  Generally
72 speaking, the size of guest memory can always fit into ram_addr_t but
73 it would not be correct to store an actual guest physical address in a
74 ram_addr_t.
76 For CPU virtual addresses there are several possible types.
77 vaddr is the best type to use to hold a CPU virtual address in
78 target-independent code. It is guaranteed to be large enough to hold a
79 virtual address for any target, and it does not change size from target
80 to target. It is always unsigned.
81 target_ulong is a type the size of a virtual address on the CPU; this means
82 it may be 32 or 64 bits depending on which target is being built. It should
83 therefore be used only in target-specific code, and in some
84 performance-critical built-per-target core code such as the TLB code.
85 There is also a signed version, target_long.
86 abi_ulong is for the ``*``-user targets, and represents a type the size of
87 'void ``*``' in that target's ABI. (This may not be the same as the size of a
88 full CPU virtual address in the case of target ABIs which use 32 bit pointers
89 on 64 bit CPUs, like sparc32plus.) Definitions of structures that must match
90 the target's ABI must use this type for anything that on the target is defined
91 to be an 'unsigned long' or a pointer type.
92 There is also a signed version, abi_long.
94 Of course, take all of the above with a grain of salt.  If you're about
95 to use some system interface that requires a type like size_t, pid_t or
96 off_t, use matching types for any corresponding variables.
98 Also, if you try to use e.g., "unsigned int" as a type, and that
99 conflicts with the signedness of a related variable, sometimes
100 it's best just to use the *wrong* type, if "pulling the thread"
101 and fixing all related variables would be too invasive.
103 Finally, while using descriptive types is important, be careful not to
104 go overboard.  If whatever you're doing causes warnings, or requires
105 casts, then reconsider or ask for help.
107 Pointers
108 --------
110 Ensure that all of your pointers are "const-correct".
111 Unless a pointer is used to modify the pointed-to storage,
112 give it the "const" attribute.  That way, the reader knows
113 up-front that this is a read-only pointer.  Perhaps more
114 importantly, if we're diligent about this, when you see a non-const
115 pointer, you're guaranteed that it is used to modify the storage
116 it points to, or it is aliased to another pointer that is.
118 Typedefs
119 --------
121 Typedefs are used to eliminate the redundant 'struct' keyword, since type
122 names have a different style than other identifiers ("CamelCase" versus
123 "snake_case").  Each named struct type should have a CamelCase name and a
124 corresponding typedef.
126 Since certain C compilers choke on duplicated typedefs, you should avoid
127 them and declare a typedef only in one header file.  For common types,
128 you can use "include/qemu/typedefs.h" for example.  However, as a matter
129 of convenience it is also perfectly fine to use forward struct
130 definitions instead of typedefs in headers and function prototypes; this
131 avoids problems with duplicated typedefs and reduces the need to include
132 headers from other headers.
134 Reserved namespaces in C and POSIX
135 ----------------------------------
137 Underscore capital, double underscore, and underscore 't' suffixes should be
138 avoided.
140 Low level memory management
141 ===========================
143 Use of the malloc/free/realloc/calloc/valloc/memalign/posix_memalign
144 APIs is not allowed in the QEMU codebase. Instead of these routines,
145 use the GLib memory allocation routines g_malloc/g_malloc0/g_new/
146 g_new0/g_realloc/g_free or QEMU's qemu_memalign/qemu_blockalign/qemu_vfree
147 APIs.
149 Please note that g_malloc will exit on allocation failure, so there
150 is no need to test for failure (as you would have to with malloc).
151 Calling g_malloc with a zero size is valid and will return NULL.
153 Prefer g_new(T, n) instead of g_malloc(sizeof(T) ``*`` n) for the following
154 reasons:
156 * It catches multiplication overflowing size_t;
157 * It returns T ``*`` instead of void ``*``, letting compiler catch more type errors.
159 Declarations like
161 .. code-block:: c
163     T *v = g_malloc(sizeof(*v))
165 are acceptable, though.
167 Memory allocated by qemu_memalign or qemu_blockalign must be freed with
168 qemu_vfree, since breaking this will cause problems on Win32.
170 String manipulation
171 ===================
173 Do not use the strncpy function.  As mentioned in the man page, it does *not*
174 guarantee a NULL-terminated buffer, which makes it extremely dangerous to use.
175 It also zeros trailing destination bytes out to the specified length.  Instead,
176 use this similar function when possible, but note its different signature:
178 .. code-block:: c
180     void pstrcpy(char *dest, int dest_buf_size, const char *src)
182 Don't use strcat because it can't check for buffer overflows, but:
184 .. code-block:: c
186     char *pstrcat(char *buf, int buf_size, const char *s)
188 The same limitation exists with sprintf and vsprintf, so use snprintf and
189 vsnprintf.
191 QEMU provides other useful string functions:
193 .. code-block:: c
195     int strstart(const char *str, const char *val, const char **ptr)
196     int stristart(const char *str, const char *val, const char **ptr)
197     int qemu_strnlen(const char *s, int max_len)
199 There are also replacement character processing macros for isxyz and toxyz,
200 so instead of e.g. isalnum you should use qemu_isalnum.
202 Because of the memory management rules, you must use g_strdup/g_strndup
203 instead of plain strdup/strndup.
205 Printf-style functions
206 ======================
208 Whenever you add a new printf-style function, i.e., one with a format
209 string argument and following "..." in its prototype, be sure to use
210 gcc's printf attribute directive in the prototype.
212 This makes it so gcc's -Wformat and -Wformat-security options can do
213 their jobs and cross-check format strings with the number and types
214 of arguments.
216 C standard, implementation defined and undefined behaviors
217 ==========================================================
219 C code in QEMU should be written to the C99 language specification. A copy
220 of the final version of the C99 standard with corrigenda TC1, TC2, and TC3
221 included, formatted as a draft, can be downloaded from:
223     `<http://www.open-std.org/jtc1/sc22/WG14/www/docs/n1256.pdf>`_
225 The C language specification defines regions of undefined behavior and
226 implementation defined behavior (to give compiler authors enough leeway to
227 produce better code).  In general, code in QEMU should follow the language
228 specification and avoid both undefined and implementation defined
229 constructs. ("It works fine on the gcc I tested it with" is not a valid
230 argument...) However there are a few areas where we allow ourselves to
231 assume certain behaviors because in practice all the platforms we care about
232 behave in the same way and writing strictly conformant code would be
233 painful. These are:
235 * you may assume that integers are 2s complement representation
236 * you may assume that right shift of a signed integer duplicates
237   the sign bit (ie it is an arithmetic shift, not a logical shift)
239 In addition, QEMU assumes that the compiler does not use the latitude
240 given in C99 and C11 to treat aspects of signed '<<' as undefined, as
241 documented in the GNU Compiler Collection manual starting at version 4.0.
243 Error handling and reporting
244 ============================
246 Reporting errors to the human user
247 ----------------------------------
249 Do not use printf(), fprintf() or monitor_printf().  Instead, use
250 error_report() or error_vreport() from error-report.h.  This ensures the
251 error is reported in the right place (current monitor or stderr), and in
252 a uniform format.
254 Use error_printf() & friends to print additional information.
256 error_report() prints the current location.  In certain common cases
257 like command line parsing, the current location is tracked
258 automatically.  To manipulate it manually, use the loc_``*``() from
259 error-report.h.
261 Propagating errors
262 ------------------
264 An error can't always be reported to the user right where it's detected,
265 but often needs to be propagated up the call chain to a place that can
266 handle it.  This can be done in various ways.
268 The most flexible one is Error objects.  See error.h for usage
269 information.
271 Use the simplest suitable method to communicate success / failure to
272 callers.  Stick to common methods: non-negative on success / -1 on
273 error, non-negative / -errno, non-null / null, or Error objects.
275 Example: when a function returns a non-null pointer on success, and it
276 can fail only in one way (as far as the caller is concerned), returning
277 null on failure is just fine, and certainly simpler and a lot easier on
278 the eyes than propagating an Error object through an Error ``*````*`` parameter.
280 Example: when a function's callers need to report details on failure
281 only the function really knows, use Error ``*````*``, and set suitable errors.
283 Do not report an error to the user when you're also returning an error
284 for somebody else to handle.  Leave the reporting to the place that
285 consumes the error returned.
287 Handling errors
288 ---------------
290 Calling exit() is fine when handling configuration errors during
291 startup.  It's problematic during normal operation.  In particular,
292 monitor commands should never exit().
294 Do not call exit() or abort() to handle an error that can be triggered
295 by the guest (e.g., some unimplemented corner case in guest code
296 translation or device emulation).  Guests should not be able to
297 terminate QEMU.
299 Note that &error_fatal is just another way to exit(1), and &error_abort
300 is just another way to abort().