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