xref: /openbsd-src/share/man/man9/style.9 (revision 46035553bfdd96e63c94e32da0210227ec2e3cf1)
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.\"	$OpenBSD: style.9,v 1.76 2020/05/10 00:56:06 guenther Exp $
26.\"
27.Dd $Mdocdate: May 10 2020 $
28.Dt STYLE 9
29.Os
30.Sh NAME
31.Nm style
32.Nd Kernel source file style guide (KNF)
33.Sh DESCRIPTION
34This file specifies the preferred style for kernel source files in the
35.Ox
36source tree.
37It is also a guide for preferred userland code style.
38These guidelines should be followed for all new code.
39In general, code can be considered
40.Dq new code
41when it makes up about 50% or more of the file(s) involved.
42This is enough to break precedents in the existing code and use the
43current style guidelines.
44.Bd -literal -offset indent
45/*
46 * Style guide for the OpenBSD KNF (Kernel Normal Form).
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.
57 * Fill them so they look like real paragraphs.
58 */
59.Ed
60.Pp
61Kernel include files (i.e.,
62.In sys/*.h )
63come first; normally, you'll need
64.In sys/types.h
65OR
66.In sys/param.h ,
67but not both!
68.In sys/types.h
69includes
70.In sys/cdefs.h ,
71and it's okay to depend on that.
72.Bd -literal -offset indent
73#include <sys/types.h>	/* Non-local includes in brackets. */
74.Ed
75.Pp
76If it's a network program, put the network include files next.
77.Bd -literal -offset indent
78#include <net/if.h>
79#include <net/if_dl.h>
80#include <net/route.h>
81#include <netinet/in.h>
82.Ed
83.Pp
84Then there's a blank line, followed by the
85.Pa /usr/include
86files.
87The
88.Pa /usr/include
89files, for the most part, should be sorted.
90.Pp
91Global pathnames are defined in
92.Pa /usr/include/paths.h .
93Pathnames local to the program go in
94.Pa pathnames.h
95in the local directory.
96.Bd -literal -offset indent
97#include <paths.h>
98.Ed
99.Pp
100Then there's a blank line, and the user include files.
101.Bd -literal -offset indent
102#include "pathnames.h"	/* Local includes in double quotes. */
103.Ed
104.Pp
105All functions are prototyped somewhere.
106.Pp
107Function prototypes for private functions (i.e., functions not used
108elsewhere) go at the top of the first source module.
109In userland, functions local to one source module should be declared
110.Ql static .
111This should not be done in kernel land since it makes it impossible
112to use the kernel debugger.
113.Pp
114Functions used from other files are prototyped in the
115relevant include file.
116.Pp
117Functions that are used locally in more than one module go into a
118separate header file, e.g.,
119.Pa extern.h .
120.Pp
121Prototypes should not have variable names associated with the types; i.e.,
122.Bd -literal -offset indent
123void	function(int);
124.Ed
125not:
126.Bd -literal -offset indent -compact
127void	function(int a);
128.Ed
129.Pp
130Prototypes may have an extra space after a tab to enable function names
131to line up:
132.Bd -literal -offset indent
133static char	*function(int, const char *);
134static void	 usage(void);
135.Ed
136.Pp
137There should be no space between the function name and the argument list.
138.Pp
139Use
140.Li __dead
141from
142.In sys/cdefs.h
143for functions that don't return, i.e.,
144.Bd -literal -offset indent
145__dead void	abort(void);
146.Ed
147.Pp
148In header files, put function prototypes within
149.Dv __BEGIN_DECLS / __END_DECLS
150matching pairs.
151This makes the header file usable from C++.
152.Pp
153Macros are capitalized and parenthesized, and should avoid side-effects.
154If they are an inline expansion of a function, the function is defined
155all in lowercase; the macro has the same name all in uppercase.
156If the macro needs more than a single line, use braces.
157Right-justify the backslashes, as the resulting definition is easier to read.
158If the macro encapsulates a compound statement, enclose it in a
159.Dq Li do
160loop,
161so that it can safely be used in
162.Dq Li if
163statements.
164Any final statement-terminating semicolon should be
165supplied by the macro invocation rather than the macro, to make parsing easier
166for pretty-printers and editors.
167.Bd -literal -offset indent
168#define	MACRO(x, y) do {					\e
169	variable = (x) + (y);					\e
170	(y) += 2;						\e
171} while (0)
172.Ed
173.Pp
174If a macro with arguments declares local variables,
175those variables should use identifiers beginning with two underscores.
176This is required for macros implementing C and POSIX interfaces
177and recommended for all macros for consistency.
178.Pp
179Enumeration values are all uppercase.
180.Bd -literal -offset indent
181enum enumtype { ONE, TWO } et;
182.Ed
183.Pp
184When defining unsigned integers use
185.Dq "unsigned int"
186rather than just
187.Dq "unsigned" ;
188the latter has been a source of confusion in the past.
189.Pp
190When declaring variables in structures, declare them sorted by use, then
191by size (largest to smallest), then by alphabetical order.
192The first category normally doesn't apply, but there are exceptions.
193Each one gets its own line.
194Put a tab after the first word, i.e., use
195.Ql int^Ix;
196and
197.Ql struct^Ifoo *x; .
198.Pp
199Major structures should be declared at the top of the file in which they
200are used, or in separate header files if they are used in multiple
201source files.
202Use of the structures should be by separate declarations and should be
203.Dq Li extern
204if they are declared in a header file.
205.Bd -literal -offset indent
206struct foo {
207	struct	foo *next;	/* List of active foo */
208	struct	mumble amumble;	/* Comment for mumble */
209	int	bar;
210};
211struct foo *foohead;		/* Head of global foo list */
212.Ed
213.Pp
214Use
215.Xr queue 3
216macros rather than rolling your own lists, whenever possible.
217Thus, the previous example would be better written:
218.Bd -literal -offset indent
219#include <sys/queue.h>
220struct	foo {
221	LIST_ENTRY(foo)	link;	/* Queue macro glue for foo lists */
222	struct	mumble amumble;	/* Comment for mumble */
223	int	bar;
224};
225LIST_HEAD(, foo) foohead;	/* Head of global foo list */
226.Ed
227.Pp
228Avoid using typedefs for structure types.
229This makes it impossible
230for applications to use pointers to such a structure opaquely, which
231is both possible and beneficial when using an ordinary struct tag.
232When convention requires a typedef, make its name match the struct tag.
233Avoid typedefs ending in
234.Dq Li \&_t ,
235except as specified in Standard C or by POSIX.
236.Bd -literal -offset indent
237/*
238 * All major routines should have a comment briefly describing what
239 * they do.  The comment before the "main" routine should describe
240 * what the program does.
241 */
242int
243main(int argc, char *argv[])
244{
245	int aflag, bflag, ch, num;
246	const char *errstr;
247.Ed
248.Pp
249For consistency,
250.Xr getopt 3
251should be used to parse options.
252Options should be sorted in the
253.Xr getopt 3
254call and the switch statement, unless
255parts of the switch cascade.
256Elements in a switch statement that cascade should have a FALLTHROUGH comment.
257Numerical arguments should be checked for accuracy.
258.Bd -literal -offset indent
259while ((ch = getopt(argc, argv, "abn:")) != -1) {
260	switch (ch) {		/* Indent the switch. */
261	case 'a':		/* Don't indent the case. */
262		aflag = 1;
263		/* FALLTHROUGH */
264	case 'b':
265		bflag = 1;
266		break;
267	case 'n':
268		num = strtonum(optarg, 0, INT_MAX, &errstr);
269		if (errstr) {
270			warnx("number is %s: %s", errstr, optarg);
271			usage();
272		}
273		break;
274	default:
275		usage();
276	}
277}
278argc -= optind;
279argv += optind;
280.Ed
281.Pp
282Use a space after keywords
283.Pf ( Li if ,
284.Li while ,
285.Li for ,
286.Li return ,
287.Li switch ) .
288No braces are
289used for control statements with zero or only a single statement unless that
290statement is more than a single line, in which case they are permitted.
291.Bd -literal -offset indent
292for (p = buf; *p != '\e0'; ++p)
293	continue;
294for (;;)
295	stmt;
296for (;;) {
297	z = a + really + long + statement + that + needs +
298	    two + lines + gets + indented + four + spaces +
299	    on + the + second + and + subsequent + lines;
300}
301for (;;) {
302	if (cond)
303		stmt;
304}
305.Ed
306.Pp
307Parts of a for loop may be left empty.
308.Bd -literal -offset indent
309for (; cnt < 15; cnt++) {
310	stmt1;
311	stmt2;
312}
313.Ed
314.Pp
315Indentation is an 8 character tab.
316Second level indents are four spaces.
317All code should fit in 80 columns.
318.Bd -literal -offset indent
319while (cnt < 20)
320	z = a + really + long + statement + that + needs +
321	    two + lines + gets + indented + four + spaces +
322	    on + the + second + and + subsequent + lines;
323.Ed
324.Pp
325Do not add whitespace at the end of a line, and only use tabs
326followed by spaces to form the indentation.
327Do not use more spaces than a tab will produce
328and do not use spaces in front of tabs.
329.Pp
330Closing and opening braces go on the same line as the else.
331Braces that aren't necessary may be left out, unless they cause
332a compiler warning.
333.Bd -literal -offset indent
334if (test)
335	stmt;
336else if (bar) {
337	stmt;
338	stmt;
339} else
340	stmt;
341.Ed
342.Pp
343Do not use spaces after function names.
344Commas have a space after them.
345Do not use spaces after
346.Sq \&(
347or
348.Sq \&[
349or preceding
350.Sq \&]
351or
352.Sq \&)
353characters.
354.Bd -literal -offset indent
355if ((error = function(a1, a2)))
356	exit(error);
357.Ed
358.Pp
359Unary operators don't require spaces; binary operators do.
360Don't use parentheses unless they're required for precedence, the statement
361is confusing without them, or the compiler generates a warning without them.
362Remember that other people may be confused more easily than you.
363Do YOU understand the following?
364.Bd -literal -offset indent
365a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
366k = !(l & FLAGS);
367.Ed
368.Pp
369Exits should be 0 on success, or non-zero for errors.
370.Bd -literal -offset indent
371/*
372 * Avoid obvious comments such as
373 * "Exit 0 on success."
374 */
375exit(0);
376.Ed
377.Pp
378The function type should be on a line by itself
379preceding the function.
380.Bd -literal -offset indent
381static char *
382function(int a1, int a2, float fl, int a4)
383{
384.Ed
385.Pp
386When declaring variables in functions, declare them sorted by size (largest to
387smallest), then in alphabetical order; multiple ones per line are okay.
388If a line overflows, reuse the type keyword.
389.Pp
390Be careful not to obfuscate the code by initializing variables in
391the declarations.
392Use this feature only thoughtfully.
393DO NOT use function calls in initializers!
394.Bd -literal -offset indent
395struct foo one, *two;
396double three;
397int *four, five;
398char *six, seven, eight, nine, ten, eleven, twelve;
399
400four = myfunction();
401.Ed
402.Pp
403Do not declare functions inside other functions.
404.Pp
405Casts and
406.Fn sizeof
407calls are not followed by a space.
408Note that
409.Xr indent 1
410does not understand this rule.
411.Pp
412Use of the
413.Dq register
414specifier is discouraged in new code.
415Optimizing compilers such as gcc can generally do a better job
416of choosing which variables to place in registers to improve
417code performance.
418The exception to this is in functions containing assembly code where the
419.Dq register
420specifier is required for proper code generation in the absence of
421compiler optimization.
422.Pp
423When using
424.Fn longjmp
425or
426.Fn vfork
427in a program, the
428.Fl W
429or
430.Fl Wall
431flag should be used to verify that the compiler does not generate
432warnings such as
433.Bd -literal -offset indent
434warning: variable `foo' might be clobbered by `longjmp' or `vfork'.
435.Ed
436.Pp
437If any warnings of this type occur, you must apply the
438.Dq volatile
439type-qualifier to the variable in question.
440Failure to do so may result in improper code generation when optimization
441is enabled.
442Note that for pointers, the location of
443.Dq volatile
444specifies if the type-qualifier applies to the pointer, or the thing being
445pointed to.
446A volatile pointer is declared with
447.Dq volatile
448to the right of the
449.Dq * .
450Example:
451.Bd -literal -offset indent
452char *volatile foo;
453.Ed
454.Pp
455says that
456.Dq foo
457is volatile, but
458.Dq *foo
459is not.
460To make
461.Dq *foo
462volatile use the syntax
463.Bd -literal -offset indent
464volatile char *foo;
465.Ed
466.Pp
467If both the pointer and the thing pointed to are volatile use
468.Bd -literal -offset indent
469volatile char *volatile foo;
470.Ed
471.Pp
472.Dq const
473is also a type-qualifier and the same rules apply.
474The description of a read-only hardware register might look something like:
475.Bd -literal -offset indent
476const volatile char *reg;
477.Ed
478.Pp
479Global flags set inside signal handlers should be of type
480.Dq volatile sig_atomic_t
481if possible.
482This guarantees that the variable may be accessed as an atomic entity,
483even when a signal has been delivered.
484Global variables of other types (such as structures) are not
485guaranteed to have consistent values when accessed via a signal handler.
486.Pp
487.Dv NULL
488is the preferred null pointer constant.
489Use
490.Dv NULL
491instead of
492(type\ *)0 or (type\ *)NULL in all cases except for arguments to variadic
493functions where the compiler does not know the type.
494.Pp
495Don't use
496.Ql \&!
497for tests unless it's a boolean, i.e., use
498.Bd -literal -offset indent
499if (*p == '\e0')
500.Ed
501not
502.Bd -literal -offset indent -compact
503if (!*p)
504.Ed
505.Pp
506Routines returning
507.Li void *
508should not have their return values cast to any pointer type.
509.Pp
510Use the
511.Xr err 3
512and
513.Xr warn 3
514family of functions.
515Don't roll your own!
516.Bd -literal -offset indent
517if ((four = malloc(sizeof(struct foo))) == NULL)
518	err(1, NULL);
519if ((six = (int *)overflow()) == NULL)
520	errx(1, "Number overflowed.");
521return eight;
522.Ed
523.Pp
524Always use ANSI function definitions.
525Long parameter lists are wrapped with a normal four space indent.
526.Pp
527Variable numbers of arguments should look like this:
528.Bd -literal -offset indent
529#include <stdarg.h>
530
531void
532vaf(const char *fmt, ...)
533{
534	va_list ap;
535	va_start(ap, fmt);
536
537	STUFF;
538
539	va_end(ap);
540
541	/* No return needed for void functions. */
542}
543
544static void
545usage(void)
546{
547.Ed
548.Pp
549Usage statements should take the same form as the synopsis in manual pages.
550Options without
551operands come first, in alphabetical order inside a single set of
552braces, followed by options with operands, in alphabetical order,
553each in braces, followed by required arguments in the order they
554are specified, followed by optional arguments in the order they
555are specified.
556.Pp
557A bar
558.Pq Sq \&|
559separates either-or options/arguments,
560and multiple options/arguments which are specified together are
561placed in a single set of braces.
562.Pp
563If numbers are used as options, they should be placed first,
564as shown in the example below.
565Uppercase letters take precedence over lowercase.
566.Bd -literal -offset indent
567"usage: f [-12aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
568"usage: f [-a | -b] [-c [-de] [-n number]]\en"
569.Ed
570.Pp
571The
572.Xr getprogname 3
573function may be used instead of hard-coding the program name.
574.Bd -literal -offset indent
575fprintf(stderr, "usage: %s [-ab]\en", getprogname());
576exit(1);
577.Ed
578.Pp
579New core kernel code should be reasonably compliant with the style guides.
580The guidelines for third-party maintained modules and device drivers are more
581relaxed but at a minimum should be internally consistent with their style.
582.Pp
583Whenever possible, code should be run through a code checker
584(e.g.,
585.Dq Li gcc -Wall -W -Wpointer-arith -Wbad-function-cast ...\&
586or splint from the ports tree) and produce minimal warnings.
587Since lint has been removed, the only lint-style comment that should
588be used is FALLTHROUGH, as it's useful to humans.
589Other lint-style comments such as ARGSUSED, LINTED, and NOTREACHED
590may be deleted.
591.Pp
592Note that documentation follows its own style guide,
593as documented in
594.Xr mdoc 7 .
595.Sh FILES
596.Bl -tag -width "/usr/share/misc/license.template " -compact
597.It Pa /usr/share/misc/license.template
598Example license for new code.
599.El
600.Sh SEE ALSO
601.Xr indent 1 ,
602.Xr err 3 ,
603.Xr queue 3 ,
604.Xr warn 3 ,
605.Xr mdoc 7
606.Sh HISTORY
607This man page is largely based on the src/admin/style/style file from the
608.Bx 4.4 Lite2
609release, with updates to reflect the current practice and
610desire of the
611.Ox
612project.
613