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