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