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