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