ctdb-utils: Add tdb_mutex_check utility
[Samba.git] / README.Coding.md
blobb87580f5f85e20240f5f715dd6534f8935edce32
1 # Coding conventions in the Samba tree
3 ## Quick Start
5 Coding style guidelines are about reducing the number of unnecessary
6 reformatting patches and making things easier for developers to work
7 together.
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
17 mentioned below.
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
24 are the highlights.
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
37   committing.
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.
45 ## Editor Hints
47 ### Emacs
49 Add the follow to your $HOME/.emacs file:
51 ```
52   (add-hook 'c-mode-hook
53         (lambda ()
54                 (c-set-style "linux")
55                 (c-toggle-auto-state)))
56 ```
59 ### Vi
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:
66 ```
67   set tabstop=8
68   set shiftwidth=8
69 ```
71 For Vim, the following settings in $HOME/.vimrc will also deal with
72 displaying trailing whitespace:
74 ```
75   if has("syntax") && (&t_Co > 2 || has("gui_running"))
76         syntax on
77         function! ActivateInvisibleCharIndicator()
78                 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
79                 highlight TrailingSpace ctermbg=Red
80         endf
81         autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
82   endif
83   " Show tabs, trailing whitespace, and continued lines visually
84   set list listchars=tab:»·,trail:·,extends:…
86   " highlight overly long lines same as TODOs.
87   set textwidth=80
88   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
89 ```
91 ### clang-format
93 ```
94 BasedOnStyle: LLVM
95 IndentWidth: 8
96 UseTab: true
97 BreakBeforeBraces: Linux
98 AllowShortIfStatementsOnASingleLine: false
99 IndentCaseLabels: false
100 BinPackParameters: false
101 BinPackArguments: false
102 SortIncludes: false
106 ## FAQ & Statement Reference
108 ### Comments
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.
118 This is good:
121         ...
122         int i;
124         /*
125          * This is a multi line comment,
126          * which explains the logical steps we have to do:
127          *
128          * 1. We need to set i=5, because...
129          * 2. We need to call complex_fn1
130          */
132         /* This is a one line comment about i = 5. */
133         i = 5;
135         /*
136          * This is a multi line comment,
137          * explaining the call to complex_fn1()
138          */
139         ret = complex_fn1();
140         if (ret != 0) {
141         ...
143         /**
144          * @brief This is a doxygen comment.
145          *
146          * This is a more detailed explanation of
147          * this simple function.
148          *
149          * @param[in]   param1     The parameter value of the function.
150          *
151          * @param[out]  result1    The result value of the function.
152          *
153          * @return              0 on success and -1 on error.
154          */
155         int example(int param1, int *result1);
158 This is bad:
161         ...
162         int i;
163         /*
164          * This is a multi line comment,
165          * which explains the logical steps we have to do:
166          *
167          * 1. We need to set i=5, because...
168          * 2. We need to call complex_fn1
169          */
170         /* This is a one line comment about i = 5. */
171         i = 5;
172         /*
173          * This is a multi line comment,
174          * explaining the call to complex_fn1()
175          */
176         ret = complex_fn1();
177         if (ret != 0) {
178         ...
180         /*This is a one line comment.*/
182         /* This is a multi line comment,
183            with some more words...*/
185         /*
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,
200                    arg3);
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.
219 This is good:
222         if (x == 1)
225 This is bad:
228         if ( x == 1 )
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
236 invoking functions.
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`
249 loop.
251 Good examples:
254         if (x == 1) {
255                 printf("good\n");
256         }
258         for (x=1; x<10; x++) {
259                 print("%d\n", x);
260         }
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++)
265         {
266                 print("%d\n", really_really_really_really_long_var_name);
267         }
269         do {
270                 printf("also good\n");
271         } while (1);
274 Bad examples:
277         while (1)
278         {
279                 print("I'm in a loop!\n"); }
281         for (x=1;
282              x<10;
283              x++)
284         {
285                 print("no good\n");
286         }
288         if (i < 10)
289                 print("I should be in braces.\n");
293 ### Goto
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
299 idea.
301 Good Examples:
304         int function foo(int y)
305         {
306                 int *z = NULL;
307                 int ret = 0;
309                 if (y < 10) {
310                         z = malloc(sizeof(int) * y);
311                         if (z == NULL) {
312                                 ret = 1;
313                                 goto done;
314                         }
315                 }
317                 print("Allocated %d elements.\n", y);
319          done:
320                 if (z != NULL) {
321                         free(z);
322                 }
324                 return ret;
325         }
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:
346         bool ok;
348         ok = foo();
349         if (!ok) {
350                 /* do something */
351         }
354 It makes the code more readable and is easy to debug.
356 ### Typedefs
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.
372 Good Example:
375         char *pointer1 = NULL;
376         char *pointer2 = NULL;
378         pointer2 = some_func2();
380         ...
382         pointer1 = some_func1();
385 Bad Example:
388         char *pointer1;
389         char *pointer2;
391         pointer2 = some_func2();
393         ...
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.
404 Good Example:
407         char *name = NULL;
408         int ret;
410         name = get_some_name();
411         if (name == NULL) {
412                 ...
413         }
415         ret = some_function_my_name(name);
416         ...
420 Bad Example:
423         ret = some_function_my_name(get_some_name());
424         ...
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
429 debugger.
431 Good example:
434         x = malloc(sizeof(short)*10);
435         if (x == NULL) {
436                 fprintf(stderr, "Unable to alloc memory!\n");
437         }
440 Bad example:
443         if ((x = malloc(sizeof(short)*10)) == NULL ) {
444                 fprintf(stderr, "Unable to alloc memory!\n");
445         }
448 There are exceptions to this rule. One example is walking a data structure in
449 an iterator style:
452         while ((opt = poptGetNextOpt(pc)) != -1) {
453                    ... do something with opt ...
454         }
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;
468                 DBG_WARNING(
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));
472         }
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
491 Don't do this:
494         frame = talloc_stackframe();
496         if (ret == LDB_SUCCESS) {
497                 if (result->count == 0) {
498                         ret = LDB_ERR_NO_SUCH_OBJECT;
499                 } else {
500                         struct ldb_message *match =
501                                 get_best_match(dn, result);
502                         if (match == NULL) {
503                                 TALLOC_FREE(frame);
504                                 return LDB_ERR_OPERATIONS_ERROR;
505                         }
506                         *msg = talloc_move(mem_ctx, &match);
507                 }
508         }
510         TALLOC_FREE(frame);
511         return ret;
514 It should be:
517         frame = talloc_stackframe();
519         if (ret != LDB_SUCCESS) {
520                 TALLOC_FREE(frame);
521                 return ret;
522         }
524         if (result->count == 0) {
525                 TALLOC_FREE(frame);
526                 return LDB_ERR_NO_SUCH_OBJECT;
527         }
529         match = get_best_match(dn, result);
530         if (match == NULL) {
531                 TALLOC_FREE(frame);
532                 return LDB_ERR_OPERATIONS_ERROR;
533         }
535         *msg = talloc_move(mem_ctx, &match);
536         TALLOC_FREE(frame);
537         return LDB_SUCCESS;
541 ### DEBUG statements
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
553 Example usage:
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
561 function name.