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