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