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