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.\+/'
97 BreakBeforeBraces: Linux
98 AllowShortIfStatementsOnASingleLine: false
99 IndentCaseLabels: false
100 BinPackParameters: false
101 BinPackArguments: false
106 ## FAQ & Statement Reference
110 Comments should always use the standard C syntax. C++
111 style comments are not currently allowed.
113 The lines before a comment should be empty. If the comment directly
114 belongs to the following code, there should be no empty line
115 after the comment, except if the comment contains a summary
116 of multiple following code blocks.
125 * This is a multi line comment,
126 * which explains the logical steps we have to do:
128 * 1. We need to set i=5, because...
129 * 2. We need to call complex_fn1
132 /* This is a one line comment about i = 5. */
136 * This is a multi line comment,
137 * explaining the call to complex_fn1()
144 * @brief This is a doxygen comment.
146 * This is a more detailed explanation of
147 * this simple function.
149 * @param[in] param1 The parameter value of the function.
151 * @param[out] result1 The result value of the function.
153 * @return 0 on success and -1 on error.
155 int example(int param1, int *result1);
164 * This is a multi line comment,
165 * which explains the logical steps we have to do:
167 * 1. We need to set i=5, because...
168 * 2. We need to call complex_fn1
170 /* This is a one line comment about i = 5. */
173 * This is a multi line comment,
174 * explaining the call to complex_fn1()
180 /*This is a one line comment.*/
182 /* This is a multi line comment,
183 with some more words...*/
186 * This is a multi line comment,
187 * with some more words...*/
190 ### Indention & Whitespace & 80 columns
192 To avoid confusion, indentations have to be tabs with length 8 (not 8
193 ' ' characters). When wrapping parameters for function calls,
194 align the parameter list with the first parameter on the previous line.
195 Use tabs to get as close as possible and then fill in the final 7
196 characters or less with whitespace. For example,
199 var1 = foo(arg1, arg2,
203 The previous example is intended to illustrate alignment of function
204 parameters across lines and not as encourage for gratuitous line
205 splitting. Never split a line before columns 70 - 79 unless you
206 have a really good reason. Be smart about formatting.
208 One exception to the previous rule is function calls, declarations, and
209 definitions. In function calls, declarations, and definitions, either the
210 declaration is a one-liner, or each parameter is listed on its own
211 line. The rationale is that if there are many parameters, each one
212 should be on its own line to make tracking interface changes easier.
215 ## If, switch, & Code blocks
217 Always follow an `if` keyword with a space but don't include additional
218 spaces following or preceding the parentheses in the conditional.
231 Yes we have a lot of code that uses the second form and we are trying
232 to clean it up without being overly intrusive.
234 Note that this is a rule about parentheses following keywords and not
235 functions. Don't insert a space between the name and left parentheses when
238 Braces for code blocks used by `for`, `if`, `switch`, `while`, `do..while`, etc.
239 should begin on the same line as the statement keyword and end on a line
240 of their own. You should always include braces, even if the block only
241 contains one statement. NOTE: Functions are different and the beginning left
242 brace should be located in the first column on the next line.
244 If the beginning statement has to be broken across lines due to length,
245 the beginning brace should be on a line of its own.
247 The exception to the ending rule is when the closing brace is followed by
248 another language keyword such as else or the closing while in a `do..while`
258 for (x=1; x<10; x++) {
262 for (really_really_really_really_long_var_name=0;
263 really_really_really_really_long_var_name<10;
264 really_really_really_really_long_var_name++)
266 print("%d\n", really_really_really_really_long_var_name);
270 printf("also good\n");
279 print("I'm in a loop!\n"); }
289 print("I should be in braces.\n");
295 While many people have been academically taught that `goto`s are
296 fundamentally evil, they can greatly enhance readability and reduce memory
297 leaks when used as the single exit point from a function. But in no Samba
298 world what so ever is a goto outside of a function or block of code a good
304 int function foo(int y)
310 z = malloc(sizeof(int) * y);
317 print("Allocated %d elements.\n", y);
329 ### Primitive Data Types
331 Samba has large amounts of historical code which makes use of data types
332 commonly supported by the C99 standard. However, at the time such types
333 as boolean and exact width integers did not exist and Samba developers
334 were forced to provide their own. Now that these types are guaranteed to
335 be available either as part of the compiler C99 support or from
336 lib/replace/, new code should adhere to the following conventions:
338 * Booleans are of type `bool` (not `BOOL`)
339 * Boolean values are `true` and `false` (not `True` or `False`)
340 * Exact width integers are of type `[u]int[8|16|32|64]_t`
342 Most of the time a good name for a boolean variable is 'ok'. Here is an
343 example we often use:
354 It makes the code more readable and is easy to debug.
358 Samba tries to avoid `typedef struct { .. } x_t;` so we do always try to use
359 `struct x { .. };`. We know there are still such typedefs in the code,
360 but for new code, please don't do that anymore.
362 ### Initialize pointers
364 All pointer variables MUST be initialized to NULL. History has
365 demonstrated that uninitialized pointer variables have lead to various
366 bugs and security issues.
368 Pointers MUST be initialized even if the assignment directly follows
369 the declaration, like pointer2 in the example below, because the
370 instructions sequence may change over time.
375 char *pointer1 = NULL;
376 char *pointer2 = NULL;
378 pointer2 = some_func2();
382 pointer1 = some_func1();
391 pointer2 = some_func2();
395 pointer1 = some_func1();
398 ### Make use of helper variables
400 Please try to avoid passing function calls as function parameters
401 in new code. This makes the code much easier to read and
402 it's also easier to use the "step" command within gdb.
410 name = get_some_name();
415 ret = some_function_my_name(name);
423 ret = some_function_my_name(get_some_name());
427 Please try to avoid passing function return values to if- or
428 while-conditions. The reason for this is better handling of code under a
434 x = malloc(sizeof(short)*10);
436 fprintf(stderr, "Unable to alloc memory!\n");
443 if ((x = malloc(sizeof(short)*10)) == NULL ) {
444 fprintf(stderr, "Unable to alloc memory!\n");
448 There are exceptions to this rule. One example is walking a data structure in
452 while ((opt = poptGetNextOpt(pc)) != -1) {
453 ... do something with opt ...
457 Another exception: DBG messages for example printing a SID or a GUID:
458 Here we don't expect any surprise from the printing functions, and the
459 main reason of this guideline is to make debugging easier. That reason
460 rarely exists for this particular use case, and we gain some
461 efficiency because the DBG_ macros don't evaluate their arguments if
462 the debuglevel is not high enough.
465 if (!NT_STATUS_IS_OK(status)) {
466 struct dom_sid_buf sid_buf;
467 struct GUID_txt_buf guid_buf;
469 "objectSID [%s] for GUID [%s] invalid\n",
470 dom_sid_str_buf(objectsid, &sid_buf),
471 GUID_buf_string(&cache->entries[idx], &guid_buf));
475 But in general, please try to avoid this pattern.
478 ### Control-Flow changing macros
480 Macros like `NT_STATUS_NOT_OK_RETURN` that change control flow
481 (`return`/`goto`/etc) from within the macro are considered bad, because
482 they look like function calls that never change control flow. Please
483 do not use them in new code.
485 The only exception is the test code that depends repeated use of calls
486 like `CHECK_STATUS`, `CHECK_VAL` and others.
489 ### Error and out logic
494 frame = talloc_stackframe();
496 if (ret == LDB_SUCCESS) {
497 if (result->count == 0) {
498 ret = LDB_ERR_NO_SUCH_OBJECT;
500 struct ldb_message *match =
501 get_best_match(dn, result);
504 return LDB_ERR_OPERATIONS_ERROR;
506 *msg = talloc_move(mem_ctx, &match);
517 frame = talloc_stackframe();
519 if (ret != LDB_SUCCESS) {
524 if (result->count == 0) {
526 return LDB_ERR_NO_SUCH_OBJECT;
529 match = get_best_match(dn, result);
532 return LDB_ERR_OPERATIONS_ERROR;
535 *msg = talloc_move(mem_ctx, &match);
543 Use these following macros instead of DEBUG:
546 DBG_ERR log level 0 error conditions
547 DBG_WARNING log level 1 warning conditions
548 DBG_NOTICE log level 3 normal, but significant, condition
549 DBG_INFO log level 5 informational message
550 DBG_DEBUG log level 10 debug-level message
556 DBG_ERR("Memory allocation failed\n");
557 DBG_DEBUG("Received %d bytes\n", count);
560 The messages from these macros are automatically prefixed with the