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