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