man pages: update the description for the virsh help command
[libvirt/aglitke.git] / HACKING
blobd64670900c6a423967f6f4db540ca8ecf0a388c8
1 -*- buffer-read-only: t -*- vi: set ro:
2 DO NOT EDIT THIS FILE!  IT IS GENERATED AUTOMATICALLY!
6                          Contributor guidelines
7                          ======================
11 General tips for contributing patches
12 =====================================
13 (1) Discuss any large changes on the mailing list first. Post patches early and
14 listen to feedback.
16 (2) Post patches in unified diff format. A command similar to this should work:
18   diff -urp libvirt.orig/ libvirt.modified/ > libvirt-myfeature.patch
20 or:
22   git diff > libvirt-myfeature.patch
24 (3) Split large changes into a series of smaller patches, self-contained if
25 possible, with an explanation of each patch and an explanation of how the
26 sequence of patches fits together.
28 (4) Make sure your patches apply against libvirt GIT. Developers only follow GIT
29 and don't care much about released versions.
31 (5) Run the automated tests on your code before submitting any changes. In
32 particular, configure with compile warnings set to -Werror:
34   ./configure --enable-compile-warnings=error
36 and run the tests:
38   make check
39   make syntax-check
40   make -C tests valgrind
42 The latter test checks for memory leaks.
44 If you encounter any failing tests, the VIR_TEST_DEBUG environment variable
45 may provide extra information to debug the failures. Larger values of
46 VIR_TEST_DEBUG may provide larger amounts of information:
48   VIR_TEST_DEBUG=1 make check    (or)
49   VIR_TEST_DEBUG=2 make check
51 Also, individual tests can be run from inside the "tests/" directory, like:
53   ./qemuxml2xmltest
55 (6) Update tests and/or documentation, particularly if you are adding a new
56 feature or changing the output of a program.
60 There is more on this subject, including lots of links to background reading
61 on the subject, on
63   Richard Jones' guide to working with open source projects
64   http://et.redhat.com/~rjones/how-to-supply-code-to-open-source-projects/
67 Code indentation
68 ================
69 Libvirt's C source code generally adheres to some basic code-formatting
70 conventions. The existing code base is not totally consistent on this front,
71 but we do prefer that contributed code be formatted similarly. In short, use
72 spaces-not-TABs for indentation, use 4 spaces for each indentation level, and
73 other than that, follow the K&R style.
75 If you use Emacs, add the following to one of one of your start-up files
76 (e.g., ~/.emacs), to help ensure that you get indentation right:
78   ;;; When editing C sources in libvirt, use this style.
79   (defun libvirt-c-mode ()
80     "C mode with adjusted defaults for use with libvirt."
81     (interactive)
82     (c-set-style "K&R")
83     (setq indent-tabs-mode nil) ; indent using spaces, not TABs
84     (setq c-indent-level 4)
85     (setq c-basic-offset 4))
86   (add-hook 'c-mode-hook
87             '(lambda () (if (string-match "/libvirt" (buffer-file-name))
88                             (libvirt-c-mode))))
91 Code formatting (especially for new code)
92 =========================================
93 With new code, we can be even more strict. Please apply the following function
94 (using GNU indent) to any new code. Note that this also gives you an idea of
95 the type of spacing we prefer around operators and keywords:
97   indent-libvirt()
98   {
99     indent -bad -bap -bbb -bli4 -br -ce -brs -cs -i4 -l75 -lc75 \
100       -sbi4 -psl -saf -sai -saw -sbi4 -ss -sc -cdw -cli4 -npcs -nbc \
101       --no-tabs "$@"
102   }
104 Note that sometimes you'll have to post-process that output further, by piping
105 it through "expand -i", since some leading TABs can get through. Usually
106 they're in macro definitions or strings, and should be converted anyhow.
109 Curly braces
110 ============
111 Omit the curly braces around an "if", "while", "for" etc. body only when that
112 body occupies a single line. In every other case we require the braces. This
113 ensures that it is trivially easy to identify a single-'statement' loop: each
114 has only one 'line' in its body.
116 Omitting braces with a single-line body is fine:
118   while (expr) // one-line body -> omitting curly braces is ok
119       single_line_stmt();
121 However, the moment your loop/if/else body extends onto a second line, for
122 whatever reason (even if it's just an added comment), then you should add
123 braces. Otherwise, it would be too easy to insert a statement just before that
124 comment (without adding braces), thinking it is already a multi-statement loop:
126   while (true) // BAD! multi-line body with no braces
127       /* comment... */
128       single_line_stmt();
130 Do this instead:
132   while (true) { // Always put braces around a multi-line body.
133       /* comment... */
134       single_line_stmt();
135   }
137 There is one exception: when the second body line is not at the same
138 indentation level as the first body line:
140   if (expr)
141       die("a diagnostic that would make this line"
142           " extend past the 80-column limit"));
144 It is safe to omit the braces in the code above, since the further-indented
145 second body line makes it obvious that this is still a single-statement body.
147 To reiterate, don't do this:
149   if (expr)            // BAD: no braces around...
150       while (expr_2) { // ... a multi-line body
151           ...
152       }
154 Do this, instead:
156   if (expr) {
157       while (expr_2) {
158           ...
159       }
160   }
162 However, there is one exception in the other direction, when even a one-line
163 block should have braces. That occurs when that one-line, brace-less block is
164 an "else" block, and the corresponding "then" block *does* use braces. In that
165 case, either put braces around the "else" block, or negate the "if"-condition
166 and swap the bodies, putting the one-line block first and making the longer,
167 multi-line block be the "else" block.
169   if (expr) {
170       ...
171       ...
172   }
173   else
174       x = y;    // BAD: braceless "else" with braced "then"
176 This is preferred, especially when the multi-line body is more than a few
177 lines long, because it is easier to read and grasp the semantics of an
178 if-then-else block when the simpler block occurs first, rather than after the
179 more involved block:
181   if (!expr)
182     x = y; // putting the smaller block first is more readable
183   else {
184       ...
185       ...
186   }
188 If you'd rather not negate the condition, then at least add braces:
190   if (expr) {
191       ...
192       ...
193   } else {
194       x = y;
195   }
198 Preprocessor
199 ============
200 For variadic macros, stick with C99 syntax:
202   #define vshPrint(_ctl, ...) fprintf(stdout, __VA_ARGS__)
204 Use parenthesis when checking if a macro is defined, and use indentation to
205 track nesting:
207   #if defined(HAVE_POSIX_FALLOCATE) && !defined(HAVE_FALLOCATE)
208   # define fallocate(a,ignored,b,c) posix_fallocate(a,b,c)
209   #endif
212 C types
213 =======
214 Use the right type.
216 Scalars
217 -------
218 - If you're using "int" or "long", odds are good that there's a better type.
220 - If a variable is counting something, be sure to declare it with an unsigned
221 type.
223 - If it's memory-size-related, use "size_t" (use "ssize_t" only if required).
225 - If it's file-size related, use uintmax_t, or maybe "off_t".
227 - If it's file-offset related (i.e., signed), use "off_t".
229 - If it's just counting small numbers use "unsigned int"; (on all but oddball
230 embedded systems, you can assume that that type is at least four bytes wide).
232 - If a variable has boolean semantics, give it the "bool" type and use the
233 corresponding "true" and "false" macros. It's ok to include <stdbool.h>, since
234 libvirt's use of gnulib ensures that it exists and is usable.
236 - In the unusual event that you require a specific width, use a standard type
237 like "int32_t", "uint32_t", "uint64_t", etc.
239 - While using "bool" is good for readability, it comes with minor caveats:
241 -- Don't use "bool" in places where the type size must be constant across all
242 systems, like public interfaces and on-the-wire protocols. Note that it would
243 be possible (albeit wasteful) to use "bool" in libvirt's logical wire
244 protocol, since XDR maps that to its lower-level "bool_t" type, which *is*
245 fixed-size.
247 -- Don't compare a bool variable against the literal, "true", since a value with
248 a logical non-false value need not be "1". I.e., don't write "if (seen ==
249 true) ...". Rather, write "if (seen)...".
255 Of course, take all of the above with a grain of salt. If you're about to use
256 some system interface that requires a type like "size_t", "pid_t" or "off_t",
257 use matching types for any corresponding variables.
259 Also, if you try to use e.g., "unsigned int" as a type, and that conflicts
260 with the signedness of a related variable, sometimes it's best just to use the
261 *wrong* type, if 'pulling the thread' and fixing all related variables would
262 be too invasive.
264 Finally, while using descriptive types is important, be careful not to go
265 overboard. If whatever you're doing causes warnings, or requires casts, then
266 reconsider or ask for help.
268 Pointers
269 --------
270 Ensure that all of your pointers are 'const-correct'. Unless a pointer is used
271 to modify the pointed-to storage, give it the "const" attribute. That way, the
272 reader knows up-front that this is a read-only pointer. Perhaps more
273 importantly, if we're diligent about this, when you see a non-const pointer,
274 you're guaranteed that it is used to modify the storage it points to, or it is
275 aliased to another pointer that is.
278 Low level memory management
279 ===========================
280 Use of the malloc/free/realloc/calloc APIs is deprecated in the libvirt
281 codebase, because they encourage a number of serious coding bugs and do not
282 enable compile time verification of checks for NULL. Instead of these
283 routines, use the macros from memory.h.
285 - To allocate a single object:
287   virDomainPtr domain;
289   if (VIR_ALLOC(domain) < 0) {
290       virReportOOMError();
291       return NULL;
292   }
296 - To allocate an array of objects:
298   virDomainPtr domains;
299   size_t ndomains = 10;
301   if (VIR_ALLOC_N(domains, ndomains) < 0) {
302       virReportOOMError();
303       return NULL;
304   }
308 - To allocate an array of object pointers:
310   virDomainPtr *domains;
311   size_t ndomains = 10;
313   if (VIR_ALLOC_N(domains, ndomains) < 0) {
314       virReportOOMError();
315       return NULL;
316   }
320 - To re-allocate the array of domains to be 1 element longer (however, note that
321 repeatedly expanding an array by 1 scales quadratically, so this is
322 recommended only for smaller arrays):
324   virDomainPtr domains;
325   size_t ndomains = 0;
327   if (VIR_EXPAND_N(domains, ndomains, 1) < 0) {
328       virReportOOMError();
329       return NULL;
330   }
331   domains[ndomains - 1] = domain;
335 - To ensure an array has room to hold at least one more element (this approach
336 scales better, but requires tracking allocation separately from usage)
338   virDomainPtr domains;
339   size_t ndomains = 0;
340   size_t ndomains_max = 0;
342   if (VIR_RESIZE_N(domains, ndomains_max, ndomains, 1) < 0) {
343       virReportOOMError();
344       return NULL;
345   }
346   domains[ndomains++] = domain;
350 - To trim an array of domains from its allocated size down to the actual used
351 size:
353   virDomainPtr domains;
354   size_t ndomains = x;
355   size_t ndomains_max = y;
357   VIR_SHRINK_N(domains, ndomains_max, ndomains_max - ndomains);
361 - To free an array of domains:
363   virDomainPtr domains;
364   size_t ndomains = x;
365   size_t ndomains_max = y;
366   size_t i;
368   for (i = 0; i < ndomains; i++)
369       VIR_FREE(domains[i]);
370   VIR_FREE(domains);
371   ndomains_max = ndomains = 0;
378 File handling
379 =============
380 Usage of the "fdopen()", "close()", "fclose()" APIs is deprecated in libvirt
381 code base to help avoiding double-closing of files or file descriptors, which
382 is particulary dangerous in a multi-threaded applications. Instead of these
383 APIs, use the macros from files.h
385 - Open a file from a file descriptor:
387   if ((file = VIR_FDOPEN(fd, "r")) == NULL) {
388       virReportSystemError(errno, "%s",
389                            _("failed to open file from file descriptor"));
390       return -1;
391   }
392   /* fd is now invalid; only access the file using file variable */
396 - Close a file descriptor:
398   if (VIR_CLOSE(fd) < 0) {
399       virReportSystemError(errno, "%s", _("failed to close file"));
400   }
404 - Close a file:
406   if (VIR_FCLOSE(file) < 0) {
407       virReportSystemError(errno, "%s", _("failed to close file"));
408   }
412 - Close a file or file descriptor in an error path, without losing the previous
413 "errno" value:
415   VIR_FORCE_CLOSE(fd);
416   VIR_FORCE_FCLOSE(file);
423 String comparisons
424 ==================
425 Do not use the strcmp, strncmp, etc functions directly. Instead use one of the
426 following semantically named macros
428 - For strict equality:
430   STREQ(a,b)
431   STRNEQ(a,b)
435 - For case insensitive equality:
437   STRCASEEQ(a,b)
438   STRCASENEQ(a,b)
442 - For strict equality of a substring:
444   STREQLEN(a,b,n)
445   STRNEQLEN(a,b,n)
449 - For case insensitive equality of a substring:
451   STRCASEEQLEN(a,b,n)
452   STRCASENEQLEN(a,b,n)
456 - For strict equality of a prefix:
458   STRPREFIX(a,b)
465 String copying
466 ==============
467 Do not use the strncpy function. According to the man page, it does *not*
468 guarantee a NULL-terminated buffer, which makes it extremely dangerous to use.
469 Instead, use one of the functionally equivalent functions:
471   virStrncpy(char *dest, const char *src, size_t n, size_t destbytes)
473 The first three arguments have the same meaning as for strncpy; namely the
474 destination, source, and number of bytes to copy, respectively. The last
475 argument is the number of bytes available in the destination string; if a copy
476 of the source string (including a \0) will not fit into the destination, no
477 bytes are copied and the routine returns NULL. Otherwise, n bytes from the
478 source are copied into the destination and a trailing \0 is appended.
480   virStrcpy(char *dest, const char *src, size_t destbytes)
482 Use this variant if you know you want to copy the entire src string into dest.
483 Note that this is a macro, so arguments could be evaluated more than once.
484 This is equivalent to virStrncpy(dest, src, strlen(src), destbytes)
486   virStrcpyStatic(char *dest, const char *src)
488 Use this variant if you know you want to copy the entire src string into dest
489 *and* you know that your destination string is a static string (i.e. that
490 sizeof(dest) returns something meaningful). Note that this is a macro, so
491 arguments could be evaluated more than once. This is equivalent to
492 virStrncpy(dest, src, strlen(src), sizeof(dest)).
495 Variable length string buffer
496 =============================
497 If there is a need for complex string concatenations, avoid using the usual
498 sequence of malloc/strcpy/strcat/snprintf functions and make use of the
499 virBuffer API described in buf.h
501 Typical usage is as follows:
503   char *
504   somefunction(...)
505   {
506      virBuffer buf = VIR_BUFFER_INITIALIZER;
508      ...
510      virBufferAddLit(&buf, "<domain>\n");
511      virBufferVSprintf(&buf, "  <memory>%d</memory>\n", memory);
512      ...
513      virBufferAddLit(&buf, "</domain>\n");
515      ...
517      if (virBufferError(&buf)) {
518          virBufferFreeAndReset(&buf);
519          virReportOOMError();
520          return NULL;
521      }
523      return virBufferContentAndReset(&buf);
524   }
527 Include files
528 =============
529 There are now quite a large number of include files, both libvirt internal and
530 external, and system includes. To manage all this complexity it's best to
531 stick to the following general plan for all *.c source files:
533   /*
534    * Copyright notice
535    * ....
536    * ....
537    * ....
538    *
539    */
541   #include <config.h>             Must come first in every file.
543   #include <stdio.h>              Any system includes you need.
544   #include <string.h>
545   #include <limits.h>
547   #if HAVE_NUMACTL                Some system includes aren't supported
548   # include <numa.h>              everywhere so need these #if guards.
549   #endif
551   #include "internal.h"           Include this first, after system includes.
553   #include "util.h"               Any libvirt internal header files.
554   #include "buf.h"
556   static int
557   myInternalFunc()                The actual code.
558   {
559       ...
561 Of particular note: *Do not* include libvirt/libvirt.h or libvirt/virterror.h.
562 It is included by "internal.h" already and there are some special reasons why
563 you cannot include these files explicitly.
566 Printf-style functions
567 ======================
568 Whenever you add a new printf-style function, i.e., one with a format string
569 argument and following "..." in its prototype, be sure to use gcc's printf
570 attribute directive in the prototype. For example, here's the one for
571 virAsprintf, in util.h:
573   int virAsprintf(char **strp, const char *fmt, ...)
574       ATTRIBUTE_FORMAT(printf, 2, 3);
576 This makes it so gcc's -Wformat and -Wformat-security options can do their
577 jobs and cross-check format strings with the number and types of arguments.
579 When printing to a string, consider using virBuffer for incremental
580 allocations, virAsprintf for a one-shot allocation, and snprintf for
581 fixed-width buffers. Do not use sprintf, even if you can prove the buffer
582 won't overflow, since gnulib does not provide the same portability guarantees
583 for sprintf as it does for snprintf.
586 Use of goto
587 ===========
588 The use of goto is not forbidden, and goto is widely used throughout libvirt.
589 While the uncontrolled use of goto will quickly lead to unmaintainable code,
590 there is a place for it in well structured code where its use increases
591 readability and maintainability. In general, if goto is used for error
592 recovery, it's likely to be ok, otherwise, be cautious or avoid it all
593 together.
595 The typical use of goto is to jump to cleanup code in the case of a long list
596 of actions, any of which may fail and cause the entire operation to fail. In
597 this case, a function will have a single label at the end of the function.
598 It's almost always ok to use this style. In particular, if the cleanup code
599 only involves free'ing memory, then having multiple labels is overkill.
600 VIR_FREE() and every function named XXXFree() in libvirt is required to handle
601 NULL as its arg. Thus you can safely call free on all the variables even if
602 they were not yet allocated (yes they have to have been initialized to NULL).
603 This is much simpler and clearer than having multiple labels.
605 There are a couple of signs that a particular use of goto is not ok:
607 - You're using multiple labels. If you find yourself using multiple labels,
608 you're strongly encouraged to rework your code to eliminate all but one of
609 them.
611 - The goto jumps back up to a point above the current line of code being
612 executed. Please use some combination of looping constructs to re-execute code
613 instead; it's almost certainly going to be more understandable by others. One
614 well-known exception to this rule is restarting an i/o operation following
615 EINTR.
617 - The goto jumps down to an arbitrary place in the middle of a function followed
618 by further potentially failing calls. You should almost certainly be using a
619 conditional and a block instead of a goto. Perhaps some of your function's
620 logic would be better pulled out into a helper function.
624 Although libvirt does not encourage the Linux kernel wind/unwind style of
625 multiple labels, there's a good general discussion of the issue archived at
627   KernelTrap
628   http://kerneltrap.org/node/553/2131
630 When using goto, please use one of these standard labels if it makes sense:
632       error: A path only taken upon return with an error code
633     cleanup: A path taken upon return with success code + optional error
634   no_memory: A path only taken upon return with an OOM error code
635       retry: If needing to jump upwards (e.g., retry on EINTR)
638 Libvirt committer guidelines
639 ============================
640 The AUTHORS files indicates the list of people with commit access right who
641 can actually merge the patches.
643 The general rule for committing a patch is to make sure it has been reviewed
644 properly in the mailing-list first, usually if a couple of people gave an ACK
645 or +1 to a patch and nobody raised an objection on the list it should be good
646 to go. If the patch touches a part of the code where you're not the main
647 maintainer, or where you do not have a very clear idea of how things work,
648 it's better to wait for a more authoritative feedback though. Before
649 committing, please also rebuild locally, run 'make check syntax-check', and
650 make sure you don't raise errors. Try to look for warnings too; for example,
651 configure with
653   --enable-compile-warnings=error
655 which adds -Werror to compile flags, so no warnings get missed
657 An exception to 'review and approval on the list first' is fixing failures to
658 build:
660 - if a recently committed patch breaks compilation on a platform or for a given
661 driver, then it's fine to commit a minimal fix directly without getting the
662 review feedback first
664 - if make check or make syntax-check breaks, if there is an obvious fix, it's
665 fine to commit immediately. The patch should still be sent to the list (or
666 tell what the fix was if trivial), and 'make check syntax-check' should pass
667 too, before committing anything
669 - fixes for documentation and code comments can be managed in the same way, but
670 still make sure they get reviewed if non-trivial.