]> git.saurik.com Git - apple/xnu.git/blame - bsd/man/man9/style.9
xnu-3789.1.32.tar.gz
[apple/xnu.git] / bsd / man / man9 / style.9
CommitLineData
9bccf70c
A
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.
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
57After any copyright header, there is a blank line, and the
58.Va rcsid
59for source files.
60Version control system ID tags should only exist once in a file
61(unlike this one).
62Non-C/C++ source files follow the example above, while C/C++ source files
63follow the one below.
64All VCS (version control system) revision identification from files obtained
65from elsewhere should be maintained, including, where applicable, multiple IDs
66showing 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.
72Most
73.No non- Ns Fx
74VCS 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
81Leave another blank line before the header files.
82.Pp
83Kernel include files (i.e.\&
84.Pa sys/*.h )
85come first; normally, include
86.Aq Pa sys/types.h
87OR
88.Aq Pa sys/param.h ,
89but not both.
90.Aq Pa sys/types.h
91includes
92.Aq Pa 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
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.Aq Pa 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
178When declaring variables in structures, declare them sorted by use, then
179by size, and then in alphabetical order.
180The first category normally does not apply, but there are exceptions.
181Each one gets its own line.
182Try to make the structure
183readable by aligning the member names using either one or two tabs
184depending upon your judgment.
185You should use one tab if it suffices to align most of the member names.
186Names following extremely long types
187should be separated by a single space.
188.Pp
189Major structures should be declared at the top of the file in which they
190are used, or in separate header files if they are used in multiple
191source files.
192Use of the structures should be by separate declarations
193and should be
194.Ic extern
195if they are declared in a header file.
196.Bd -literal
197struct 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};
203struct foo *foohead; /* Head of global foo list. */
204.Ed
205.Pp
206Use
207.Xr queue 3
208macros rather than rolling your own lists, whenever possible.
209Thus,
210the previous example would be better written:
211.Bd -literal
212#include <sys/queue.h>
213
214struct 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};
220LIST_HEAD(, foo) foohead; /* Head of global foo list. */
221.Ed
222.Pp
2d21ac55
A
223Avoid using typedefs for structure types. Typedefs are problematic
224because they do not properly hide their underlying type; for example you
225need to know if the typedef is the structure itself or a pointer to the
226structure. In addition they must be declared exactly once, whereas an
227incomplete structure type can be mentioned as many times as necessary.
228Typedefs are difficult to use in stand-alone header files: the header
229that defines the typedef must be included before the header that uses it,
230or by the header that uses it (which causes namespace pollution), or
231there must be a back-door mechanism for obtaining the typedef.
232.Pp
9bccf70c
A
233When convention requires a
234.Ic typedef ,
235make its name match the struct tag.
9bccf70c
A
236.Bd -literal
237/* Make the structure name match the typedef. */
238typedef struct bar {
239 int level;
2d21ac55 240} bar_t;
9bccf70c
A
241.Ed
242.Pp
243All functions are prototyped somewhere.
244.Pp
245Function prototypes for private functions (i.e. functions not used
246elsewhere) go at the top of the first source module.
247Functions
248local to one source module should be declared
249.Ic static .
2d21ac55
A
250Functions that are not exported outside of the kernel should
251be declared
252.Ic __private_extern__ .
9bccf70c
A
253.Pp
254Functions used from other parts of the kernel are prototyped in the
255relevant include file.
256.Pp
257Functions that are used locally in more than one module go into a
258separate header file, e.g.\&
259.Qq Pa extern.h .
260.Pp
2d21ac55 261Do not use the __P macro.
9bccf70c
A
262.Pp
263In general code can be considered
264.Dq "new code"
265when it makes up about 50% or more of the file(s) involved.
266This is enough
267to break precedents in the existing code and use the current
268.Nm
269guidelines.
270.Pp
271The kernel has a name associated with parameter types, e.g., in the kernel
272use:
273.Bd -literal
274void function(int fd);
275.Ed
276.Pp
277In header files visible to userland applications, prototypes that are
278visible must use either
279.Dq protected
280names (ones beginning with an underscore)
281or no names with the types.
282It is preferable to use protected names.
283E.g., use:
284.Bd -literal
285void function(int);
286.Ed
287.Pp
288or:
289.Bd -literal
290void function(int _fd);
291.Ed
292.Pp
293Prototypes may have an extra space after a tab to enable function names
294to line up:
295.Bd -literal
296static char *function(int _arg, const char *_arg2, struct foo *_arg3,
297 struct bar *_arg4);
298static void usage(void);
299
300/*
301 * All major routines should have a comment briefly describing what
302 * they do. The comment before the "main" routine should describe
303 * what the program does.
304 */
305int
306main(int argc, char *argv[])
307{
308 long num;
309 int ch;
310 char *ep;
311
312.Ed
313.Pp
314For consistency,
315.Xr getopt 3
316should be used to parse options.
317Options
318should be sorted in the
319.Xr getopt 3
320call and the
321.Ic switch
322statement, unless
323parts of the
324.Ic switch
325cascade.
326Elements in a
327.Ic switch
328statement that cascade should have a
329.Li FALLTHROUGH
330comment.
331Numerical arguments should be checked for accuracy.
332Code that cannot be reached should have a
333.Li NOTREACHED
334comment.
335.Bd -literal
336 while ((ch = getopt(argc, argv, "abn:")) != -1)
337 switch (ch) { /* Indent the switch. */
338 case 'a': /* Don't indent the case. */
339 aflag = 1;
340 /* FALLTHROUGH */
341 case 'b':
342 bflag = 1;
343 break;
344 case 'n':
345 num = strtol(optarg, &ep, 10);
346 if (num <= 0 || *ep != '\e0') {
347 warnx("illegal number, -n argument -- %s",
348 optarg);
349 usage();
350 }
351 break;
352 case '?':
353 default:
354 usage();
355 /* NOTREACHED */
356 }
357 argc -= optind;
358 argv += optind;
359.Ed
360.Pp
361Space after keywords
362.Pq Ic if , while , for , return , switch .
363No braces are
364used for control statements with zero or only a single statement unless that
365statement is more than a single line in which case they are permitted.
366Forever loops are done with
367.Ic for Ns 's ,
368not
369.Ic while Ns 's .
370.Bd -literal
371 for (p = buf; *p != '\e0'; ++p)
372 ; /* nothing */
373 for (;;)
374 stmt;
375 for (;;) {
376 z = a + really + long + statement + that + needs +
377 two lines + gets + indented + four + spaces +
378 on + the + second + and + subsequent + lines;
379 }
380 for (;;) {
381 if (cond)
382 stmt;
383 }
384 if (val != NULL)
385 val = realloc(val, newsize);
386.Ed
387.Pp
388Parts of a
389.Ic for
390loop may be left empty.
391Do not put declarations
392inside blocks unless the routine is unusually complicated.
393.Bd -literal
394 for (; cnt < 15; cnt++) {
395 stmt1;
396 stmt2;
397 }
398.Ed
399.Pp
2d21ac55
A
400Variable names should contain underscores to separate words. DO NOT use
401StudlyCaps.
402.Pp
403Indentation is an 8 character tab. All code should fit in 80 columns.
9bccf70c
A
404If you have to wrap a long statement, put the operator at the end of the
405line.
406.Bd -literal
2d21ac55
A
407 while (cnt < 20 && this_variable_name_is_too_long &&
408 ep != NULL)
9bccf70c
A
409 z = a + really + long + statement + that + needs +
410 two lines + gets + indented + four + spaces +
411 on + the + second + and + subsequent + lines;
412.Ed
413.Pp
414Do not add whitespace at the end of a line, and only use tabs
415followed by spaces
416to form the indentation.
417Do not use more spaces than a tab will produce
418and do not use spaces in front of tabs.
419.Pp
420Closing and opening braces go on the same line as the
421.Ic else .
422Braces that are not necessary may be left out.
423.Bd -literal
424 if (test)
425 stmt;
426 else if (bar) {
427 stmt;
428 stmt;
429 } else
430 stmt;
431.Ed
432.Pp
433No spaces after function names.
434Commas have a space after them.
435No spaces
436after
437.Ql \&(
438or
439.Ql \&[
440or preceding
441.Ql \&]
442or
443.Ql \&)
444characters.
445.Bd -literal
446 error = function(a1, a2);
447 if (error != 0)
448 exit(error);
449.Ed
450.Pp
451Unary operators do not require spaces, binary operators do.
452Do not use parentheses unless they are required for precedence or unless the
453statement is confusing without them.
454Remember that other people may
455confuse easier than you.
456Do YOU understand the following?
457.Bd -literal
458 a = b->c[0] + ~d == (e || f) || g && h ? i : j >> 1;
459 k = !(l & FLAGS);
460.Ed
461.Pp
462Exits should be 0 on success, or according to the predefined
463values in
464.Xr sysexits 3 .
465.Bd -literal
466 exit(EX_OK); /*
467 * Avoid obvious comments such as
468 * "Exit 0 on success."
469 */
470}
471.Ed
472.Pp
473The function type should be on a line by itself
474preceding the function.
475.Bd -literal
476static char *
477function(int a1, int a2, float fl, int a4)
478{
479.Ed
480.Pp
481When declaring variables in functions declare them sorted by size,
482then in alphabetical order; multiple ones per line are okay.
483If a line overflows reuse the type keyword.
484.Pp
485Be careful to not obfuscate the code by initializing variables in
486the declarations.
487Use this feature only thoughtfully.
488DO NOT use function calls in initializers.
489.Bd -literal
490 struct foo one, *two;
491 double three;
492 int *four, five;
493 char *six, seven, eight, nine, ten, eleven, twelve;
494
495 four = myfunction();
496.Ed
497.Pp
498Do not declare functions inside other functions; ANSI C says that
499such declarations have file scope regardless of the nesting of the
500declaration.
501Hiding file declarations in what appears to be a local
502scope is undesirable and will elicit complaints from a good compiler.
503.Pp
504Casts and
505.Ic sizeof Ns 's
506are not followed by a space.
507Note that
508.Xr indent 1
509does not understand this rule.
2d21ac55
A
510.Ic sizeof Ns 's
511are written with parentheses always.
9bccf70c
A
512.Pp
513.Dv NULL
514is the preferred null pointer constant.
515Use
516.Dv NULL
517instead of
518.Vt ( "type *" ) Ns 0
519or
520.Vt ( "type *" ) Ns Dv NULL
521in contexts where the compiler knows the
522type, e.g., in assignments.
523Use
524.Vt ( "type *" ) Ns Dv NULL
525in other contexts,
526in particular for all function args.
527(Casting is essential for
528variadic args and is necessary for other args if the function prototype
529might not be in scope.)
530Test pointers against
531.Dv NULL ,
532e.g., use:
533.Pp
534.Bd -literal
535(p = f()) == NULL
536.Ed
537.Pp
538not:
539.Bd -literal
540!(p = f())
541.Ed
542.Pp
543Do not use
544.Ic \&!
545for tests unless it is a boolean, e.g. use
546.Bd -literal
547if (*p == '\e0')
548.Ed
549.Pp
550not
551.Bd -literal
552if (!*p)
553.Ed
554.Pp
555Routines returning
556.Vt "void *"
557should not have their return values cast
558to any pointer type.
559.Pp
2d21ac55
A
560Values in
561.Ic return
562statements should be enclosed in parentheses.
563.Pp
9bccf70c
A
564Use
565.Xr err 3
566or
567.Xr warn 3 ,
568do not roll your own.
569.Bd -literal
570 if ((four = malloc(sizeof(struct foo))) == NULL)
571 err(1, (char *)NULL);
572 if ((six = (int *)overflow()) == NULL)
573 errx(1, "number overflowed");
574 return (eight);
575}
576.Ed
577.Pp
2d21ac55 578Use ANSI function declarations.
9bccf70c
A
579.Pp
580Variable numbers of arguments should look like this.
581.Bd -literal
582#include <stdarg.h>
583
584void
585vaf(const char *fmt, ...)
586{
587 va_list ap;
588
589 va_start(ap, fmt);
590 STUFF;
591 va_end(ap);
592 /* No return needed for void functions. */
593}
9bccf70c
A
594.Ed
595.Pp
596Use
597.Xr printf 3 ,
598not
599.Xr fputs 3 ,
600.Xr puts 3 ,
601.Xr putchar 3 ,
602whatever; it is faster and usually cleaner, not
603to mention avoiding stupid bugs.
604.Pp
605Usage statements should look like the manual pages
606.Sx SYNOPSIS .
607The usage statement should be structured in the following order:
608.Bl -enum
609.It
610Options without operands come first,
611in alphabetical order,
612inside a single set of brackets
613.Ql ( \&[
614and
615.Ql \&] ) .
616.It
617Options with operands come next,
618also in alphabetical order,
619with each option and its argument inside its own pair of brackets.
620.It
621Required arguments
622(if any)
623are next,
624listed in the order they should be specified on the command line.
625.It
626Finally,
627any optional arguments should be listed,
628listed in the order they should be specified,
629and all inside brackets.
630.El
631.Pp
632A bar
633.Pq Ql \&|
634separates
635.Dq either-or
636options/arguments,
637and multiple options/arguments which are specified together are
638placed in a single set of brackets.
639.Bd -literal -offset 4n
640"usage: f [-aDde] [-b b_arg] [-m m_arg] req1 req2 [opt1 [opt2]]\en"
641"usage: f [-a | -b] [-c [-dEe] [-n number]]\en"
642.Ed
643.Bd -literal
644 (void)fprintf(stderr, "usage: f [-ab]\en");
645 exit(EX_USAGE);
646}
647.Ed
648.Pp
649Note that the manual page options description should list the options in
650pure alphabetical order.
651That is, without regard to whether an option takes arguments or not.
652The alphabetical ordering should take into account the case ordering
653shown above.
654.Pp
2d21ac55 655New core kernel code should be compliant with the
9bccf70c
A
656.Nm
657guides.
9bccf70c
A
658.Pp
659Stylistic changes (including whitespace changes) are hard on the source
660repository and are to be avoided without good reason.
661Code that is approximately
662.Fx
663KNF
664.Nm
665compliant in the repository must not diverge from compliance.
666.Pp
2d21ac55
A
667Code should be run through a code checker (e.g., sparse or
668.Nm gcc Fl Wall Fl Werror
669).
9bccf70c
A
670.Sh SEE ALSO
671.Xr indent 1 ,
672.Xr lint 1 ,
673.Xr err 3 ,
674.Xr sysexits 3 ,
675.Xr warn 3
676.Sh HISTORY
677This man page is largely based on the
678.Pa src/admin/style/style
679file from the
680.Bx 4.4 Lite2
681release, with occasional updates to reflect the current practice and
682desire of the
683.Fx
684project.