smbd: Remove unused [push_pull]_file_id_24
[samba.git] / README.Coding.md
blob76f2c70e95a263654070b528aa4c9f8260c0c5a7
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 ### 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
100 staged changes.
102 ## FAQ & Statement Reference
104 ### Comments
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.
114 This is good:
117         ...
118         int i;
120         /*
121          * This is a multi line comment,
122          * which explains the logical steps we have to do:
123          *
124          * 1. We need to set i=5, because...
125          * 2. We need to call complex_fn1
126          */
128         /* This is a one line comment about i = 5. */
129         i = 5;
131         /*
132          * This is a multi line comment,
133          * explaining the call to complex_fn1()
134          */
135         ret = complex_fn1();
136         if (ret != 0) {
137         ...
139         /**
140          * @brief This is a doxygen comment.
141          *
142          * This is a more detailed explanation of
143          * this simple function.
144          *
145          * @param[in]   param1     The parameter value of the function.
146          *
147          * @param[out]  result1    The result value of the function.
148          *
149          * @return              0 on success and -1 on error.
150          */
151         int example(int param1, int *result1);
154 This is bad:
157         ...
158         int i;
159         /*
160          * This is a multi line comment,
161          * which explains the logical steps we have to do:
162          *
163          * 1. We need to set i=5, because...
164          * 2. We need to call complex_fn1
165          */
166         /* This is a one line comment about i = 5. */
167         i = 5;
168         /*
169          * This is a multi line comment,
170          * explaining the call to complex_fn1()
171          */
172         ret = complex_fn1();
173         if (ret != 0) {
174         ...
176         /*This is a one line comment.*/
178         /* This is a multi line comment,
179            with some more words...*/
181         /*
182          * This is a multi line comment,
183          * with some more words...*/
186 ### Indentation & 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,
196                    arg3);
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.
215 This is good:
218         if (x == 1)
221 This is bad:
224         if ( x == 1 )
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
232 invoking functions.
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`
245 loop.
247 Good examples:
250         if (x == 1) {
251                 printf("good\n");
252         }
254         for (x=1; x<10; x++) {
255                 print("%d\n", x);
256         }
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++)
261         {
262                 print("%d\n", really_really_really_really_long_var_name);
263         }
265         do {
266                 printf("also good\n");
267         } while (1);
270 Bad examples:
273         while (1)
274         {
275                 print("I'm in a loop!\n"); }
277         for (x=1;
278              x<10;
279              x++)
280         {
281                 print("no good\n");
282         }
284         if (i < 10)
285                 print("I should be in braces.\n");
289 ### Goto
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
295 idea.
297 Good Examples:
300         int function foo(int y)
301         {
302                 int *z = NULL;
303                 int ret = 0;
305                 if (y < 10) {
306                         z = malloc(sizeof(int) * y);
307                         if (z == NULL) {
308                                 ret = 1;
309                                 goto done;
310                         }
311                 }
313                 print("Allocated %d elements.\n", y);
315          done:
316                 if (z != NULL) {
317                         free(z);
318                 }
320                 return ret;
321         }
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:
342         bool ok;
344         ok = foo();
345         if (!ok) {
346                 /* do something */
347         }
350 It makes the code more readable and is easy to debug.
352 ### Typedefs
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.
368 Good Example:
371         char *pointer1 = NULL;
372         char *pointer2 = NULL;
374         pointer2 = some_func2();
376         ...
378         pointer1 = some_func1();
381 Bad Example:
384         char *pointer1;
385         char *pointer2;
387         pointer2 = some_func2();
389         ...
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.
400 Good Example:
403         char *name = NULL;
404         int ret;
406         name = get_some_name();
407         if (name == NULL) {
408                 ...
409         }
411         ret = some_function_my_name(name);
412         ...
416 Bad Example:
419         ret = some_function_my_name(get_some_name());
420         ...
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
425 debugger.
427 Good example:
430         x = malloc(sizeof(short)*10);
431         if (x == NULL) {
432                 fprintf(stderr, "Unable to alloc memory!\n");
433         }
436 Bad example:
439         if ((x = malloc(sizeof(short)*10)) == NULL ) {
440                 fprintf(stderr, "Unable to alloc memory!\n");
441         }
444 There are exceptions to this rule. One example is walking a data structure in
445 an iterator style:
448         while ((opt = poptGetNextOpt(pc)) != -1) {
449                    ... do something with opt ...
450         }
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;
464                 DBG_WARNING(
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));
468         }
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
487 Don't do this:
490         frame = talloc_stackframe();
492         if (ret == LDB_SUCCESS) {
493                 if (result->count == 0) {
494                         ret = LDB_ERR_NO_SUCH_OBJECT;
495                 } else {
496                         struct ldb_message *match =
497                                 get_best_match(dn, result);
498                         if (match == NULL) {
499                                 TALLOC_FREE(frame);
500                                 return LDB_ERR_OPERATIONS_ERROR;
501                         }
502                         *msg = talloc_move(mem_ctx, &match);
503                 }
504         }
506         TALLOC_FREE(frame);
507         return ret;
510 It should be:
513         frame = talloc_stackframe();
515         if (ret != LDB_SUCCESS) {
516                 TALLOC_FREE(frame);
517                 return ret;
518         }
520         if (result->count == 0) {
521                 TALLOC_FREE(frame);
522                 return LDB_ERR_NO_SUCH_OBJECT;
523         }
525         match = get_best_match(dn, result);
526         if (match == NULL) {
527                 TALLOC_FREE(frame);
528                 return LDB_ERR_OPERATIONS_ERROR;
529         }
531         *msg = talloc_move(mem_ctx, &match);
532         TALLOC_FREE(frame);
533         return LDB_SUCCESS;
537 ### DEBUG statements
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
549 Example usage:
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
557 function name.
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.
572 Example usage:
575 D_DEBUG("Resolving %"PRIu32" SID(s).\n", state->num_sids);
578 Note:
580 Do not use PRIu32 for uid_t and gid_t, they do not have to be uint32_t.