nrelease - fix/improve livecd
[dragonfly.git] / share / man / man9 / style.9
1 .\" Copyright (c) 1995-2001 FreeBSD Inc.
2 .\" All rights reserved.
3 .\"
4 .\" Redistribution and use in source and binary forms, with or without
5 .\" modification, are permitted provided that the following conditions
6 .\" are met:
7 .\" 1. Redistributions of source code must retain the above copyright
8 .\"    notice, this list of conditions and the following disclaimer.
9 .\" 2. Redistributions in binary form must reproduce the above copyright
10 .\"    notice, this list of conditions and the following disclaimer in the
11 .\"    documentation and/or other materials provided with the distribution.
12 .\"
13 .\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 .\" ARE DISCLAIMED.  IN NO EVENT SHALL [your name] OR CONTRIBUTORS BE LIABLE
17 .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 .\" SUCH DAMAGE.
24 .\"
25 .\" Style guide for DragonFly.  Based on the CSRG's KNF (Kernel Normal Form).
26 .\"
27 .\"     @(#)style       1.14 (Berkeley) 4/28/95
28 .\" $FreeBSD: src/share/man/man9/style.9,v 1.32.2.19 2002/04/14 19:28:03 asmodai Exp $
29 .\"
30 .Dd February 5, 2013
31 .Dt STYLE 9
32 .Os
33 .Sh NAME
34 .Nm style
35 .Nd "kernel source file style guide"
36 .Sh DESCRIPTION
37 This file specifies the preferred style for kernel source files in the
38 .Dx
39 source tree.
40 It is also a guide for preferred userland code style.
41 Many of the style rules are implicit in the examples.
42 Be careful to check the examples before assuming that
43 .Nm
44 is silent on an issue.
45 .Bd -literal
46 /*
47  * VERY important single-line comments look like this.
48  */
49
50 /* Most single-line comments look like this. */
51
52 /*
53  * Multi-line comments look like this.  Make them real sentences.  Fill
54  * them so they look like real paragraphs.
55  */
56
57 /*
58  * XXX in a comment indicates code which is incomplete, suboptimal,
59  * or otherwise deserving of further attention.
60  */
61
62 .Ed
63 .Pp
64 Version control system ID tags should only exist once in a file
65 (unlike this one).
66 All VCS (version control system) revision identification from files obtained
67 from elsewhere should be maintained in comments, including, where applicable,
68 multiple IDs showing a file's history.
69 In general, keep the IDs intact, including any
70 .So Li $ Sc Ns s .
71 There is no reason to add
72 .Qq Li "From"
73 in front of foreign VCS IDs.
74 All VCS IDs should generally be placed in comments somewhere near the
75 top of the source, typically either before or after the copyright message.
76 .Pp
77 Leave another blank line before the header files.
78 .Pp
79 Kernel include files (i.e.\&
80 .Pa sys/*.h )
81 come first; normally, include
82 .In sys/types.h
83 OR
84 .In sys/param.h ,
85 but not both.
86 .In sys/types.h
87 includes
88 .In sys/cdefs.h ,
89 and it is okay to depend on that.
90 .Bd -literal
91 #include <sys/types.h>  /* Non-local includes in angle brackets. */
92 .Ed
93 .Pp
94 For a network program, put the network include files next.
95 .Bd -literal
96 #include <net/if.h>
97 #include <net/if_dl.h>
98 #include <net/route.h>
99 #include <netinet/in.h>
100 #include <protocols/rwhod.h>
101 .Ed
102 .Pp
103 Do not use files in
104 .Pa /usr/include
105 for files in the kernel.
106 .Pp
107 Leave a blank line before the next group, the
108 .Pa /usr
109 include files,
110 which should be sorted alphabetically by name.
111 .Bd -literal
112 #include <stdio.h>
113 .Ed
114 .Pp
115 Global pathnames are defined in
116 .In paths.h .
117 Pathnames local
118 to the program go in
119 .Qq Pa pathnames.h
120 in the local directory.
121 .Bd -literal
122 #include <paths.h>
123 .Ed
124 .Pp
125 Leave another blank line before the user include files.
126 .Bd -literal
127 #include "pathnames.h"          /* Local includes in double quotes. */
128 .Ed
129 .Pp
130 Do not
131 .Ic #define
132 or declare names in the implementation namespace except
133 for implementing application interfaces.
134 .Pp
135 The names of
136 .Dq unsafe
137 macros (ones that have side effects), and the names of macros for
138 manifest constants, are all in uppercase.
139 The expansions of expression-like macros are either a single token
140 or have outer parentheses.
141 Put a single tab character between the
142 .Ic #define
143 and the macro name.
144 If a macro is an inline expansion of a function, the function name is
145 all in lowercase and the macro has the same name all in uppercase.
146 .\" XXX the above conflicts with ANSI style where the names are the
147 .\" same and you #undef the macro (if any) to get the function.
148 .\" It is not followed for MALLOC(), and not very common if inline
149 .\" functions are used.
150 If a
151 macro needs more than a single line, use braces
152 .Ql ( \&{
153 and
154 .Ql \&} ) .
155 Right-justify the
156 backslashes; it makes it easier to read.
157 If the macro encapsulates a compound statement, enclose it in a
158 .Ic do
159 loop,
160 so that it can safely be used in
161 .Ic if
162 statements.
163 Any final statement-terminating semicolon should be
164 supplied by the macro invocation rather than the macro, to make parsing easier
165 for pretty-printers and editors.
166 .Bd -literal
167 #define MACRO(x, y) do {                                                \e
168         variable = (x) + (y);                                           \e
169         (y) += 2;                                                       \e
170 } while (0)
171 .Ed
172 .Pp
173 Enumeration values are all uppercase.
174 .Bd -literal
175 enum enumtype { ONE, TWO } et;
176 .Ed
177 .Pp
178 As fixed size integers the
179 .Tn POSIX
180 defined types are preferred:
181 .Bd -literal -offset indent
182 uint8_t         8 bits fixed size unsigned integer
183 uint16_t        16 bits fixed size unsigned integer
184 uint32_t        32 bits fixed size unsigned integer
185 uint64_t        64 bits fixed size unsigned integer
186 .Ed
187 .Pp
188 When declaring variables in structures, declare them sorted by use, then
189 by size, and then in alphabetical order.
190 The first category normally does not apply, but there are exceptions.
191 Each one gets its own line.
192 Try to make the structure
193 readable by aligning the member names using either one or two tabs
194 depending upon your judgment.
195 You should use one tab if it suffices to align most of the member names.
196 Names following extremely long types
197 should be separated by a single space.
198 .Pp
199 Major structures should be declared at the top of the file in which they
200 are used, or in separate header files if they are used in multiple
201 source files.
202 Use of the structures should be by separate declarations
203 and should be
204 .Ic extern
205 if they are declared in a header file.
206 .Bd -literal
207 struct foo {
208         struct foo      *next;          /* List of active foo. */
209         struct mumble   amumble;        /* Comment for mumble. */
210         int             bar;            /* Try to align the comments. */
211         struct verylongtypename *baz;   /* Won't fit in 2 tabs. */
212 };
213 struct foo *foohead;                    /* Head of global foo list. */
214 .Ed
215 .Pp
216 Use
217 .Xr queue 3
218 macros rather than rolling your own lists, whenever possible.
219 Thus,
220 the previous example would be better written:
221 .Bd -literal
222 #include <sys/queue.h>
223
224 struct foo {
225         LIST_ENTRY(foo) link;           /* Use queue macros for foo lists. */
226         struct mumble   amumble;        /* Comment for mumble. */
227         int             bar;            /* Try to align the comments. */
228         struct verylongtypename *baz;   /* Won't fit in 2 tabs. */
229 };
230 LIST_HEAD(, foo) foohead;               /* Head of global foo list. */
231 .Ed
232 .Pp
233 Avoid using typedefs for structure types.
234 This makes it impossible
235 for applications to use pointers to such a structure opaquely, which
236 is both possible and beneficial when using an ordinary struct tag.
237 When convention requires a
238 .Ic typedef ,
239 make its name match the struct tag.
240 Avoid typedefs ending in
241 .Dq Li _t ,
242 except as specified in Standard C or by
243 .Tn POSIX .
244 .Bd -literal
245 /* Make the structure name match the typedef. */
246 typedef struct bar {
247         int     level;
248 } BAR;
249 typedef int             foo;            /* This is foo. */
250 typedef const long      baz;            /* This is baz. */
251 .Ed
252 .Pp
253 All functions are prototyped somewhere.
254 .Pp
255 Function prototypes for private functions (i.e. functions not used
256 elsewhere) go at the top of the first source module.
257 Functions
258 local to one source module should be declared
259 .Ic static .
260 .Pp
261 Functions used from other parts of the kernel are prototyped in the
262 relevant include file.
263 .Pp
264 Functions that are used locally in more than one module go into a
265 separate header file, e.g.\&
266 .Qq Pa extern.h .
267 .Pp
268 Do not use the
269 .Ic register
270 keyword and the
271 .Dv __P
272 macro from the include file
273 .In sys/cdefs.h .
274 Code in the
275 .Dx
276 source tree is not expected to be K&R compliant.
277 .Pp
278 Changes to existing files should be consistent with that file's conventions.
279 In general, code can be considered
280 .Dq "new code"
281 when it makes up about 50% or more of the file(s) involved.
282 This is enough
283 to break precedents in the existing code and use the current
284 .Nm
285 guidelines.
286 .Pp
287 Function prototypes for the kernel have parameter names associated
288 with parameter types. E.g., in the kernel use:
289 .Bd -literal
290 void    function(int fd);
291 .Ed
292 .Pp
293 Prototypes that are visible to userland applications
294 should not include parameter names with the types, to avoid
295 possible collisions with defined macro names.
296 I.e., use:
297 .Bd -literal
298 void    function(int);
299 .Ed
300 .Pp
301 Prototypes may have an extra space after a tab to enable function names
302 to line up:
303 .Bd -literal
304 static char     *function(int, const char *, struct foo *, struct bar *,
305                      struct baz **);
306 static void      usage(void);
307
308 /*
309  * All major routines should have a comment briefly describing what
310  * they do.  The comment before the "main" routine should describe
311  * what the program does.
312  */
313 int
314 main(int argc, char **argv)
315 {
316         long num;
317         int ch;
318         char *ep;
319
320 .Ed
321 .Pp
322 For consistency,
323 .Xr getopt 3
324 should be used to parse options.
325 Options
326 should be sorted in the
327 .Xr getopt 3
328 call and the
329 .Ic switch
330 statement, unless
331 parts of the
332 .Ic switch
333 cascade.
334 Elements in a
335 .Ic switch
336 statement that cascade should have a
337 .Li FALLTHROUGH
338 comment, unless they contain no code of their own.
339 Numerical arguments should be checked for accuracy.
340 Code that cannot be reached should have a
341 .Li NOTREACHED
342 comment.
343 .Bd -literal
344         while ((ch = getopt(argc, argv, "abn:")) != -1)
345                 switch (ch) {           /* Indent the switch. */
346                 case 'a':               /* Don't indent the case. */
347                         aflag = 1;
348                         /* FALLTHROUGH */
349                 case 'b':
350                         bflag = 1;
351                         break;
352                 case 'n':
353                         num = strtol(optarg, &ep, 10);
354                         if (num <= 0 || *ep != '\e0') {
355                                 warnx("illegal number, -n argument -- %s",
356                                     optarg);
357                                 usage();
358                         }
359                         break;
360                 default:
361                         usage();
362                         /* NOTREACHED */
363                 }
364         argc -= optind;
365         argv += optind;
366 .Ed
367 .Pp
368 Put a single space after control statement keywords
369 .Pq Ic if , do , while , for , switch .
370 No braces are
371 used for control statements with zero or only a single statement unless that
372 statement is more than a single line in which case they are permitted.
373 .Sq Forever
374 loops (loops with no test expression, which are only terminated by a
375 .Ic break ,
376 .Ic return
377 or
378 .Ic exit
379 inside the loop body) are done with
380 .Ic for Ns 's ,
381 not
382 .Ic while Ns 's .
383 .Bd -literal
384         for (p = buf; *p != '\e0'; ++p)
385                 ;       /* nothing */
386         for (;;)
387                 stmt;
388         for (;;) {
389                 z = a + really + long + statement + that + needs +
390                     two + lines + gets + indented + four + spaces +
391                     on + the + second + and + subsequent + lines;
392         }
393         for (;;) {
394                 if (cond)
395                         stmt;
396         }
397         if (val != NULL)
398                 val = realloc(val, newsize);
399 .Ed
400 .Pp
401 Parts of a
402 .Ic for
403 loop may be left empty.
404 Do not put declarations
405 inside blocks unless the routine is unusually complicated.
406 .Bd -literal
407         for (; cnt < 15; cnt++) {
408                 stmt1;
409                 stmt2;
410         }
411 .Ed
412 .Pp
413 Indentation used for program block structure is an 8 character tab.
414 Second level indents used for line continuation are four spaces.
415 If you have to wrap a long statement, put the operator at the end of the
416 line.
417 .Bd -literal
418         while (cnt < 20 && this_variable_name_is_really_far_too_long &&
419             ep != NULL) {
420                 z = a + really + long + statement + that + needs +
421                     two + lines + gets + indented + four + spaces +
422                     on + the + second + and + subsequent + lines;
423         }
424 .Ed
425 .Pp
426 Do not add whitespace at the end of a line, and only use tabs
427 followed by spaces
428 to form the indentation.
429 Do not use more spaces than a tab will produce
430 and do not use spaces in front of tabs.
431 .Pp
432 Closing and opening braces go on the same line as the
433 .Ic else .
434 Braces that are not necessary may be left out, but always use braces around
435 complex or confusing sequences, for example if any part of a conditional is
436 multi-line, use braces for all parts of the conditional, and use braces
437 around multi-line substatements of loops or conditionals even if they are
438 theoretically one statement from the compiler's point of view.
439 .Bd -literal
440         if (test)
441                 stmt;
442         else if (bar)
443                 stmt;
444         else
445                 stmt;
446
447         if (test) {
448                 stmt;
449         } else if (bar) {
450                 stmt;
451                 stmt;
452         } else {
453                 stmt;
454         }
455
456         /* THIS IS WRONG, BRACES SHOULD BE USED */
457         if (fubar)
458                 /* xyz */
459                 x = 1;
460
461         /* THIS IS ALSO WRONG, USE BRACES AROUND THE OUTER CONDITIONAL */
462         if (fubar)
463                 if (barbaz)
464                         x = 1;
465 .Ed
466 .Pp
467 Do not put spaces after function names,
468 after
469 .Ql \&(
470 or
471 .Ql \&[
472 characters, or preceding
473 .Ql \&] ,
474 .Ql \&) ,
475 .Ql \&; ,
476 or
477 .Ql \&,
478 characters.
479 But do put a space after commas and semicolons if there is
480 further text on the same line.
481 .Bd -literal
482         error = function(a1, a2);
483         if (error != 0)
484                 exit(error);
485 .Ed
486 .Pp
487 Unary operators do not require spaces around them,
488 but binary operators (except for
489 .Ql \&.
490 and
491 .Ql \&-> )
492 do.
493 Do not use parentheses unless they are required for precedence or unless the
494 statement is confusing without them.
495 Remember that other people may become
496 confused more easily than you.
497 Do YOU understand the following?
498 .Bd -literal
499         a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
500         k = !(l & FLAGS);
501 .Ed
502 .Pp
503 Casts are not followed by a space.
504 Note that
505 .Xr indent 1
506 does not understand this rule.
507 Also, for the purposes of formatting, treat
508 .Ic return
509 and
510 .Ic sizeof
511 as functions.  In other words, they are not
512 followed by a space, and their single argument
513 should be enclosed in parentheses.
514 .Pp
515 Exits should be 0 on success, or according to the predefined
516 values in
517 .Xr sysexits 3 .
518 .Bd -literal
519         exit(EX_OK);    /*
520                          * Avoid obvious comments such as
521                          * "Exit 0 on success."
522                          */
523 }
524 .Ed
525 .Pp
526 The function type should be on a line by itself
527 preceding the function.
528 .Bd -literal
529 static char *
530 function(int a1, int a2, float fl, int a4)
531 {
532 .Ed
533 .Pp
534 When declaring variables in functions declare them sorted by size,
535 then in alphabetical order; multiple ones per line are okay.
536 If a line overflows reuse the type keyword.
537 .Pp
538 Be careful to not obfuscate the code by initializing variables in
539 the declarations.
540 Use this feature only thoughtfully.
541 DO NOT use function calls in initializers.
542 .Bd -literal
543         struct foo one, *two;
544         double three;
545         int *four, five;
546         char *six, seven, eight, nine, ten, eleven, twelve;
547
548         four = myfunction();
549 .Ed
550 .Pp
551 Do not declare functions inside other functions; ANSI C says that
552 such declarations have file scope regardless of the nesting of the
553 declaration.
554 Hiding file declarations in what appears to be a local
555 scope is undesirable and will elicit complaints from a good compiler.
556 .Pp
557 .Dv NULL
558 is the preferred null pointer constant.
559 Use
560 .Dv NULL
561 instead of
562 .Vt ( "type *" ) Ns 0
563 or
564 .Vt ( "type *" ) Ns Dv NULL
565 in contexts where the compiler knows the
566 type, e.g., in assignments.
567 Use
568 .Vt ( "type *" ) Ns Dv NULL
569 in other contexts,
570 in particular for all function args.
571 (Casting is essential for
572 variadic args and is necessary for other args if the function prototype
573 might not be in scope.)
574 Test pointers against
575 .Dv NULL ,
576 e.g., use:
577 .Bd -literal
578 (p = f()) == NULL
579 .Ed
580 .Pp
581 not:
582 .Bd -literal
583 !(p = f())
584 .Ed
585 .Pp
586 Do not use
587 .Ic \&!
588 for tests unless it is a boolean, e.g. use
589 .Bd -literal
590 if (*p == '\e0')
591 .Ed
592 .Pp
593 not
594 .Bd -literal
595 if (!*p)
596 .Ed
597 .Pp
598 Do not cast the unused return value of a function to (void).
599 .Pp
600 Routines returning
601 .Vt "void *"
602 should not have their return values cast
603 to any pointer type.
604 .Pp
605 Use
606 .Xr err 3
607 or
608 .Xr warn 3 ,
609 do not roll your own.
610 .Bd -literal
611         if ((four = malloc(sizeof(struct foo))) == NULL)
612                 err(1, NULL);
613         if ((six = (int *)overflow()) == NULL)
614                 errx(1, "number overflowed");
615         return(eight);
616 }
617 .Ed
618 .Pp
619 Avoid old-style function declarations that look like this:
620 .Bd -literal
621 static char *
622 function(a1, a2, fl, a4)
623         int a1, a2;     /* Declare ints, too, don't default them. */
624         float fl;       /* Beware double vs. float prototype differences. */
625         int a4;         /* List in order declared. */
626 {
627 .Ed
628 .Pp
629 Use ANSI function declarations instead.
630 Long parameter lists are wrapped so that the first parameter on each line
631 lines up.
632 .Pp
633 Try to avoid using obsolete functions such as:
634 .Xr ftime 3 ,
635 .Xr getwd 3 ,
636 .Xr index 3 ,
637 .Xr rindex 3 ,
638 .Xr mktemp 3
639 and
640 .Xr utimes 3 .
641 .Pp
642 All new code must avoid using unbounded string functions.  For example,
643 .Xr strlcpy 3
644 should be used instead of
645 .Xr strcpy 3 ,
646 and
647 .Xr snprintf 3
648 should be used instead of
649 .Xr sprintf 3 .
650 .Pp
651 Varargs procedures should be formatted as follows:
652 .Bd -literal
653 #include <stdarg.h>
654
655 void
656 vaf(const char *fmt, ...)
657 {
658         va_list va;
659
660         va_start(va, fmt);
661         STUFF;
662         va_end(va);
663         /* No return needed for void functions. */
664 }
665 .Ed
666 .Pp
667 Use
668 .Xr printf 3 ,
669 not
670 .Xr fputs 3 ,
671 .Xr puts 3 ,
672 .Xr putchar 3 ,
673 whatever; it is faster and usually cleaner, not
674 to mention avoiding stupid bugs.
675 .Pp
676 Usage statements should look like the manual pages
677 .Sx SYNOPSIS .
678 The usage statement should be structured in the following order:
679 .Bl -enum
680 .It
681 Options without operands come first,
682 in alphabetical order,
683 inside a single set of brackets
684 .Ql ( \&[
685 and
686 .Ql \&] ) .
687 .It
688 Options with operands come next,
689 also in alphabetical order,
690 with each option and its argument inside its own pair of brackets.
691 .It
692 Required arguments
693 (if any)
694 are next,
695 listed in the order they should be specified on the command line.
696 .It
697 Finally,
698 any optional arguments should be listed,
699 listed in the order they should be specified,
700 and all inside brackets.
701 .El
702 .Pp
703 A bar
704 .Pq Ql \&|
705 separates
706 .Dq either-or
707 options/arguments,
708 and multiple options/arguments which are specified together are
709 placed in a single set of brackets.
710 .Bd -literal -offset 4n
711 "usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
712 "usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
713 .Ed
714 .Bd -literal
715 void
716 usage(void)
717 {
718         fprintf(stderr, "usage: f [-ab]\en");
719         exit(EX_USAGE);
720 }
721 .Ed
722 .Pp
723 Note that the manual page options description should list the options in
724 pure alphabetical order.
725 That is, without regard to whether an option takes arguments or not.
726 The alphabetical ordering should take into account the case ordering
727 shown above.
728 .Pp
729 New core kernel code should be reasonably compliant with the
730 .Nm
731 guides.
732 The guidelines for third-party maintained modules and device drivers are more
733 relaxed but at a minimum should be internally consistent with their style.
734 .Pp
735 Stylistic changes (including whitespace changes) are hard on the source
736 repository and are to be avoided without good reason.
737 Code that is approximately
738 .Dx
739 KNF
740 .Nm
741 compliant in the repository must not diverge from compliance.
742 .Pp
743 .Dx Ap s
744 default warning options are a reasonable subset and -Werror is enabled for
745 kernel and world, so passing
746 .Cm buildworld
747 or
748 .Cm buildkernel
749 alone is a good check.
750 The warnings of most recent compilers are of high quality.
751 Further analysis can be done using one of the various code checkers such as
752 .Xr cppcheck 1
753 or
754 .Xr clang 1 Ap s
755 static analyzer.
756 .Sh SEE ALSO
757 .Xr indent 1 ,
758 .Xr err 3 ,
759 .Xr sysexits 3 ,
760 .Xr warn 3
761 .Sh HISTORY
762 This man page is largely based on the
763 .Pa src/admin/style/style
764 file from the
765 .Bx 4.4 Lite2
766 release, with occasional updates to reflect the current practice and
767 desire of the
768 .Dx
769 project.