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