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.\" $FreeBSD$ 26.\" 27.Dd December 14, 1995 28.Dt STYLE 9 29.Os FreeBSD 30.Sh NAME 31.Nm style 32.Nd "Kernel source file style guide" 33.Sh DESCRIPTION 34This file specifies the preferred style for kernel source files in the 35.Tn FreeBSD 36source tree. It is also a guide for preferred userland code style. 37.Bd -literal -offset 0i 38/* 39 * Style guide for the FreeBSD KNF (Kernel Normal Form). 40 */ 41 42/* 43 * VERY important single-line comments look like this. 44 */ 45 46/* Most single-line comments look like this. */ 47 48/* 49 * Multi-line comments look like this. Make them real sentences. Fill 50 * them so they look like real paragraphs. 51 */ 52.Ed 53.Pp 54Kernel include files (i.e. sys/*.h) come first; normally, you'll need 55<sys/types.h> 56OR <sys/param.h>, but not both! <sys/types.h> includes <sys/cdefs.h>, 57and it's okay to depend on that. 58.Bd -literal -offset 0i 59#include <sys/types.h> /* Non-local includes in brackets. */ 60.Ed 61.Pp 62If it's a network program, put the network include files next. 63.Bd -literal -offset 0i 64#include <net/if.h> 65#include <net/if_dl.h> 66#include <net/route.h> 67#include <netinet/in.h> 68#include <protocols/rwhod.h> 69.Ed 70.Pp 71Then there's a blank line, followed by the /usr include files. 72The /usr include files should be sorted! 73.Bd -literal -offset 0i 74#include <stdio.h> 75.Ed 76.Pp 77Global pathnames are defined in /usr/include/paths.h. Pathnames local 78to the program go in pathnames.h in the local directory. 79.Bd -literal -offset 0i 80#include <paths.h> 81.Ed 82.Pp 83Then, there's a blank line, and the user include files. 84.Bd -literal -offset 0i 85#include "pathnames.h" /* Local includes in double quotes. */ 86.Ed 87.Pp 88Macros are capitalized, parenthesized, and should avoid side-effects. 89If they are an inline expansion of a function, the function is defined 90all in lowercase, the macro has the same name all in uppercase. If the 91macro needs more than a single line, use braces. Right-justify the 92backslashes; it makes it easier to read. 93If the macro encapsulates a compound statement, enclose it in a 94.Dq Li do 95loop, 96so that it can safely be used in 97.Dq Li if 98statements. 99Any final statement-terminating semicolon should be 100supplied by the macro invocation rather than the macro, to make parsing easier 101for pretty-printers and editors. 102.Bd -literal -offset 0i 103#define MACRO(x, y) do { \e 104 variable = (x) + (y); \e 105 (y) += 2; \e 106} while(0) 107.Ed 108.Pp 109Enumeration values are all uppercase. 110.Bd -literal -offset 0i 111enum enumtype { ONE, TWO } et; 112.Ed 113.Pp 114When declaring variables in structures, declare them sorted by use, then 115by size, and then by alphabetical order. The first category normally 116doesn't apply, but there are exceptions. Each one gets its own line. 117Put a tab after the first word, i.e. use 118.Ql int^Ix; 119and 120.Ql struct^Ifoo *x; . 121.Pp 122Major structures should be declared at the top of the file in which they 123are used, or in separate header files if they are used in multiple 124source files. Use of the structures should be by separate declarations 125and should be "extern" if they are declared in a header file. 126.Bd -literal -offset 0i 127struct foo { 128 struct foo *next; /* List of active foo */ 129 struct mumble amumble; /* Comment for mumble */ 130 int bar; 131}; 132struct foo *foohead; /* Head of global foo list */ 133.Ed 134.Pp 135Use 136.Xr queue 3 137macros rather than rolling your own lists, whenever possible. Thus, 138the previous example would be better written: 139.Bd -literal -offset 0i 140#include <sys/queue.h> 141struct foo { 142 LIST_ENTRY(foo) link; /* Queue macro glue for foo lists */ 143 struct mumble amumble; /* Comment for mumble */ 144 int bar; 145}; 146LIST_HEAD(, foo) foohead; /* Head of global foo list */ 147.Ed 148.Pp 149Avoid using typedefs for structure types. This makes it impossible 150for applications to use pointers to such a structure opaquely, which 151is both possible and beneficial when using an ordinary struct tag. 152When convention requires a typedef, make its name match the struct 153tag. Avoid typedefs ending in 154.Dq Li \&_t , 155except as specified in Standard C or by 156.Tn POSIX . 157.Bd -literal -offset 0i 158/* Make the structure name match the typedef. */ 159typedef struct _bar { 160 int level; 161} BAR; 162.Ed 163.Pp 164All functions are prototyped somewhere. 165.Pp 166Function prototypes for private functions (i.e. functions not used 167elsewhere) go at the top of the first source module. Functions 168local to one source module should be declared 169.Ql static . 170.Pp 171Functions used from other parts of the kernel are prototyped in the 172relevant include file. 173.Pp 174Functions that are used locally in more than one module go into a 175separate header file, e.g. 176.Pa extern.h . 177.Pp 178Only use the __P macro from the include file <sys/cdefs.h> if the source 179file in general is (to be) compilable with a K&R Old Testament compiler. 180Use of the __P macro in new code is discouraged, although modifications 181to existing files should be consistent with that file's conventions. 182.Pp 183In general code can be considered 184.Dq new code 185when it makes up about 50% or more of the file[s] involved. This is enough 186to break precedents in the existing code and use the current style guidelines. 187.Pp 188The kernel has a name associated with parameter types, e.g., in the kernel 189use: 190.Bd -literal -offset 0i 191void function(int fd); 192.Ed 193.Pp 194In header files visible to userland applications, prototypes that are 195visible must use either protected names or no names with the types. It 196is preferable to use protected names. 197e.g., use: 198.Bd -literal -offset 0i 199void function(int); 200.Ed 201.Pp 202or: 203.Bd -literal -offset 0i 204void function(int _fd); 205.Ed 206.Pp 207Prototypes may have an extra space after a tab to enable function names 208to line up: 209.Bd -literal -offset 0i 210static char *function(int _arg, const char *_arg2, struct foo *_arg3, 211 struct bar *_arg4); 212static void usage(void); 213 214/* 215 * All major routines should have a comment briefly describing what 216 * they do. The comment before the "main" routine should describe 217 * what the program does. 218 */ 219int 220main(int argc, char *argv[]) 221{ 222 long num; 223 int ch; 224 char *ep; 225 226.Ed 227.Pp 228For consistency, getopt should be used to parse options. Options 229should be sorted in the getopt call and the switch statement, unless 230parts of the switch cascade. Elements in a switch statement that 231cascade should have a FALLTHROUGH comment. Numerical arguments 232should be checked for accuracy. Code that cannot be reached should 233have a NOTREACHED comment. 234.Bd -literal -offset 0i 235 while ((ch = getopt(argc, argv, "abn")) != -1) 236 switch (ch) { /* Indent the switch. */ 237 case 'a': /* Don't indent the case. */ 238 aflag = 1; 239 /* FALLTHROUGH */ 240 case 'b': 241 bflag = 1; 242 break; 243 case 'n': 244 num = strtol(optarg, &ep, 10); 245 if (num <= 0 || *ep != '\e0') { 246 warnx("illegal number, -n argument -- %s", 247 optarg); 248 usage(); 249 } 250 break; 251 case '?': 252 default: 253 usage(); 254 /* NOTREACHED */ 255 } 256 argc -= optind; 257 argv += optind; 258 259.Ed 260.Pp 261Space after keywords (if, while, for, return, switch). No braces are 262used for control statements with zero or only a single statement unless that 263statement is more than a single line in which case they are permitted. 264Forever loops are done with for's, not while's. 265.Bd -literal -offset 0i 266 for (p = buf; *p != '\e0'; ++p) 267 ; /* nothing */ 268 for (;;) 269 stmt; 270 for (;;) { 271 z = a + really + long + statement + that + needs + 272 two lines + gets + indented + four + spaces + 273 on + the + second + and + subsequent + lines; 274 } 275 for (;;) { 276 if (cond) 277 stmt; 278 } 279 if (val != NULL) 280 val = realloc(val, newsize); 281.Ed 282.Pp 283Parts of a for loop may be left empty. Don't put declarations 284inside blocks unless the routine is unusually complicated. 285.Bd -literal -offset 0i 286 for (; cnt < 15; cnt++) { 287 stmt1; 288 stmt2; 289 } 290.Ed 291.Pp 292Indentation is an 8 character tab. 293Second level indents are four spaces. 294.Bd -literal -offset 0i 295 while (cnt < 20) 296 z = a + really + long + statement + that + needs + 297 two lines + gets + indented + four + spaces + 298 on + the + second + and + subsequent + lines. 299.Ed 300.Pp 301Do not add whitespace at the end of a line, and only use tabs 302followed by spaces 303to form the indentation. Do not use more spaces than a tab will produce 304and do not use spaces in front of tabs. 305.Pp 306Closing and opening braces go on the same line as the else. 307Braces that aren't necessary may be left out. 308.Bd -literal -offset 0i 309 if (test) 310 stmt; 311 else if (bar) { 312 stmt; 313 stmt; 314 } else 315 stmt; 316.Ed 317.Pp 318No spaces after function names. Commas have a space after them. No spaces 319after 320.Sq \&( 321or 322.Sq \&[ 323or preceding 324.Sq \&] 325or 326.Sq \&) 327characters. 328.Bd -literal -offset 0i 329 if (error = function(a1, a2)) 330 exit(error); 331.Ed 332.Pp 333Unary operators don't require spaces, binary operators do. Don't 334use parentheses unless they're required for precedence or unless the 335statement is confusing without them. Remember that other people may 336confuse easier than you. Do YOU understand the following? 337.Bd -literal -offset 0i 338 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1; 339 k = !(l & FLAGS); 340.Ed 341.Pp 342Exits should be 0 on success, or according to the predefined 343values in 344.Xr sysexits 3 . 345.Bd -literal -offset 0i 346 exit(EX_OK); /* 347 * Avoid obvious comments such as 348 * "Exit 0 on success." 349 */ 350} 351.Ed 352.Pp 353The function type should be on a line by itself 354preceding the function. 355.Bd -literal -offset 0i 356static char * 357function(int a1, int a2, float fl, int a4) 358{ 359.Ed 360.Pp 361When declaring variables in functions declare them sorted by size, 362then in alphabetical order; multiple ones per line are okay. 363Declaring functions inside functions is not recommended, since their 364linkage scope is always global. If a line overflows reuse the type 365keyword. 366.Pp 367Be careful to not obfuscate the code by initializing variables in 368the declarations. Use this feature only thoughtfully. 369DO NOT use function calls in initializers! 370.Bd -literal -offset 0i 371 struct foo one, *two; 372 double three; 373 int *four, five; 374 char *six, seven, eight, nine, ten, eleven, twelve; 375 376 four = myfunction(); 377.Ed 378.Pp 379Do not declare functions inside other functions; ANSI C says that 380such declarations have file scope regardless of the nesting of the 381declaration. Hiding file declarations in what appears to be a local 382scope is undesirable and will elicit complaints from a good compiler. 383.Pp 384Casts and sizeof's are not followed by a space. Note that 385.Xr indent 1 386does not understand this rule. 387.Pp 388NULL is the preferred null pointer constant. Use NULL instead of 389(type *)0 or (type *)NULL in contexts where the compiler knows the 390type, e.g., in assignments. Use (type *)NULL in other contexts, 391in particular for all function args. (Casting is essential for 392variadic args and is necessary for other args if the function prototype 393might not be in scope.) 394Test pointers 395against NULL, e.g., use: 396.Bd -literal -offset 0i 397(p = f()) == NULL 398.Ed 399.Pp 400not: 401.Bd -literal -offset 0i 402!(p = f()) 403.Ed 404.Pp 405Don't use '!' for tests unless it's a boolean, e.g. use 406.Bd -literal -offset 0i 407if (*p == '\e0') 408.Ed 409.Pp 410not 411.Bd -literal -offset 0i 412if (!*p) 413.Ed 414.Pp 415Routines returning void * should not have their return values cast 416to any pointer type. 417.Pp 418Use 419.Xr err 3 420or 421.Xr warn 3 , 422don't roll your own! 423.Bd -literal -offset 0i 424 if ((four = malloc(sizeof(struct foo))) == NULL) 425 err(1, (char *)NULL); 426 if ((six = (int *)overflow()) == NULL) 427 errx(1, "Number overflowed."); 428 return (eight); 429} 430.Ed 431.Pp 432Old-style function declarations look like this: 433.Bd -literal -offset 0i 434static char * 435function(a1, a2, fl, a4) 436 int a1, a2; /* Declare ints, too, don't default them. */ 437 float fl; /* Beware double vs. float prototype differences. */ 438 int a4; /* List in order declared. */ 439{ 440.Ed 441.Pp 442Use ANSI function declarations unless you explicitly need K&R compatibility. 443.Pp 444Variable numbers of arguments should look like this. 445.Bd -literal -offset 0i 446#include <stdarg.h> 447 448void 449vaf(const char *fmt, ...) 450{ 451 va_list ap; 452 453 va_start(ap, fmt); 454 STUFF; 455 va_end(ap); 456 /* No return needed for void functions. */ 457} 458 459static void 460usage() 461{ 462 /* Insert an empty line if the function has no local variables. */ 463.Ed 464.Pp 465Use 466.Xr printf 3 , 467not fputs/puts/putchar/whatever; it's faster and usually cleaner, not 468to mention avoiding stupid bugs. 469.Pp 470Usage statements should look like the manual pages. Options w/o 471operands come first, in alphabetical order inside a single set of 472braces, followed by options with operands, in alphabetical order, 473each in braces, followed by required arguments in the order they 474are specified, followed by optional arguments in the order they 475are specified. A bar 476.Pq Sq \&| 477separates either-or options/arguments, 478and multiple options/arguments which are specified together are 479placed in a single set of braces. 480.Pp 481.Bd -ragged -offset 0.3i 482"usage: f [-ade] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en" 483"usage: f [-a | -b] [-c [-de] [-n number]]\en" 484.Ed 485.Bd -literal -offset 0i 486 (void)fprintf(stderr, "usage: f [-ab]\en"); 487 exit(1); 488} 489.Ed 490.Pp 491New core kernel code should be reasonably compliant with the style guides. 492The guidelines for third-party maintained modules and device drivers are more 493relaxed but at a minimum should be internally consistent with their style. 494.Pp 495Stylistic changes (including whitespace changes) are hard on the source 496repository and are to be avoided without good reason. Code that is 497approximately KNF compliant in the repository must not diverge from 498compliance. 499.Pp 500Whenever possible, code should be run through a code checker 501(e.g., "gcc -Wall" or xlint(1)) and produce minimal warnings. 502 503.Sh SEE ALSO 504.Xr indent 1 , 505.Xr err 3 , 506.Xr sysexits 3 , 507.Xr warn 3 508.Sh HISTORY 509This man page is largely based on the src/admin/style/style file from 510the 511.Tn BSD 5124.4-Lite2 release, with updates to reflect the current practice and 513desire of the 514.Tn FreeBSD 515project. 516