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.75 2020/02/03 22:33:04 schwarze Exp $ 26.\" 27.Dd $Mdocdate: February 3 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 174Enumeration values are all uppercase. 175.Bd -literal -offset indent 176enum enumtype { ONE, TWO } et; 177.Ed 178.Pp 179When defining unsigned integers use 180.Dq "unsigned int" 181rather than just 182.Dq "unsigned" ; 183the latter has been a source of confusion in the past. 184.Pp 185When declaring variables in structures, declare them sorted by use, then 186by size (largest to smallest), then by alphabetical order. 187The first category normally doesn't apply, but there are exceptions. 188Each one gets its own line. 189Put a tab after the first word, i.e., use 190.Ql int^Ix; 191and 192.Ql struct^Ifoo *x; . 193.Pp 194Major structures should be declared at the top of the file in which they 195are used, or in separate header files if they are used in multiple 196source files. 197Use of the structures should be by separate declarations and should be 198.Dq Li extern 199if they are declared in a header file. 200.Bd -literal -offset indent 201struct foo { 202 struct foo *next; /* List of active foo */ 203 struct mumble amumble; /* Comment for mumble */ 204 int bar; 205}; 206struct foo *foohead; /* Head of global foo list */ 207.Ed 208.Pp 209Use 210.Xr queue 3 211macros rather than rolling your own lists, whenever possible. 212Thus, the previous example would be better written: 213.Bd -literal -offset indent 214#include <sys/queue.h> 215struct foo { 216 LIST_ENTRY(foo) link; /* Queue macro glue for foo lists */ 217 struct mumble amumble; /* Comment for mumble */ 218 int bar; 219}; 220LIST_HEAD(, foo) foohead; /* Head of global foo list */ 221.Ed 222.Pp 223Avoid using typedefs for structure types. 224This makes it impossible 225for applications to use pointers to such a structure opaquely, which 226is both possible and beneficial when using an ordinary struct tag. 227When convention requires a typedef, make its name match the struct tag. 228Avoid typedefs ending in 229.Dq Li \&_t , 230except as specified in Standard C or by POSIX. 231.Bd -literal -offset indent 232/* 233 * All major routines should have a comment briefly describing what 234 * they do. The comment before the "main" routine should describe 235 * what the program does. 236 */ 237int 238main(int argc, char *argv[]) 239{ 240 int aflag, bflag, ch, num; 241 const char *errstr; 242.Ed 243.Pp 244For consistency, 245.Xr getopt 3 246should be used to parse options. 247Options should be sorted in the 248.Xr getopt 3 249call and the switch statement, unless 250parts of the switch cascade. 251Elements in a switch statement that cascade should have a FALLTHROUGH comment. 252Numerical arguments should be checked for accuracy. 253.Bd -literal -offset indent 254while ((ch = getopt(argc, argv, "abn:")) != -1) { 255 switch (ch) { /* Indent the switch. */ 256 case 'a': /* Don't indent the case. */ 257 aflag = 1; 258 /* FALLTHROUGH */ 259 case 'b': 260 bflag = 1; 261 break; 262 case 'n': 263 num = strtonum(optarg, 0, INT_MAX, &errstr); 264 if (errstr) { 265 warnx("number is %s: %s", errstr, optarg); 266 usage(); 267 } 268 break; 269 default: 270 usage(); 271 } 272} 273argc -= optind; 274argv += optind; 275.Ed 276.Pp 277Use a space after keywords 278.Pf ( Li if , 279.Li while , 280.Li for , 281.Li return , 282.Li switch ) . 283No braces are 284used for control statements with zero or only a single statement unless that 285statement is more than a single line, in which case they are permitted. 286.Bd -literal -offset indent 287for (p = buf; *p != '\e0'; ++p) 288 continue; 289for (;;) 290 stmt; 291for (;;) { 292 z = a + really + long + statement + that + needs + 293 two + lines + gets + indented + four + spaces + 294 on + the + second + and + subsequent + lines; 295} 296for (;;) { 297 if (cond) 298 stmt; 299} 300.Ed 301.Pp 302Parts of a for loop may be left empty. 303.Bd -literal -offset indent 304for (; cnt < 15; cnt++) { 305 stmt1; 306 stmt2; 307} 308.Ed 309.Pp 310Indentation is an 8 character tab. 311Second level indents are four spaces. 312All code should fit in 80 columns. 313.Bd -literal -offset indent 314while (cnt < 20) 315 z = a + really + long + statement + that + needs + 316 two + lines + gets + indented + four + spaces + 317 on + the + second + and + subsequent + lines; 318.Ed 319.Pp 320Do not add whitespace at the end of a line, and only use tabs 321followed by spaces to form the indentation. 322Do not use more spaces than a tab will produce 323and do not use spaces in front of tabs. 324.Pp 325Closing and opening braces go on the same line as the else. 326Braces that aren't necessary may be left out, unless they cause 327a compiler warning. 328.Bd -literal -offset indent 329if (test) 330 stmt; 331else if (bar) { 332 stmt; 333 stmt; 334} else 335 stmt; 336.Ed 337.Pp 338Do not use spaces after function names. 339Commas have a space after them. 340Do not use spaces after 341.Sq \&( 342or 343.Sq \&[ 344or preceding 345.Sq \&] 346or 347.Sq \&) 348characters. 349.Bd -literal -offset indent 350if ((error = function(a1, a2))) 351 exit(error); 352.Ed 353.Pp 354Unary operators don't require spaces; binary operators do. 355Don't use parentheses unless they're required for precedence, the statement 356is confusing without them, or the compiler generates a warning without them. 357Remember that other people may be confused more easily than you. 358Do YOU understand the following? 359.Bd -literal -offset indent 360a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 361k = !(l & FLAGS); 362.Ed 363.Pp 364Exits should be 0 on success, or non-zero for errors. 365.Bd -literal -offset indent 366/* 367 * Avoid obvious comments such as 368 * "Exit 0 on success." 369 */ 370exit(0); 371.Ed 372.Pp 373The function type should be on a line by itself 374preceding the function. 375.Bd -literal -offset indent 376static char * 377function(int a1, int a2, float fl, int a4) 378{ 379.Ed 380.Pp 381When declaring variables in functions, declare them sorted by size (largest to 382smallest), then in alphabetical order; multiple ones per line are okay. 383If a line overflows, reuse the type keyword. 384.Pp 385Be careful not to obfuscate the code by initializing variables in 386the declarations. 387Use this feature only thoughtfully. 388DO NOT use function calls in initializers! 389.Bd -literal -offset indent 390struct foo one, *two; 391double three; 392int *four, five; 393char *six, seven, eight, nine, ten, eleven, twelve; 394 395four = myfunction(); 396.Ed 397.Pp 398Do not declare functions inside other functions. 399.Pp 400Casts and 401.Fn sizeof 402calls are not followed by a space. 403Note that 404.Xr indent 1 405does not understand this rule. 406.Pp 407Use of the 408.Dq register 409specifier is discouraged in new code. 410Optimizing compilers such as gcc can generally do a better job 411of choosing which variables to place in registers to improve 412code performance. 413The exception to this is in functions containing assembly code where the 414.Dq register 415specifier is required for proper code generation in the absence of 416compiler optimization. 417.Pp 418When using 419.Fn longjmp 420or 421.Fn vfork 422in a program, the 423.Fl W 424or 425.Fl Wall 426flag should be used to verify that the compiler does not generate 427warnings such as 428.Bd -literal -offset indent 429warning: variable `foo' might be clobbered by `longjmp' or `vfork'. 430.Ed 431.Pp 432If any warnings of this type occur, you must apply the 433.Dq volatile 434type-qualifier to the variable in question. 435Failure to do so may result in improper code generation when optimization 436is enabled. 437Note that for pointers, the location of 438.Dq volatile 439specifies if the type-qualifier applies to the pointer, or the thing being 440pointed to. 441A volatile pointer is declared with 442.Dq volatile 443to the right of the 444.Dq * . 445Example: 446.Bd -literal -offset indent 447char *volatile foo; 448.Ed 449.Pp 450says that 451.Dq foo 452is volatile, but 453.Dq *foo 454is not. 455To make 456.Dq *foo 457volatile use the syntax 458.Bd -literal -offset indent 459volatile char *foo; 460.Ed 461.Pp 462If both the pointer and the thing pointed to are volatile use 463.Bd -literal -offset indent 464volatile char *volatile foo; 465.Ed 466.Pp 467.Dq const 468is also a type-qualifier and the same rules apply. 469The description of a read-only hardware register might look something like: 470.Bd -literal -offset indent 471const volatile char *reg; 472.Ed 473.Pp 474Global flags set inside signal handlers should be of type 475.Dq volatile sig_atomic_t 476if possible. 477This guarantees that the variable may be accessed as an atomic entity, 478even when a signal has been delivered. 479Global variables of other types (such as structures) are not 480guaranteed to have consistent values when accessed via a signal handler. 481.Pp 482.Dv NULL 483is the preferred null pointer constant. 484Use 485.Dv NULL 486instead of 487(type\ *)0 or (type\ *)NULL in all cases except for arguments to variadic 488functions where the compiler does not know the type. 489.Pp 490Don't use 491.Ql \&! 492for tests unless it's a boolean, i.e., use 493.Bd -literal -offset indent 494if (*p == '\e0') 495.Ed 496not 497.Bd -literal -offset indent -compact 498if (!*p) 499.Ed 500.Pp 501Routines returning 502.Li void * 503should not have their return values cast to any pointer type. 504.Pp 505Use the 506.Xr err 3 507and 508.Xr warn 3 509family of functions. 510Don't roll your own! 511.Bd -literal -offset indent 512if ((four = malloc(sizeof(struct foo))) == NULL) 513 err(1, NULL); 514if ((six = (int *)overflow()) == NULL) 515 errx(1, "Number overflowed."); 516return eight; 517.Ed 518.Pp 519Always use ANSI function definitions. 520Long parameter lists are wrapped with a normal four space indent. 521.Pp 522Variable numbers of arguments should look like this: 523.Bd -literal -offset indent 524#include <stdarg.h> 525 526void 527vaf(const char *fmt, ...) 528{ 529 va_list ap; 530 va_start(ap, fmt); 531 532 STUFF; 533 534 va_end(ap); 535 536 /* No return needed for void functions. */ 537} 538 539static void 540usage(void) 541{ 542.Ed 543.Pp 544Usage statements should take the same form as the synopsis in manual pages. 545Options without 546operands come first, in alphabetical order inside a single set of 547braces, followed by options with operands, in alphabetical order, 548each in braces, followed by required arguments in the order they 549are specified, followed by optional arguments in the order they 550are specified. 551.Pp 552A bar 553.Pq Sq \&| 554separates either-or options/arguments, 555and multiple options/arguments which are specified together are 556placed in a single set of braces. 557.Pp 558If numbers are used as options, they should be placed first, 559as shown in the example below. 560Uppercase letters take precedence over lowercase. 561.Bd -literal -offset indent 562"usage: f [-12aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 563"usage: f [-a | -b] [-c [-de] [-n number]]\en" 564.Ed 565.Pp 566The 567.Xr getprogname 3 568function may be used instead of hard-coding the program name. 569.Bd -literal -offset indent 570fprintf(stderr, "usage: %s [-ab]\en", getprogname()); 571exit(1); 572.Ed 573.Pp 574New core kernel code should be reasonably compliant with the style guides. 575The guidelines for third-party maintained modules and device drivers are more 576relaxed but at a minimum should be internally consistent with their style. 577.Pp 578Whenever possible, code should be run through a code checker 579(e.g., 580.Dq Li gcc -Wall -W -Wpointer-arith -Wbad-function-cast ...\& 581or splint from the ports tree) and produce minimal warnings. 582Since lint has been removed, the only lint-style comment that should 583be used is FALLTHROUGH, as it's useful to humans. 584Other lint-style comments such as ARGSUSED, LINTED, and NOTREACHED 585may be deleted. 586.Pp 587Note that documentation follows its own style guide, 588as documented in 589.Xr mdoc 7 . 590.Sh FILES 591.Bl -tag -width "/usr/share/misc/license.template " -compact 592.It Pa /usr/share/misc/license.template 593Example license for new code. 594.El 595.Sh SEE ALSO 596.Xr indent 1 , 597.Xr err 3 , 598.Xr queue 3 , 599.Xr warn 3 , 600.Xr mdoc 7 601.Sh HISTORY 602This man page is largely based on the src/admin/style/style file from the 603.Bx 4.4 Lite2 604release, with updates to reflect the current practice and 605desire of the 606.Ox 607project. 608