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