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