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