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