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