xref: /freebsd/share/man/man9/style.9 (revision 6990ffd8a95caaba6858ad44ff1b3157d1efba8f)
1.\" Copyright (c) 1995 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 14, 1995
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.  It is also a guide for preferred userland code style.
36.Bd -literal
37/*
38 * Style guide for FreeBSD.  Based on the CSRG's KNF (Kernel Normal Form).
39 *
40 *	@(#)style	1.14 (Berkeley) 4/28/95
41 * $FreeBSD$
42 */
43
44/*
45 * VERY important single-line comments look like this.
46 */
47
48/* Most single-line comments look like this. */
49
50/*
51 * Multi-line comments look like this.  Make them real sentences.  Fill
52 * them so they look like real paragraphs.
53 */
54.Ed
55.Pp
56After any copyright header, there is a blank line, and the
57.Va rcsid
58for source files.
59Version control system ID tags should only exist once in a file
60(unlike this one).
61Non-C/C++ source files follow the example above, while C/C++ source files
62follow the one below.
63All VCS (version control system) revision identification from files obtained
64from elsewhere should be maintained, including, where applicable, multiple IDs
65showing a file's history.
66In general, keep the IDs intact, including any `$'s.
67There is no reason to add "From" in front of foreign VCS IDs.
68Most
69.No non- Ns Fx
70VCS IDs should be indented by a tab if in a comment.
71.Bd -literal
72#include <sys/cdefs.h>
73__RCSID("@(#)style	1.14 (Berkeley) 4/28/95")
74__FBSDID("$FreeBSD$")
75.Ed
76.Pp
77Leave another blank line before the header files.
78.Pp
79Kernel include files (i.e. sys/*.h) come first; normally, include
80<sys/types.h>
81OR <sys/param.h>, but not both.  <sys/types.h> includes <sys/cdefs.h>,
82and it's okay to depend on that.
83.Bd -literal
84#include <sys/types.h>	/* Non-local includes in angle brackets. */
85.Ed
86.Pp
87For a network program, put the network include files next.
88.Bd -literal
89#include <net/if.h>
90#include <net/if_dl.h>
91#include <net/route.h>
92#include <netinet/in.h>
93#include <protocols/rwhod.h>
94.Ed
95.Pp
96Leave a blank line before the next group, the /usr include files,
97which should be sorted alphabetically by name.
98.Bd -literal
99#include <stdio.h>
100.Ed
101.Pp
102Global pathnames are defined in /usr/include/paths.h.  Pathnames local
103to the program go in pathnames.h in the local directory.
104.Bd -literal
105#include <paths.h>
106.Ed
107.Pp
108Leave another blank line before the user include files.
109.Bd -literal
110#include "pathnames.h"		/* Local includes in double quotes. */
111.Ed
112.Pp
113Do not #define or declare names in the implementation namespace except
114for implementing application interfaces.
115.Pp
116The names of
117.Dq Li unsafe
118macros (ones that have side effects), and the names of macros for
119manifest constants, are all in uppercase.
120The expansions of expression-like macros are either a single token
121or have outer parentheses.
122Put a single tab character between the
123.Ql #define
124and the macro name.
125If a macro is an inline expansion of a function, the function name is
126all in lowercase and the macro has the same name all in uppercase.
127.\" XXX the above conflicts with ANSI style where the names are the
128.\" same and you #undef the macro (if any) to get the function.
129.\" It is not followed for MALLOC(), and not very common if inline
130.\" functions are used.
131If a
132macro needs more than a single line, use braces
133.Sq ( \&{
134and
135.Sq \&} ) .
136Right-justify the
137backslashes; it makes it easier to read.
138If the macro encapsulates a compound statement, enclose it in a
139.Dq Li do
140loop,
141so that it can safely be used in
142.Dq Li if
143statements.
144Any final statement-terminating semicolon should be
145supplied by the macro invocation rather than the macro, to make parsing easier
146for pretty-printers and editors.
147.Bd -literal
148#define	MACRO(x, y) do {						\e
149	variable = (x) + (y);						\e
150	(y) += 2;							\e
151} while(0)
152.Ed
153.Pp
154Enumeration values are all uppercase.
155.Bd -literal
156enum enumtype { ONE, TWO } et;
157.Ed
158.Pp
159When declaring variables in structures, declare them sorted by use, then
160by size, and then by alphabetical order.  The first category normally
161doesn't apply, but there are exceptions.  Each one gets its own line.
162Put a tab after the first word, i.e. use
163.Ql int^Ix;
164and
165.Ql struct^Ifoo *x; .
166.Pp
167Major structures should be declared at the top of the file in which they
168are used, or in separate header files if they are used in multiple
169source files.  Use of the structures should be by separate declarations
170and should be "extern" if they are declared in a header file.
171.Bd -literal
172struct foo {
173	struct	foo *next;	/* List of active foo */
174	struct	mumble amumble;	/* Comment for mumble */
175	int	bar;
176};
177struct foo *foohead;		/* Head of global foo list */
178.Ed
179.Pp
180Use
181.Xr queue 3
182macros rather than rolling your own lists, whenever possible.  Thus,
183the previous example would be better written:
184.Bd -literal
185#include <sys/queue.h>
186struct foo {
187	LIST_ENTRY(foo)	link;	/* Queue macro glue for foo lists */
188	struct	mumble amumble;	/* Comment for mumble */
189	int	bar;
190};
191LIST_HEAD(, foo) foohead;	/* Head of global foo list */
192.Ed
193.Pp
194Avoid using typedefs for structure types.  This makes it impossible
195for applications to use pointers to such a structure opaquely, which
196is both possible and beneficial when using an ordinary struct tag.
197When convention requires a typedef, make its name match the struct
198tag.  Avoid typedefs ending in
199.Dq Li \&_t ,
200except as specified in Standard C or by
201.Tn POSIX .
202.Bd -literal
203/* Make the structure name match the typedef. */
204typedef struct bar {
205	int	level;
206} BAR;
207.Ed
208.Pp
209All functions are prototyped somewhere.
210.Pp
211Function prototypes for private functions (i.e. functions not used
212elsewhere) go at the top of the first source module.  Functions
213local to one source module should be declared
214.Ql static .
215.Pp
216Functions used from other parts of the kernel are prototyped in the
217relevant include file.
218.Pp
219Functions that are used locally in more than one module go into a
220separate header file, e.g.\&
221.Pa extern.h .
222.Pp
223Only use the __P macro from the include file <sys/cdefs.h> if the source
224file in general is (to be) compilable with a K&R Old Testament compiler.
225Use of the __P macro in new code is discouraged, although modifications
226to existing files should be consistent with that file's conventions.
227.Pp
228In general code can be considered
229.Dq new code
230when it makes up about 50% or more of the file[s] involved.  This is enough
231to break precedents in the existing code and use the current style guidelines.
232.Pp
233The kernel has a name associated with parameter types, e.g., in the kernel
234use:
235.Bd -literal
236void	function(int fd);
237.Ed
238.Pp
239In header files visible to userland applications, prototypes that are
240visible must use either protected names or no names with the types.  It
241is preferable to use protected names.
242E.g., use:
243.Bd -literal
244void	function(int);
245.Ed
246.Pp
247or:
248.Bd -literal
249void	function(int _fd);
250.Ed
251.Pp
252Prototypes may have an extra space after a tab to enable function names
253to line up:
254.Bd -literal
255static char	*function(int _arg, const char *_arg2, struct foo *_arg3,
256		    struct bar *_arg4);
257static void	 usage(void);
258
259/*
260 * All major routines should have a comment briefly describing what
261 * they do.  The comment before the "main" routine should describe
262 * what the program does.
263 */
264int
265main(int argc, char *argv[])
266{
267	long num;
268	int ch;
269	char *ep;
270
271.Ed
272.Pp
273For consistency, getopt should be used to parse options.  Options
274should be sorted in the getopt call and the switch statement, unless
275parts of the switch cascade.  Elements in a switch statement that
276cascade should have a FALLTHROUGH comment.  Numerical arguments
277should be checked for accuracy.  Code that cannot be reached should
278have a NOTREACHED comment.
279.Bd -literal
280	while ((ch = getopt(argc, argv, "abn:")) != -1)
281		switch (ch) {		/* Indent the switch. */
282		case 'a':		/* Don't indent the case. */
283			aflag = 1;
284			/* FALLTHROUGH */
285		case 'b':
286			bflag = 1;
287			break;
288		case 'n':
289			num = strtol(optarg, &ep, 10);
290			if (num <= 0 || *ep != '\e0') {
291				warnx("illegal number, -n argument -- %s",
292				    optarg);
293				usage();
294			}
295			break;
296		case '?':
297		default:
298			usage();
299			/* NOTREACHED */
300		}
301	argc -= optind;
302	argv += optind;
303
304.Ed
305.Pp
306Space after keywords (if, while, for, return, switch).  No braces are
307used for control statements with zero or only a single statement unless that
308statement is more than a single line in which case they are permitted.
309Forever loops are done with for's, not while's.
310.Bd -literal
311	for (p = buf; *p != '\e0'; ++p)
312		;	/* nothing */
313	for (;;)
314		stmt;
315	for (;;) {
316		z = a + really + long + statement + that + needs +
317		    two lines + gets + indented + four + spaces +
318		    on + the + second + and + subsequent + lines;
319	}
320	for (;;) {
321		if (cond)
322			stmt;
323	}
324	if (val != NULL)
325		val = realloc(val, newsize);
326.Ed
327.Pp
328Parts of a for loop may be left empty.  Don't put declarations
329inside blocks unless the routine is unusually complicated.
330.Bd -literal
331	for (; cnt < 15; cnt++) {
332		stmt1;
333		stmt2;
334	}
335.Ed
336.Pp
337Indentation is an 8 character tab.
338Second level indents are four spaces.
339If you have to wrap a long statement, put the operator at the end of the
340line.
341.Bd -literal
342	while (cnt < 20 && this_variable_name_is_too_long_for_its_own_good &&
343	    ep != NULL)
344		z = a + really + long + statement + that + needs +
345		    two lines + gets + indented + four + spaces +
346		    on + the + second + and + subsequent + lines;
347.Ed
348.Pp
349Do not add whitespace at the end of a line, and only use tabs
350followed by spaces
351to form the indentation.  Do not use more spaces than a tab will produce
352and do not use spaces in front of tabs.
353.Pp
354Closing and opening braces go on the same line as the else.
355Braces that aren't necessary may be left out.
356.Bd -literal
357	if (test)
358		stmt;
359	else if (bar) {
360		stmt;
361		stmt;
362	} else
363		stmt;
364.Ed
365.Pp
366No spaces after function names.  Commas have a space after them.  No spaces
367after
368.Sq \&(
369or
370.Sq \&[
371or preceding
372.Sq \&]
373or
374.Sq \&)
375characters.
376.Bd -literal
377	error = function(a1, a2);
378	if (error != 0)
379		exit(error);
380.Ed
381.Pp
382Unary operators don't require spaces, binary operators do.  Don't
383use parentheses unless they're required for precedence or unless the
384statement is confusing without them.  Remember that other people may
385confuse easier than you.  Do YOU understand the following?
386.Bd -literal
387	a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
388	k = !(l & FLAGS);
389.Ed
390.Pp
391Exits should be 0 on success, or according to the predefined
392values in
393.Xr sysexits 3 .
394.Bd -literal
395	exit(EX_OK);	/*
396			 * Avoid obvious comments such as
397			 * "Exit 0 on success."
398			 */
399}
400.Ed
401.Pp
402The function type should be on a line by itself
403preceding the function.
404.Bd -literal
405static char *
406function(int a1, int a2, float fl, int a4)
407{
408.Ed
409.Pp
410When declaring variables in functions declare them sorted by size,
411then in alphabetical order; multiple ones per line are okay.
412If a line overflows reuse the type keyword.
413.Pp
414Be careful to not obfuscate the code by initializing variables in
415the declarations.  Use this feature only thoughtfully.
416DO NOT use function calls in initializers.
417.Bd -literal
418	struct foo one, *two;
419	double three;
420	int *four, five;
421	char *six, seven, eight, nine, ten, eleven, twelve;
422
423	four = myfunction();
424.Ed
425.Pp
426Do not declare functions inside other functions; ANSI C says that
427such declarations have file scope regardless of the nesting of the
428declaration.  Hiding file declarations in what appears to be a local
429scope is undesirable and will elicit complaints from a good compiler.
430.Pp
431Casts and sizeof's are not followed by a space.  Note that
432.Xr indent 1
433does not understand this rule.
434.Pp
435NULL is the preferred null pointer constant.  Use NULL instead of
436(type *)0 or (type *)NULL in contexts where the compiler knows the
437type, e.g., in assignments.  Use (type *)NULL in other contexts,
438in particular for all function args.  (Casting is essential for
439variadic args and is necessary for other args if the function prototype
440might not be in scope.)
441Test pointers
442against NULL, e.g., use:
443.Bd -literal
444(p = f()) == NULL
445.Ed
446.Pp
447not:
448.Bd -literal
449!(p = f())
450.Ed
451.Pp
452Don't use '!' for tests unless it's a boolean, e.g. use
453.Bd -literal
454if (*p == '\e0')
455.Ed
456.Pp
457not
458.Bd -literal
459if (!*p)
460.Ed
461.Pp
462Routines returning void * should not have their return values cast
463to any pointer type.
464.Pp
465Use
466.Xr err 3
467or
468.Xr warn 3 ,
469don't roll your own.
470.Bd -literal
471	if ((four = malloc(sizeof(struct foo))) == NULL)
472		err(1, (char *)NULL);
473	if ((six = (int *)overflow()) == NULL)
474		errx(1, "number overflowed");
475	return (eight);
476}
477.Ed
478.Pp
479Old-style function declarations look like this:
480.Bd -literal
481static char *
482function(a1, a2, fl, a4)
483	int a1, a2;	/* Declare ints, too, don't default them. */
484	float fl;	/* Beware double vs. float prototype differences. */
485	int a4;		/* List in order declared. */
486{
487.Ed
488.Pp
489Use ANSI function declarations unless you explicitly need K&R compatibility.
490Long parameter lists are wrapped with a normal four space indent.
491.Pp
492Variable numbers of arguments should look like this.
493.Bd -literal
494#include <stdarg.h>
495
496void
497vaf(const char *fmt, ...)
498{
499	va_list ap;
500
501	va_start(ap, fmt);
502	STUFF;
503	va_end(ap);
504	/* No return needed for void functions. */
505}
506
507static void
508usage()
509{
510	/* Insert an empty line if the function has no local variables. */
511.Ed
512.Pp
513Use
514.Xr printf 3 ,
515not fputs/puts/putchar/whatever; it's faster and usually cleaner, not
516to mention avoiding stupid bugs.
517.Pp
518Usage statements should look like the manual pages synopsis.
519The usage statement should be structured in the following order:
520.Pp
521.Bl -enum
522.It
523Options without operands come first,
524in alphabetical order,
525inside a single set of brackets
526.Sq ( \&[
527and
528.Sq \&] ) .
529.It
530Options with operands come next,
531also in alphabetical order,
532with each option and its argument inside its own pair of brackets.
533.It
534Required arguments
535(if any)
536are next,
537listed in the order they should be specified in the command line.
538.It
539Finally,
540any optional arguments should be listed,
541listed in the order they should be specified,
542and all inside brackets.
543.El
544.Pp
545A bar
546.Pq Sq \&|
547separates either-or options/arguments,
548and multiple options/arguments which are specified together are
549placed in a single set of brackets.
550.Pp
551.Bd -ragged -offset 4n
552"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
553"usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
554.Ed
555.Bd -literal
556	(void)fprintf(stderr, "usage: f [-ab]\en");
557	exit(EX_USAGE);
558}
559.Ed
560.Pp
561Note that the manual page options description should list the options in
562pure alphabetical order.
563That is, without regard to whether an option takes arguments or not.
564The alphabetical ordering should take into account the case ordering
565shown above.
566.Pp
567New core kernel code should be reasonably compliant with the style guides.
568The guidelines for third-party maintained modules and device drivers are more
569relaxed but at a minimum should be internally consistent with their style.
570.Pp
571Stylistic changes (including whitespace changes) are hard on the source
572repository and are to be avoided without good reason.  Code that is
573approximately
574.Fx
575KNF
576.Xr style 9
577compliant in the repository must not diverge from compliance.
578.Pp
579Whenever possible, code should be run through a code checker
580(e.g.,
581.Xr lint 1
582or
583"gcc -Wall") and produce minimal warnings.
584.Sh SEE ALSO
585.Xr indent 1 ,
586.Xr lint 1 ,
587.Xr err 3 ,
588.Xr sysexits 3 ,
589.Xr warn 3
590.Sh HISTORY
591This man page is largely based on the src/admin/style/style file from
592the
593.Bx 4.4 Lite2
594release, with updates to reflect the current practice and
595desire of the
596.Fx
597project.
598