xref: /freebsd/share/man/man9/style.9 (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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
124include files,
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
250Enumeration values are all uppercase.
251.Bd -literal
252enum enumtype { ONE, TWO } et;
253.Ed
254.Pp
255In declarations, do not put any whitespace between asterisks and
256adjacent tokens, except for tokens that are identifiers related to
257types.
258(These identifiers are the names of basic types, type
259qualifiers, and
260.Ic typedef Ns -names
261other than the one being declared.)
262Separate these identifiers from asterisks using a single space.
263.Pp
264When declaring variables in structures, declare them sorted by use, then
265by size, and then in alphabetical order.
266The first category normally does not apply, but there are exceptions.
267Each one gets its own line.
268Try to make the structure
269readable by aligning the member names using either one or two tabs
270depending upon your judgment.
271You should use one tab only if it suffices to align at least 90% of
272the member names.
273Names following extremely long types
274should be separated by a single space.
275.Pp
276Major structures should be declared at the top of the file in which they
277are used, or in separate header files if they are used in multiple
278source files.
279Use of the structures should be by separate declarations
280and should be
281.Ic extern
282if they are declared in a header file.
283.Bd -literal
284struct foo {
285	struct foo	*next;		/* List of active foo. */
286	struct mumble	amumble;	/* Comment for mumble. */
287	int		bar;		/* Try to align the comments. */
288	struct verylongtypename *baz;	/* Won't fit in 2 tabs. */
289};
290struct foo *foohead;			/* Head of global foo list. */
291.Ed
292.Pp
293Use
294.Xr queue 3
295macros rather than rolling your own lists, whenever possible.
296Thus,
297the previous example would be better written:
298.Bd -literal
299#include <sys/queue.h>
300
301struct foo {
302	LIST_ENTRY(foo)	link;		/* Use queue macros for foo lists. */
303	struct mumble	amumble;	/* Comment for mumble. */
304	int		bar;		/* Try to align the comments. */
305	struct verylongtypename *baz;	/* Won't fit in 2 tabs. */
306};
307LIST_HEAD(, foo) foohead;		/* Head of global foo list. */
308.Ed
309.Pp
310Avoid using typedefs for structure types.
311This makes it impossible
312for applications to use pointers to such a structure opaquely, which
313is both possible and beneficial when using an ordinary struct tag.
314When convention requires a
315.Ic typedef ,
316make its name match the struct tag.
317Avoid typedefs ending in
318.Dq Li _t ,
319except as specified in Standard C or by
320.Tn POSIX .
321.Bd -literal
322/* Make the structure name match the typedef. */
323typedef	struct bar {
324	int	level;
325} BAR;
326typedef	int		foo;		/* This is foo. */
327typedef	const long	baz;		/* This is baz. */
328.Ed
329.Pp
330All functions are prototyped somewhere.
331.Pp
332Function prototypes for private functions (i.e. functions not used
333elsewhere) go at the top of the first source module.
334Functions
335local to one source module should be declared
336.Ic static .
337.Pp
338Functions used from other parts of the kernel are prototyped in the
339relevant include file.
340Function prototypes should be listed in a logical order, preferably
341alphabetical unless there is a compelling reason to use a different
342ordering.
343.Pp
344Functions that are used locally in more than one module go into a
345separate header file, e.g.\&
346.Qq Pa extern.h .
347.Pp
348Do not use the
349.Dv __P
350macro.
351.Pp
352In general code can be considered
353.Dq "new code"
354when it makes up about 50% or more of the file(s) involved.
355This is enough
356to break precedents in the existing code and use the current
357.Nm
358guidelines.
359.Pp
360The kernel has a name associated with parameter types, e.g., in the kernel
361use:
362.Bd -literal
363void	function(int fd);
364.Ed
365.Pp
366In header files visible to userland applications, prototypes that are
367visible must use either
368.Dq protected
369names (ones beginning with an underscore)
370or no names with the types.
371It is preferable to use protected names.
372E.g., use:
373.Bd -literal
374void	function(int);
375.Ed
376.Pp
377or:
378.Bd -literal
379void	function(int _fd);
380.Ed
381.Pp
382Prototypes may have an extra space after a tab to enable function names
383to line up:
384.Bd -literal
385static char	*function(int _arg, const char *_arg2, struct foo *_arg3,
386		    struct bar *_arg4);
387static void	 usage(void);
388
389/*
390 * All major routines should have a comment briefly describing what
391 * they do.  The comment before the "main" routine should describe
392 * what the program does.
393 */
394int
395main(int argc, char *argv[])
396{
397	char *ep;
398	long num;
399	int ch;
400.Ed
401.Pp
402For consistency,
403.Xr getopt 3
404should be used to parse options.
405Options
406should be sorted in the
407.Xr getopt 3
408call and the
409.Ic switch
410statement, unless
411parts of the
412.Ic switch
413cascade.
414Elements in a
415.Ic switch
416statement that cascade should have a
417.Li FALLTHROUGH
418comment.
419Numerical arguments should be checked for accuracy.
420Code that cannot be reached should have a
421.Li NOTREACHED
422comment.
423.Bd -literal
424	while ((ch = getopt(argc, argv, "abn:")) != -1)
425		switch (ch) {		/* Indent the switch. */
426		case 'a':		/* Don't indent the case. */
427			aflag = 1;
428			/* FALLTHROUGH */
429		case 'b':
430			bflag = 1;
431			break;
432		case 'n':
433			num = strtol(optarg, &ep, 10);
434			if (num <= 0 || *ep != '\e0') {
435				warnx("illegal number, -n argument -- %s",
436				    optarg);
437				usage();
438			}
439			break;
440		case '?':
441		default:
442			usage();
443			/* NOTREACHED */
444		}
445	argc -= optind;
446	argv += optind;
447.Ed
448.Pp
449Space after keywords
450.Pq Ic if , while , for , return , switch .
451No braces
452.Ql ( \&{
453and
454.Ql \&} )
455are
456used for control statements with zero or only a single statement unless that
457statement is more than a single line in which case they are permitted.
458Forever loops are done with
459.Ic for Ns 's ,
460not
461.Ic while Ns 's .
462.Bd -literal
463	for (p = buf; *p != '\e0'; ++p)
464		;	/* nothing */
465	for (;;)
466		stmt;
467	for (;;) {
468		z = a + really + long + statement + that + needs +
469		    two + lines + gets + indented + four + spaces +
470		    on + the + second + and + subsequent + lines;
471	}
472	for (;;) {
473		if (cond)
474			stmt;
475	}
476	if (val != NULL)
477		val = realloc(val, newsize);
478.Ed
479.Pp
480Parts of a
481.Ic for
482loop may be left empty.
483Do not put declarations
484inside blocks unless the routine is unusually complicated.
485.Bd -literal
486	for (; cnt < 15; cnt++) {
487		stmt1;
488		stmt2;
489	}
490.Ed
491.Pp
492Indentation is an 8 character tab.
493Second level indents are four spaces.
494If you have to wrap a long statement, put the operator at the end of the
495line.
496.Bd -literal
497	while (cnt < 20 && this_variable_name_is_too_long &&
498	    ep != NULL)
499		z = a + really + long + statement + that + needs +
500		    two + lines + gets + indented + four + spaces +
501		    on + the + second + and + subsequent + lines;
502.Ed
503.Pp
504Do not add whitespace at the end of a line, and only use tabs
505followed by spaces
506to form the indentation.
507Do not use more spaces than a tab will produce
508and do not use spaces in front of tabs.
509.Pp
510Closing and opening braces go on the same line as the
511.Ic else .
512Braces that are not necessary may be left out.
513.Bd -literal
514	if (test)
515		stmt;
516	else if (bar) {
517		stmt;
518		stmt;
519	} else
520		stmt;
521.Ed
522.Pp
523No spaces after function names.
524Commas have a space after them.
525No spaces
526after
527.Ql \&(
528or
529.Ql \&[
530or preceding
531.Ql \&]
532or
533.Ql \&)
534characters.
535.Bd -literal
536	error = function(a1, a2);
537	if (error != 0)
538		exit(error);
539.Ed
540.Pp
541Unary operators do not require spaces, binary operators do.
542Do not use parentheses unless they are required for precedence or unless the
543statement is confusing without them.
544Remember that other people may
545confuse easier than you.
546Do YOU understand the following?
547.Bd -literal
548	a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
549	k = !(l & FLAGS);
550.Ed
551.Pp
552Exits should be 0 on success, or according to the predefined
553values in
554.Xr sysexits 3 .
555.Bd -literal
556	exit(EX_OK);	/*
557			 * Avoid obvious comments such as
558			 * "Exit 0 on success."
559			 */
560}
561.Ed
562.Pp
563The function type should be on a line by itself
564preceding the function.
565The opening brace of the function body should be
566on a line by itself.
567.Bd -literal
568static char *
569function(int a1, int a2, float fl, int a4)
570{
571.Ed
572.Pp
573When declaring variables in functions declare them sorted by size,
574then in alphabetical order; multiple ones per line are okay.
575If a line overflows reuse the type keyword.
576.Pp
577Be careful to not obfuscate the code by initializing variables in
578the declarations.
579Use this feature only thoughtfully.
580DO NOT use function calls in initializers.
581.Bd -literal
582	struct foo one, *two;
583	double three;
584	int *four, five;
585	char *six, seven, eight, nine, ten, eleven, twelve;
586
587	four = myfunction();
588.Ed
589.Pp
590Do not declare functions inside other functions; ANSI C says that
591such declarations have file scope regardless of the nesting of the
592declaration.
593Hiding file declarations in what appears to be a local
594scope is undesirable and will elicit complaints from a good compiler.
595.Pp
596Casts and
597.Ic sizeof Ns 's
598are not followed by a space.
599Note that
600.Xr indent 1
601does not understand this rule.
602.Ic sizeof Ns 's
603are written with parenthesis always.
604The redundant parenthesis rules do not apply to
605.Fn sizeof var
606instances.
607.Pp
608.Dv NULL
609is the preferred null pointer constant.
610Use
611.Dv NULL
612instead of
613.Vt ( "type *" ) Ns 0
614or
615.Vt ( "type *" ) Ns Dv NULL
616in contexts where the compiler knows the
617type, e.g., in assignments.
618Use
619.Vt ( "type *" ) Ns Dv NULL
620in other contexts,
621in particular for all function args.
622(Casting is essential for
623variadic args and is necessary for other args if the function prototype
624might not be in scope.)
625Test pointers against
626.Dv NULL ,
627e.g., use:
628.Pp
629.Bd -literal
630(p = f()) == NULL
631.Ed
632.Pp
633not:
634.Bd -literal
635!(p = f())
636.Ed
637.Pp
638Do not use
639.Ic \&!
640for tests unless it is a boolean, e.g. use
641.Bd -literal
642if (*p == '\e0')
643.Ed
644.Pp
645not
646.Bd -literal
647if (!*p)
648.Ed
649.Pp
650Routines returning
651.Vt "void *"
652should not have their return values cast
653to any pointer type.
654.Pp
655Values in
656.Ic return
657statements should be enclosed in parentheses.
658.Pp
659Use
660.Xr err 3
661or
662.Xr warn 3 ,
663do not roll your own.
664.Bd -literal
665	if ((four = malloc(sizeof(struct foo))) == NULL)
666		err(1, (char *)NULL);
667	if ((six = (int *)overflow()) == NULL)
668		errx(1, "number overflowed");
669	return (eight);
670}
671.Ed
672.Pp
673Old-style function declarations look like this:
674.Bd -literal
675static char *
676function(a1, a2, fl, a4)
677	int a1, a2;	/* Declare ints, too, don't default them. */
678	float fl;	/* Beware double vs. float prototype differences. */
679	int a4;		/* List in order declared. */
680{
681.Ed
682.Pp
683Use ANSI function declarations unless you explicitly need K&R compatibility.
684Long parameter lists are wrapped with a normal four space indent.
685.Pp
686Variable numbers of arguments should look like this.
687.Bd -literal
688#include <stdarg.h>
689
690void
691vaf(const char *fmt, ...)
692{
693	va_list ap;
694
695	va_start(ap, fmt);
696	STUFF;
697	va_end(ap);
698	/* No return needed for void functions. */
699}
700
701static void
702usage()
703{
704	/* Insert an empty line if the function has no local variables. */
705.Ed
706.Pp
707Use
708.Xr printf 3 ,
709not
710.Xr fputs 3 ,
711.Xr puts 3 ,
712.Xr putchar 3 ,
713whatever; it is faster and usually cleaner, not
714to mention avoiding stupid bugs.
715.Pp
716Usage statements should look like the manual pages
717.Sx SYNOPSIS .
718The usage statement should be structured in the following order:
719.Bl -enum
720.It
721Options without operands come first,
722in alphabetical order,
723inside a single set of brackets
724.Ql ( \&[
725and
726.Ql \&] ) .
727.It
728Options with operands come next,
729also in alphabetical order,
730with each option and its argument inside its own pair of brackets.
731.It
732Required arguments
733(if any)
734are next,
735listed in the order they should be specified on the command line.
736.It
737Finally,
738any optional arguments should be listed,
739listed in the order they should be specified,
740and all inside brackets.
741.El
742.Pp
743A bar
744.Pq Ql \&|
745separates
746.Dq either-or
747options/arguments,
748and multiple options/arguments which are specified together are
749placed in a single set of brackets.
750.Bd -literal -offset 4n
751"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
752"usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
753.Ed
754.Bd -literal
755	(void)fprintf(stderr, "usage: f [-ab]\en");
756	exit(EX_USAGE);
757}
758.Ed
759.Pp
760Note that the manual page options description should list the options in
761pure alphabetical order.
762That is, without regard to whether an option takes arguments or not.
763The alphabetical ordering should take into account the case ordering
764shown above.
765.Pp
766New core kernel code should be reasonably compliant with the
767.Nm
768guides.
769The guidelines for third-party maintained modules and device drivers are more
770relaxed but at a minimum should be internally consistent with their style.
771.Pp
772Stylistic changes (including whitespace changes) are hard on the source
773repository and are to be avoided without good reason.
774Code that is approximately
775.Fx
776KNF
777.Nm
778compliant in the repository must not diverge from compliance.
779.Pp
780Whenever possible, code should be run through a code checker
781(e.g.,
782.Xr lint 1
783or
784.Nm gcc Fl Wall )
785and produce minimal warnings.
786.Sh SEE ALSO
787.Xr indent 1 ,
788.Xr lint 1 ,
789.Xr err 3 ,
790.Xr sysexits 3 ,
791.Xr warn 3 ,
792.Xr style.Makefile 5
793.Sh HISTORY
794This man page is largely based on the
795.Pa src/admin/style/style
796file from the
797.Bx 4.4 Lite2
798release, with occasional updates to reflect the current practice and
799desire of the
800.Fx
801project.
802