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