1 # Coding conventions in the Samba tree
5 Coding style guidelines are about reducing the number of unnecessary
6 reformatting patches and making things easier for developers to work
8 You don't have to like them or even agree with them, but once put in place
9 we all have to abide by them (or vote to change them). However, coding
10 style should never outweigh coding itself and so the guidelines
11 described here are hopefully easy enough to follow as they are very
12 common and supported by tools and editors.
14 The basic style for C code is the Linux kernel coding style (See
15 Documentation/CodingStyle in the kernel source tree). This closely matches
16 what most Samba developers use already anyways, with a few exceptions as
19 The coding style for Python code is documented in
20 [PEP8](https://www.python.org/dev/peps/pep-0008/). New Python code
21 should be compatible with Python 3.6 onwards.
23 But to save you the trouble of reading the Linux kernel style guide, here
26 * Maximum Line Width is 80 Characters
27 The reason is not about people with low-res screens but rather sticking
28 to 80 columns prevents you from easily nesting more than one level of
29 if statements or other code blocks. Use [source3/script/count_80_col.pl](source3/script/count_80_col.pl)
30 to check your changes.
32 * Use 8 Space Tabs to Indent
33 No whitespace fillers.
35 * No Trailing Whitespace
36 Use [source3/script/strip_trail_ws.pl](source3/script/strip_trail_ws.pl) to clean up your files before
39 * Follow the K&R guidelines. We won't go through all of them here. Do you
40 have a copy of "The C Programming Language" anyways right? You can also use
41 the [format_indent.sh script found in source3/script/](source3/script/format_indent.sh) if all else fails.
49 Add the follow to your $HOME/.emacs file:
52 (add-hook 'c-mode-hook
55 (c-toggle-auto-state)))
61 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
63 For the basic vi editor included with all variants of \*nix, add the
64 following to $HOME/.exrc:
71 For Vim, the following settings in $HOME/.vimrc will also deal with
72 displaying trailing whitespace:
75 if has("syntax") && (&t_Co > 2 || has("gui_running"))
77 function! ActivateInvisibleCharIndicator()
78 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
79 highlight TrailingSpace ctermbg=Red
81 autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
83 " Show tabs, trailing whitespace, and continued lines visually
84 set list listchars=tab:»·,trail:·,extends:…
86 " highlight overly long lines same as TODOs.
88 autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
91 ### How to use clang-format
93 Install 'git-format-clang' which is part of the clang suite (Fedora:
94 git-clang-format, openSUSE: clang-tools).
96 Now do your changes and stage them with `git add`. Once they are staged
97 format the code using `git clang-format` before you commit.
99 Now the formatting changed can be viewed with `git diff` against the
102 ## FAQ & Statement Reference
106 Comments should always use the standard C syntax. C++
107 style comments are not currently allowed.
109 The lines before a comment should be empty. If the comment directly
110 belongs to the following code, there should be no empty line
111 after the comment, except if the comment contains a summary
112 of multiple following code blocks.
121 * This is a multi line comment,
122 * which explains the logical steps we have to do:
124 * 1. We need to set i=5, because...
125 * 2. We need to call complex_fn1
128 /* This is a one line comment about i = 5. */
132 * This is a multi line comment,
133 * explaining the call to complex_fn1()
140 * @brief This is a doxygen comment.
142 * This is a more detailed explanation of
143 * this simple function.
145 * @param[in] param1 The parameter value of the function.
147 * @param[out] result1 The result value of the function.
149 * @return 0 on success and -1 on error.
151 int example(int param1, int *result1);
160 * This is a multi line comment,
161 * which explains the logical steps we have to do:
163 * 1. We need to set i=5, because...
164 * 2. We need to call complex_fn1
166 /* This is a one line comment about i = 5. */
169 * This is a multi line comment,
170 * explaining the call to complex_fn1()
176 /*This is a one line comment.*/
178 /* This is a multi line comment,
179 with some more words...*/
182 * This is a multi line comment,
183 * with some more words...*/
186 ### Indention & Whitespace & 80 columns
188 To avoid confusion, indentations have to be tabs with length 8 (not 8
189 ' ' characters). When wrapping parameters for function calls,
190 align the parameter list with the first parameter on the previous line.
191 Use tabs to get as close as possible and then fill in the final 7
192 characters or less with whitespace. For example,
195 var1 = foo(arg1, arg2,
199 The previous example is intended to illustrate alignment of function
200 parameters across lines and not as encourage for gratuitous line
201 splitting. Never split a line before columns 70 - 79 unless you
202 have a really good reason. Be smart about formatting.
204 One exception to the previous rule is function calls, declarations, and
205 definitions. In function calls, declarations, and definitions, either the
206 declaration is a one-liner, or each parameter is listed on its own
207 line. The rationale is that if there are many parameters, each one
208 should be on its own line to make tracking interface changes easier.
211 ## If, switch, & Code blocks
213 Always follow an `if` keyword with a space but don't include additional
214 spaces following or preceding the parentheses in the conditional.
227 Yes we have a lot of code that uses the second form and we are trying
228 to clean it up without being overly intrusive.
230 Note that this is a rule about parentheses following keywords and not
231 functions. Don't insert a space between the name and left parentheses when
234 Braces for code blocks used by `for`, `if`, `switch`, `while`, `do..while`, etc.
235 should begin on the same line as the statement keyword and end on a line
236 of their own. You should always include braces, even if the block only
237 contains one statement. NOTE: Functions are different and the beginning left
238 brace should be located in the first column on the next line.
240 If the beginning statement has to be broken across lines due to length,
241 the beginning brace should be on a line of its own.
243 The exception to the ending rule is when the closing brace is followed by
244 another language keyword such as else or the closing while in a `do..while`
254 for (x=1; x<10; x++) {
258 for (really_really_really_really_long_var_name=0;
259 really_really_really_really_long_var_name<10;
260 really_really_really_really_long_var_name++)
262 print("%d\n", really_really_really_really_long_var_name);
266 printf("also good\n");
275 print("I'm in a loop!\n"); }
285 print("I should be in braces.\n");
291 While many people have been academically taught that `goto`s are
292 fundamentally evil, they can greatly enhance readability and reduce memory
293 leaks when used as the single exit point from a function. But in no Samba
294 world what so ever is a goto outside of a function or block of code a good
300 int function foo(int y)
306 z = malloc(sizeof(int) * y);
313 print("Allocated %d elements.\n", y);
325 ### Primitive Data Types
327 Samba has large amounts of historical code which makes use of data types
328 commonly supported by the C99 standard. However, at the time such types
329 as boolean and exact width integers did not exist and Samba developers
330 were forced to provide their own. Now that these types are guaranteed to
331 be available either as part of the compiler C99 support or from
332 lib/replace/, new code should adhere to the following conventions:
334 * Booleans are of type `bool` (not `BOOL`)
335 * Boolean values are `true` and `false` (not `True` or `False`)
336 * Exact width integers are of type `[u]int[8|16|32|64]_t`
338 Most of the time a good name for a boolean variable is 'ok'. Here is an
339 example we often use:
350 It makes the code more readable and is easy to debug.
354 Samba tries to avoid `typedef struct { .. } x_t;` so we do always try to use
355 `struct x { .. };`. We know there are still such typedefs in the code,
356 but for new code, please don't do that anymore.
358 ### Initialize pointers
360 All pointer variables MUST be initialized to NULL. History has
361 demonstrated that uninitialized pointer variables have lead to various
362 bugs and security issues.
364 Pointers MUST be initialized even if the assignment directly follows
365 the declaration, like pointer2 in the example below, because the
366 instructions sequence may change over time.
371 char *pointer1 = NULL;
372 char *pointer2 = NULL;
374 pointer2 = some_func2();
378 pointer1 = some_func1();
387 pointer2 = some_func2();
391 pointer1 = some_func1();
394 ### Make use of helper variables
396 Please try to avoid passing function calls as function parameters
397 in new code. This makes the code much easier to read and
398 it's also easier to use the "step" command within gdb.
406 name = get_some_name();
411 ret = some_function_my_name(name);
419 ret = some_function_my_name(get_some_name());
423 Please try to avoid passing function return values to if- or
424 while-conditions. The reason for this is better handling of code under a
430 x = malloc(sizeof(short)*10);
432 fprintf(stderr, "Unable to alloc memory!\n");
439 if ((x = malloc(sizeof(short)*10)) == NULL ) {
440 fprintf(stderr, "Unable to alloc memory!\n");
444 There are exceptions to this rule. One example is walking a data structure in
448 while ((opt = poptGetNextOpt(pc)) != -1) {
449 ... do something with opt ...
453 Another exception: DBG messages for example printing a SID or a GUID:
454 Here we don't expect any surprise from the printing functions, and the
455 main reason of this guideline is to make debugging easier. That reason
456 rarely exists for this particular use case, and we gain some
457 efficiency because the DBG_ macros don't evaluate their arguments if
458 the debuglevel is not high enough.
461 if (!NT_STATUS_IS_OK(status)) {
462 struct dom_sid_buf sid_buf;
463 struct GUID_txt_buf guid_buf;
465 "objectSID [%s] for GUID [%s] invalid\n",
466 dom_sid_str_buf(objectsid, &sid_buf),
467 GUID_buf_string(&cache->entries[idx], &guid_buf));
471 But in general, please try to avoid this pattern.
474 ### Control-Flow changing macros
476 Macros like `NT_STATUS_NOT_OK_RETURN` that change control flow
477 (`return`/`goto`/etc) from within the macro are considered bad, because
478 they look like function calls that never change control flow. Please
479 do not use them in new code.
481 The only exception is the test code that depends repeated use of calls
482 like `CHECK_STATUS`, `CHECK_VAL` and others.
485 ### Error and out logic
490 frame = talloc_stackframe();
492 if (ret == LDB_SUCCESS) {
493 if (result->count == 0) {
494 ret = LDB_ERR_NO_SUCH_OBJECT;
496 struct ldb_message *match =
497 get_best_match(dn, result);
500 return LDB_ERR_OPERATIONS_ERROR;
502 *msg = talloc_move(mem_ctx, &match);
513 frame = talloc_stackframe();
515 if (ret != LDB_SUCCESS) {
520 if (result->count == 0) {
522 return LDB_ERR_NO_SUCH_OBJECT;
525 match = get_best_match(dn, result);
528 return LDB_ERR_OPERATIONS_ERROR;
531 *msg = talloc_move(mem_ctx, &match);
539 Use these following macros instead of DEBUG:
542 DBG_ERR log level 0 error conditions
543 DBG_WARNING log level 1 warning conditions
544 DBG_NOTICE log level 3 normal, but significant, condition
545 DBG_INFO log level 5 informational message
546 DBG_DEBUG log level 10 debug-level message
552 DBG_ERR("Memory allocation failed\n");
553 DBG_DEBUG("Received %d bytes\n", count);
556 The messages from these macros are automatically prefixed with the
561 ### PRINT format specifiers PRIuxx
563 Use %PRIu32 instead of %u for uint32_t. Do not assume that this is valid:
565 /usr/include/inttypes.h
566 104:# define PRIu32 "u"
568 It could be possible to have a platform where "unsigned" is 64-bit. In theory
569 even 16-bit. The point is that "unsigned" being 32-bit is nowhere specified.
570 The PRIuxx specifiers are standard.
575 D_DEBUG("Resolving %"PRIu32" SID(s).\n", state->num_sids);
580 Do not use PRIu32 for uid_t and gid_t, they do not have to be uint32_t.