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