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