You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HACKING 10KB

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