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