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.20 2001/06/28 22:14:23 millert Exp $ 26.\" 27.Dd June 18, 2001 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 0i 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. Fill 57 * them so they look like real paragraphs. 58 */ 59.Ed 60.Pp 61Kernel include files (i.e., 62.Pa Aq sys/*.h ) 63come first; normally, you'll need 64.Pa Aq sys/types.h 65OR 66.Pa Aq sys/param.h , 67but not both! 68.Pa Aq sys/types.h 69includes 70.Pa Aq sys/cdefs.h , 71and it's okay to depend on that. 72.Bd -literal -offset 0i 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 0i 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 87include files. 88The 89.Pa /usr 90include files should be sorted! 91.Bd -literal -offset 0i 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 0i 101#include <paths.h> 102.Ed 103.Pp 104Then, there's a blank line, and the user include files. 105.Bd -literal -offset 0i 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 125Only use the 126.Li __P 127macro from the include file 128.Pa Aq sys/cdefs.h 129if the source file in general is (to be) compilable with a K&R compiler. 130Use of the 131.Li __P 132macro in new code is discouraged, although modifications to existing 133files should be consistent with that file's conventions. 134Prototypes should not have variable names associated with the types; i.e.: 135.Bd -literal -compact -offset 0i 136void function(int); 137.Ed 138.Pp 139not: 140.Bd -literal -compact -offset 0i 141void function(int a); 142.Ed 143.Pp 144Prototypes may have an extra space after a tab to enable function names 145to line up: 146.Bd -literal -offset 0i 147static char *function(int, const char *); 148static void usage(void); 149.Ed 150.Pp 151There should be no space between the function name and the argument list. 152.Pp 153Use 154.Li __dead 155from 156.Pa Aq sys/cdefs.h 157for functions that don't return, e.g., 158.Bd -literal -offset 0i 159__dead void abort(void); 160.Ed 161.Pp 162In header files, put function prototypes within 163.Dv __BEGIN_DECLS / __END_DECLS 164matching pairs. 165This makes the header file usable from C++. 166.Pp 167Macros are capitalized and parenthesized, and should avoid side-effects. 168If they are an inline expansion of a function, the function is defined 169all in lowercase; the macro has the same name all in uppercase. 170If the macro needs more than a single line, use braces. 171Right-justify the backslashes, as the resulting definition is easier to read. 172If the macro encapsulates a compound statement, enclose it in a 173.Dq Li do 174loop, 175so that it can safely be used in 176.Dq Li if 177statements. 178Any final statement-terminating semicolon should be 179supplied by the macro invocation rather than the macro, to make parsing easier 180for pretty-printers and editors. 181.Bd -literal -offset 0i 182#define MACRO(x, y) do { \e 183 variable = (x) + (y); \e 184 (y) += 2; \e 185} while (0) 186.Ed 187.Pp 188Enumeration values are all uppercase. 189.Bd -literal -offset 0i 190enum enumtype { ONE, TWO } et; 191.Ed 192.Pp 193When declaring variables in structures, declare them sorted by use, then 194by size (largest to smallest), then by alphabetical order. 195The first category normally doesn't apply, but there are exceptions. 196Each one gets its own line. 197Put a tab after the first word, i.e., use 198.Ql int^Ix; 199and 200.Ql struct^Ifoo *x; . 201.Pp 202Major structures should be declared at the top of the file in which they 203are used, or in separate header files if they are used in multiple 204source files. 205Use of the structures should be by separate declarations and should be 206.Dq Li extern 207if they are declared in a header file. 208.Bd -literal -offset 0i 209struct foo { 210 struct foo *next; /* List of active foo */ 211 struct mumble amumble; /* Comment for mumble */ 212 int bar; 213}; 214struct foo *foohead; /* Head of global foo list */ 215.Ed 216.Pp 217Use 218.Xr queue 3 219macros rather than rolling your own lists, whenever possible. 220Thus, the previous example would be better written: 221.Bd -literal -offset 0i 222#include <sys/queue.h> 223struct foo { 224 LIST_ENTRY(foo) link; /* Queue macro glue for foo lists */ 225 struct mumble amumble; /* Comment for mumble */ 226 int bar; 227}; 228LIST_HEAD(, foo) foohead; /* Head of global foo list */ 229.Ed 230.Pp 231Avoid using typedefs for structure types. 232This makes it impossible 233for applications to use pointers to such a structure opaquely, which 234is both possible and beneficial when using an ordinary struct tag. 235When convention requires a typedef, make its name match the struct tag. 236Avoid typedefs ending in 237.Dq Li \&_t , 238except as specified in Standard C or by 239.Tn POSIX . 240Don't use the same name for a struct tag and a typedef, as this makes 241the code unusable from C++. 242.Bd -literal -offset 0i 243/* Make the structure name match the typedef. */ 244typedef struct _bar { 245 int level; 246} BAR; 247.Ed 248.Pp 249.Bd -literal -offset 0i 250/* 251 * All major routines should have a comment briefly describing what 252 * they do. The comment before the "main" routine should describe 253 * what the program does. 254 */ 255int 256main(int argc, char *argv[]) 257{ 258 long num; 259 int ch; 260 char *ep; 261 262.Ed 263.Pp 264For consistency, 265.Xr getopt 3 266should be used to parse options. 267Options should be sorted in the 268.Xr getopt 3 269call and the switch statement, unless 270parts of the switch cascade. 271Elements in a switch statement that cascade should have a FALLTHROUGH comment. 272Numerical arguments should be checked for accuracy. 273Code that cannot be reached should have a NOTREACHED comment, 274.Bd -literal -offset 0i 275 while ((ch = getopt(argc, argv, "abn:")) != -1) 276 switch (ch) { /* Indent the switch. */ 277 case 'a': /* Don't indent the case. */ 278 aflag = 1; 279 /* FALLTHROUGH */ 280 case 'b': 281 bflag = 1; 282 break; 283 case 'n': 284 num = strtol(optarg, &ep, 10); 285 if (num <= 0 || *ep != '\e0') { 286 warnx("illegal number, -n argument -- %s", 287 optarg); 288 usage(); 289 } 290 break; 291 case '?': 292 default: 293 usage(); 294 /* NOTREACHED */ 295 } 296 argc -= optind; 297 argv += optind; 298 299.Ed 300.Pp 301Use space after keywords 302.Pf ( Li if , 303.Li while , 304.Li for , 305.Li return , 306.Li switch ) . 307No braces are 308used for control statements with zero or only a single statement unless that 309statement is more than a single line, in which case they are permitted. 310Forever loops are done with 311.Li for , 312not 313.Li while . 314.Bd -literal -offset 0i 315 for (p = buf; *p != '\e0'; ++p) 316 ; /* nothing */ 317 for (;;) 318 stmt; 319 for (;;) { 320 z = a + really + long + statement + that + needs + 321 two + lines + gets + indented + four + spaces + 322 on + the + second + and + subsequent + lines; 323 } 324 for (;;) { 325 if (cond) 326 stmt; 327 } 328.Ed 329.Pp 330Parts of a for loop may be left empty. 331Don't put declarations inside blocks unless the routine is 332unusually complicated. 333.Bd -literal -offset 0i 334 for (; cnt < 15; cnt++) { 335 stmt1; 336 stmt2; 337 } 338.Ed 339.Pp 340Indentation is an 8 character tab. 341Second level indents are four spaces. 342.Bd -literal -offset 0i 343 while (cnt < 20) 344 z = a + really + long + statement + that + needs + 345 two lines + gets + indented + four + spaces + 346 on + the + second + and + subsequent + lines; 347.Ed 348.Pp 349Do not add whitespace at the end of a line, and only use tabs 350followed by spaces to form the indentation. 351Do not use more spaces than a tab will produce 352and do not use spaces in front of tabs. 353.Pp 354Closing and opening braces go on the same line as the else. 355Braces that aren't necessary may be left out, unless they cause 356a compiler warning. 357.Bd -literal -offset 0i 358 if (test) 359 stmt; 360 else if (bar) { 361 stmt; 362 stmt; 363 } else 364 stmt; 365.Ed 366.Pp 367Do not use spaces after function names. 368Commas have a space after them. 369Do not use spaces after 370.Sq \&( 371or 372.Sq \&[ 373or preceding 374.Sq \&] 375or 376.Sq \&) 377characters. 378.Bd -literal -offset 0i 379 if (error = function(a1, a2)) 380 exit(error); 381.Ed 382.Pp 383Unary operators don't require spaces, binary operators do. 384Don't use parentheses unless they're required for precedence, the statement 385is confusing without them, or the compiler generates a warning without them. 386Remember that other people may be confused more easily than you. 387Do YOU understand the following? 388.Bd -literal -offset 0i 389 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 390 k = !(l & FLAGS); 391.Ed 392.Pp 393Exits should be 0 on success, or according to the predefined 394values in 395.Xr sysexits 3 . 396.Bd -literal -offset 0i 397 exit(EX_OK); /* 398 * Avoid obvious comments such as 399 * "Exit 0 on success." 400 */ 401} 402.Ed 403.Pp 404The function type should be on a line by itself 405preceding the function. 406.Bd -literal -offset 0i 407static char * 408function(int a1, int a2, float fl, int a4) 409{ 410.Ed 411.Pp 412When declaring variables in functions declare them sorted by size (largest to 413smallest), then in alphabetical order; multiple ones per line are okay. 414Old style function declarations should be avoided. 415ANSI style function declarations should go in an include file such as 416.Dq Pa extern.h . 417If a line overflows reuse the type keyword. 418.Pp 419Be careful to not obfuscate the code by initializing variables in 420the declarations. 421Use this feature only thoughtfully. 422DO NOT use function calls in initializers! 423.Bd -literal -offset 0i 424 struct foo one, *two; 425 double three; 426 int *four, five; 427 char *six, seven, eight, nine, ten, eleven, twelve; 428 429 four = myfunction(); 430.Ed 431.Pp 432Do not declare functions inside other functions; ANSI C says that 433such declarations have file scope regardless of the nesting of the 434declaration. 435Hiding file declarations in what appears to be a local scope is 436undesirable and will elicit complaints from a good compiler, such as 437.Dq Li gcc -Wtraditional . 438.Pp 439Casts and 440.Fn sizeof 441calls are not followed by a space. Note that 442.Xr indent 1 443does not understand this rule. 444.Pp 445.Dv NULL 446is the preferred null pointer constant. 447Use 448.Dv NULL 449instead of 450(type\ *)0 or (type\ *)NULL in contexts where the compiler knows the 451type, e.g., in assignments. 452Use (type\ *)NULL in other contexts, in particular for all function args. 453(Casting is essential for variadic args and is necessary for other args 454if the function prototype might not be in scope.) 455Test pointers 456against 457.Dv NULL , 458e.g., use: 459.Bd -literal -offset 0i 460(p = f()) == NULL 461.Ed 462.Pp 463not: 464.Bd -literal -offset 0i 465!(p = f()) 466.Ed 467.Pp 468Don't use 469.Ql \&! 470for tests unless it's a boolean, e.g., use 471.Bd -literal -offset 0i 472if (*p == '\e0') 473.Ed 474.Pp 475not 476.Bd -literal -offset 0i 477if (!*p) 478.Ed 479.Pp 480Routines returning 481.Li void * 482should not have their return values cast to any pointer type. 483.Pp 484Use 485.Xr err 3 486or 487.Xr warn 3 , 488don't roll your own! 489.Bd -literal -offset 0i 490 if ((four = malloc(sizeof(struct foo))) == NULL) 491 err(1, (char *)NULL); 492 if ((six = (int *)overflow()) == NULL) 493 errx(1, "Number overflowed."); 494 return (eight); 495} 496.Ed 497.Pp 498Old-style function declarations look like this: 499.Bd -literal -offset 0i 500static char * 501function(a1, a2, fl, a4) 502 int a1, a2; /* Declare ints, too, don't default them. */ 503 float fl; /* Beware double vs. float prototype differences. */ 504 int a4; /* List in order declared. */ 505{ 506 ... 507} 508.Ed 509.Pp 510Use ANSI function declarations unless you explicitly need K&R compatibility. 511Long parameter lists are wrapped with a normal four space indent. 512.Pp 513Variable numbers of arguments should look like this: 514.Bd -literal -offset 0i 515#include <stdarg.h> 516 517void 518vaf(const char *fmt, ...) 519{ 520 va_list ap; 521 va_start(ap, fmt); 522 523 STUFF; 524 525 va_end(ap); 526 527 /* No return needed for void functions. */ 528} 529 530static void 531usage() 532{ 533 extern char *__progname; /* from crt0.o */ 534.Ed 535.Pp 536Usage statements should look like the manual pages. 537Options without 538operands come first, in alphabetical order inside a single set of 539braces, followed by options with operands, in alphabetical order, 540each in braces, followed by required arguments in the order they 541are specified, followed by optional arguments in the order they 542are specified. 543A bar 544.Pq Sq \&| 545separates either-or options/arguments, 546and multiple options/arguments which are specified together are 547placed in a single set of braces. 548.Pp 549.Bd -ragged -offset 0.3i 550"usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 551"usage: f [-a | -b] [-c [-de] [-n number]]\en" 552.Ed 553.Pp 554The 555.Li __progname 556string, should be used instead of hard-coding the program name. 557.Bd -literal -offset 0i 558 (void)fprintf(stderr, "usage: %s [-ab]\en", __progname); 559 exit(1); 560} 561.Ed 562.Pp 563New core kernel code should be reasonably compliant with the style guides. 564The guidelines for third-party maintained modules and device drivers are more 565relaxed but at a minimum should be internally consistent with their style. 566.Pp 567Stylistic changes (including whitespace changes) are hard on the source 568repository and are to be avoided without good reason. 569Code that is approximately KNF compliant in the repository must not diverge 570from compliance. 571.Pp 572Whenever possible, code should be run through a code checker 573(e.g., 574.Dq Li gcc -Wall -W -Wtraditional -Wpointer-arith -Wbad-function-cast ... , 575.Xr lint 1 576or lclint from the ports tree) and produce minimal warnings. 577.Sh SEE ALSO 578.Xr indent 1 , 579.Xr err 3 , 580.Xr queue 3 , 581.Xr sysexits 3 , 582.Xr warn 3 583.Sh HISTORY 584This man page is largely based on the src/admin/style/style file from 585the 586.Tn BSD 5874.4-Lite2 release, with updates to reflect the current practice and 588desire of the 589.Ox 590project. 591