]> git.saurik.com Git - apple/xnu.git/blob - bsd/man/man9/style.9
xnu-517.tar.gz
[apple/xnu.git] / bsd / man / man9 / style.9
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
33 This file specifies the preferred style for kernel source files in the
34 .Fx
35 source tree.
36 It is also a guide for preferred userland code style.
37 .Bd -literal
38 /*
39 * Style guide for FreeBSD. Based on the CSRG's KNF (Kernel Normal Form).
40 *
41 * @(#)style 1.14 (Berkeley) 4/28/95
42 * $FreeBSD: src/share/man/man9/style.9,v 1.32.2.16 2001/12/17 11:30:19 ru Exp $
43 */
44
45 /*
46 * VERY important single-line comments look like this.
47 */
48
49 /* Most single-line comments look like this. */
50
51 /*
52 * Multi-line comments look like this. Make them real sentences. Fill
53 * them so they look like real paragraphs.
54 */
55 .Ed
56 .Pp
57 After any copyright header, there is a blank line, and the
58 .Va rcsid
59 for source files.
60 Version control system ID tags should only exist once in a file
61 (unlike this one).
62 Non-C/C++ source files follow the example above, while C/C++ source files
63 follow the one below.
64 All VCS (version control system) revision identification from files obtained
65 from elsewhere should be maintained, including, where applicable, multiple IDs
66 showing a file's history.
67 In general, keep the IDs intact, including any
68 .So Li $ Sc Ns s .
69 There is no reason to add
70 .Qq Li "From"
71 in front of foreign VCS IDs.
72 Most
73 .No non- Ns Fx
74 VCS IDs should be indented by a tab if in a comment.
75 .Bd -literal
76 #include <sys/cdefs.h>
77 __RCSID("@(#)style 1.14 (Berkeley) 4/28/95");
78 __FBSDID("$FreeBSD: src/share/man/man9/style.9,v 1.32.2.16 2001/12/17 11:30:19 ru Exp $");
79 .Ed
80 .Pp
81 Leave another blank line before the header files.
82 .Pp
83 Kernel include files (i.e.\&
84 .Pa sys/*.h )
85 come first; normally, include
86 .Aq Pa sys/types.h
87 OR
88 .Aq Pa sys/param.h ,
89 but not both.
90 .Aq Pa sys/types.h
91 includes
92 .Aq Pa sys/cdefs.h ,
93 and 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
98 For 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
107 Leave a blank line before the next group, the
108 .Pa /usr
109 include files,
110 which should be sorted alphabetically by name.
111 .Bd -literal
112 #include <stdio.h>
113 .Ed
114 .Pp
115 Global pathnames are defined in
116 .Aq Pa paths.h .
117 Pathnames local
118 to the program go in
119 .Qq Pa pathnames.h
120 in the local directory.
121 .Bd -literal
122 #include <paths.h>
123 .Ed
124 .Pp
125 Leave another blank line before the user include files.
126 .Bd -literal
127 #include "pathnames.h" /* Local includes in double quotes. */
128 .Ed
129 .Pp
130 Do not
131 .Ic #define
132 or declare names in the implementation namespace except
133 for implementing application interfaces.
134 .Pp
135 The names of
136 .Dq unsafe
137 macros (ones that have side effects), and the names of macros for
138 manifest constants, are all in uppercase.
139 The expansions of expression-like macros are either a single token
140 or have outer parentheses.
141 Put a single tab character between the
142 .Ic #define
143 and the macro name.
144 If a macro is an inline expansion of a function, the function name is
145 all 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.
150 If a
151 macro needs more than a single line, use braces
152 .Ql ( \&{
153 and
154 .Ql \&} ) .
155 Right-justify the
156 backslashes; it makes it easier to read.
157 If the macro encapsulates a compound statement, enclose it in a
158 .Ic do
159 loop,
160 so that it can safely be used in
161 .Ic if
162 statements.
163 Any final statement-terminating semicolon should be
164 supplied by the macro invocation rather than the macro, to make parsing easier
165 for 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
173 Enumeration values are all uppercase.
174 .Bd -literal
175 enum enumtype { ONE, TWO } et;
176 .Ed
177 .Pp
178 When declaring variables in structures, declare them sorted by use, then
179 by size, and then in alphabetical order.
180 The first category normally does not apply, but there are exceptions.
181 Each one gets its own line.
182 Try to make the structure
183 readable by aligning the member names using either one or two tabs
184 depending upon your judgment.
185 You should use one tab if it suffices to align most of the member names.
186 Names following extremely long types
187 should be separated by a single space.
188 .Pp
189 Major structures should be declared at the top of the file in which they
190 are used, or in separate header files if they are used in multiple
191 source files.
192 Use of the structures should be by separate declarations
193 and should be
194 .Ic extern
195 if they are declared in a header file.
196 .Bd -literal
197 struct foo {
198 struct foo *next; /* List of active foo. */
199 struct mumble amumble; /* Comment for mumble. */
200 int bar; /* Try to align the comments. */
201 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
202 };
203 struct foo *foohead; /* Head of global foo list. */
204 .Ed
205 .Pp
206 Use
207 .Xr queue 3
208 macros rather than rolling your own lists, whenever possible.
209 Thus,
210 the previous example would be better written:
211 .Bd -literal
212 #include <sys/queue.h>
213
214 struct foo {
215 LIST_ENTRY(foo) link; /* Use queue macros for foo lists. */
216 struct mumble amumble; /* Comment for mumble. */
217 int bar; /* Try to align the comments. */
218 struct verylongtypename *baz; /* Won't fit in 2 tabs. */
219 };
220 LIST_HEAD(, foo) foohead; /* Head of global foo list. */
221 .Ed
222 .Pp
223 Avoid using typedefs for structure types.
224 This makes it impossible
225 for applications to use pointers to such a structure opaquely, which
226 is both possible and beneficial when using an ordinary struct tag.
227 When convention requires a
228 .Ic typedef ,
229 make its name match the struct tag.
230 Avoid typedefs ending in
231 .Dq Li _t ,
232 except as specified in Standard C or by \*[Px].
233 .Bd -literal
234 /* Make the structure name match the typedef. */
235 typedef struct bar {
236 int level;
237 } BAR;
238 .Ed
239 .Pp
240 All functions are prototyped somewhere.
241 .Pp
242 Function prototypes for private functions (i.e. functions not used
243 elsewhere) go at the top of the first source module.
244 Functions
245 local to one source module should be declared
246 .Ic static .
247 .Pp
248 Functions used from other parts of the kernel are prototyped in the
249 relevant include file.
250 .Pp
251 Functions that are used locally in more than one module go into a
252 separate header file, e.g.\&
253 .Qq Pa extern.h .
254 .Pp
255 Only use the
256 .Dv __P
257 macro from the include file
258 .Aq Pa sys/cdefs.h
259 if the source
260 file in general is (to be) compilable with a K&R Old Testament compiler.
261 Use of the
262 .Dv __P
263 macro in new code is discouraged, although modifications
264 to existing files should be consistent with that file's conventions.
265 .Pp
266 In general code can be considered
267 .Dq "new code"
268 when it makes up about 50% or more of the file(s) involved.
269 This is enough
270 to break precedents in the existing code and use the current
271 .Nm
272 guidelines.
273 .Pp
274 The kernel has a name associated with parameter types, e.g., in the kernel
275 use:
276 .Bd -literal
277 void function(int fd);
278 .Ed
279 .Pp
280 In header files visible to userland applications, prototypes that are
281 visible must use either
282 .Dq protected
283 names (ones beginning with an underscore)
284 or no names with the types.
285 It is preferable to use protected names.
286 E.g., use:
287 .Bd -literal
288 void function(int);
289 .Ed
290 .Pp
291 or:
292 .Bd -literal
293 void function(int _fd);
294 .Ed
295 .Pp
296 Prototypes may have an extra space after a tab to enable function names
297 to line up:
298 .Bd -literal
299 static char *function(int _arg, const char *_arg2, struct foo *_arg3,
300 struct bar *_arg4);
301 static 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 */
308 int
309 main(int argc, char *argv[])
310 {
311 long num;
312 int ch;
313 char *ep;
314
315 .Ed
316 .Pp
317 For consistency,
318 .Xr getopt 3
319 should be used to parse options.
320 Options
321 should be sorted in the
322 .Xr getopt 3
323 call and the
324 .Ic switch
325 statement, unless
326 parts of the
327 .Ic switch
328 cascade.
329 Elements in a
330 .Ic switch
331 statement that cascade should have a
332 .Li FALLTHROUGH
333 comment.
334 Numerical arguments should be checked for accuracy.
335 Code that cannot be reached should have a
336 .Li NOTREACHED
337 comment.
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
364 Space after keywords
365 .Pq Ic if , while , for , return , switch .
366 No braces are
367 used for control statements with zero or only a single statement unless that
368 statement is more than a single line in which case they are permitted.
369 Forever loops are done with
370 .Ic for Ns 's ,
371 not
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
391 Parts of a
392 .Ic for
393 loop may be left empty.
394 Do not put declarations
395 inside blocks unless the routine is unusually complicated.
396 .Bd -literal
397 for (; cnt < 15; cnt++) {
398 stmt1;
399 stmt2;
400 }
401 .Ed
402 .Pp
403 Indentation is an 8 character tab.
404 Second level indents are four spaces.
405 If you have to wrap a long statement, put the operator at the end of the
406 line.
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
415 Do not add whitespace at the end of a line, and only use tabs
416 followed by spaces
417 to form the indentation.
418 Do not use more spaces than a tab will produce
419 and do not use spaces in front of tabs.
420 .Pp
421 Closing and opening braces go on the same line as the
422 .Ic else .
423 Braces 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
434 No spaces after function names.
435 Commas have a space after them.
436 No spaces
437 after
438 .Ql \&(
439 or
440 .Ql \&[
441 or preceding
442 .Ql \&]
443 or
444 .Ql \&)
445 characters.
446 .Bd -literal
447 error = function(a1, a2);
448 if (error != 0)
449 exit(error);
450 .Ed
451 .Pp
452 Unary operators do not require spaces, binary operators do.
453 Do not use parentheses unless they are required for precedence or unless the
454 statement is confusing without them.
455 Remember that other people may
456 confuse easier than you.
457 Do 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
463 Exits should be 0 on success, or according to the predefined
464 values 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
474 The function type should be on a line by itself
475 preceding the function.
476 .Bd -literal
477 static char *
478 function(int a1, int a2, float fl, int a4)
479 {
480 .Ed
481 .Pp
482 When declaring variables in functions declare them sorted by size,
483 then in alphabetical order; multiple ones per line are okay.
484 If a line overflows reuse the type keyword.
485 .Pp
486 Be careful to not obfuscate the code by initializing variables in
487 the declarations.
488 Use this feature only thoughtfully.
489 DO 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
499 Do not declare functions inside other functions; ANSI C says that
500 such declarations have file scope regardless of the nesting of the
501 declaration.
502 Hiding file declarations in what appears to be a local
503 scope is undesirable and will elicit complaints from a good compiler.
504 .Pp
505 Casts and
506 .Ic sizeof Ns 's
507 are not followed by a space.
508 Note that
509 .Xr indent 1
510 does not understand this rule.
511 .Pp
512 .Dv NULL
513 is the preferred null pointer constant.
514 Use
515 .Dv NULL
516 instead of
517 .Vt ( "type *" ) Ns 0
518 or
519 .Vt ( "type *" ) Ns Dv NULL
520 in contexts where the compiler knows the
521 type, e.g., in assignments.
522 Use
523 .Vt ( "type *" ) Ns Dv NULL
524 in other contexts,
525 in particular for all function args.
526 (Casting is essential for
527 variadic args and is necessary for other args if the function prototype
528 might not be in scope.)
529 Test pointers against
530 .Dv NULL ,
531 e.g., use:
532 .Pp
533 .Bd -literal
534 (p = f()) == NULL
535 .Ed
536 .Pp
537 not:
538 .Bd -literal
539 !(p = f())
540 .Ed
541 .Pp
542 Do not use
543 .Ic \&!
544 for tests unless it is a boolean, e.g. use
545 .Bd -literal
546 if (*p == '\e0')
547 .Ed
548 .Pp
549 not
550 .Bd -literal
551 if (!*p)
552 .Ed
553 .Pp
554 Routines returning
555 .Vt "void *"
556 should not have their return values cast
557 to any pointer type.
558 .Pp
559 Use
560 .Xr err 3
561 or
562 .Xr warn 3 ,
563 do 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
573 Old-style function declarations look like this:
574 .Bd -literal
575 static char *
576 function(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
583 Use ANSI function declarations unless you explicitly need K&R compatibility.
584 Long parameter lists are wrapped with a normal four space indent.
585 .Pp
586 Variable numbers of arguments should look like this.
587 .Bd -literal
588 #include <stdarg.h>
589
590 void
591 vaf(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
601 static void
602 usage()
603 {
604 /* Insert an empty line if the function has no local variables. */
605 .Ed
606 .Pp
607 Use
608 .Xr printf 3 ,
609 not
610 .Xr fputs 3 ,
611 .Xr puts 3 ,
612 .Xr putchar 3 ,
613 whatever; it is faster and usually cleaner, not
614 to mention avoiding stupid bugs.
615 .Pp
616 Usage statements should look like the manual pages
617 .Sx SYNOPSIS .
618 The usage statement should be structured in the following order:
619 .Bl -enum
620 .It
621 Options without operands come first,
622 in alphabetical order,
623 inside a single set of brackets
624 .Ql ( \&[
625 and
626 .Ql \&] ) .
627 .It
628 Options with operands come next,
629 also in alphabetical order,
630 with each option and its argument inside its own pair of brackets.
631 .It
632 Required arguments
633 (if any)
634 are next,
635 listed in the order they should be specified on the command line.
636 .It
637 Finally,
638 any optional arguments should be listed,
639 listed in the order they should be specified,
640 and all inside brackets.
641 .El
642 .Pp
643 A bar
644 .Pq Ql \&|
645 separates
646 .Dq either-or
647 options/arguments,
648 and multiple options/arguments which are specified together are
649 placed 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
660 Note that the manual page options description should list the options in
661 pure alphabetical order.
662 That is, without regard to whether an option takes arguments or not.
663 The alphabetical ordering should take into account the case ordering
664 shown above.
665 .Pp
666 New core kernel code should be reasonably compliant with the
667 .Nm
668 guides.
669 The guidelines for third-party maintained modules and device drivers are more
670 relaxed but at a minimum should be internally consistent with their style.
671 .Pp
672 Stylistic changes (including whitespace changes) are hard on the source
673 repository and are to be avoided without good reason.
674 Code that is approximately
675 .Fx
676 KNF
677 .Nm
678 compliant in the repository must not diverge from compliance.
679 .Pp
680 Whenever possible, code should be run through a code checker
681 (e.g.,
682 .Xr lint 1
683 or
684 .Nm gcc Fl Wall )
685 and 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
693 This man page is largely based on the
694 .Pa src/admin/style/style
695 file from the
696 .Bx 4.4 Lite2
697 release, with occasional updates to reflect the current practice and
698 desire of the
699 .Fx
700 project.