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