VERSION: Bump version up to Samba 4.13.18...
[samba.git] / README.Coding.md
1 # Coding conventions in the Samba tree
2
3 ## Quick Start
4
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.
13
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.
18
19 The coding style for Python code is documented in
20 [PEP8](https://www.python.org/dev/peps/pep-0008/). New Python code should be compatible
21 with Python 2.6, 2.7, and Python 3.4 onwards. This means using Python 3 syntax
22 with the appropriate `from __future__` imports.
23
24 But to save you the trouble of reading the Linux kernel style guide, here
25 are the highlights.
26
27 * Maximum Line Width is 80 Characters
28   The reason is not about people with low-res screens but rather sticking
29   to 80 columns prevents you from easily nesting more than one level of
30   if statements or other code blocks.  Use [source3/script/count_80_col.pl](source3/script/count_80_col.pl)
31   to check your changes.
32
33 * Use 8 Space Tabs to Indent
34   No whitespace fillers.
35
36 * No Trailing Whitespace
37   Use [source3/script/strip_trail_ws.pl](source3/script/strip_trail_ws.pl) to clean up your files before
38   committing.
39
40 * Follow the K&R guidelines.  We won't go through all of them here. Do you
41   have a copy of "The C Programming Language" anyways right? You can also use
42   the [format_indent.sh script found in source3/script/](source3/script/format_indent.sh) if all else fails.
43
44
45
46 ## Editor Hints
47
48 ### Emacs
49
50 Add the follow to your $HOME/.emacs file:
51
52 ```
53   (add-hook 'c-mode-hook
54         (lambda ()
55                 (c-set-style "linux")
56                 (c-toggle-auto-state)))
57 ```
58
59
60 ### Vi
61
62 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
63
64 For the basic vi editor included with all variants of \*nix, add the
65 following to $HOME/.exrc:
66
67 ```
68   set tabstop=8
69   set shiftwidth=8
70 ```
71
72 For Vim, the following settings in $HOME/.vimrc will also deal with
73 displaying trailing whitespace:
74
75 ```
76   if has("syntax") && (&t_Co > 2 || has("gui_running"))
77         syntax on
78         function! ActivateInvisibleCharIndicator()
79                 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
80                 highlight TrailingSpace ctermbg=Red
81         endf
82         autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
83   endif
84   " Show tabs, trailing whitespace, and continued lines visually
85   set list listchars=tab:»·,trail:·,extends:…
86
87   " highlight overly long lines same as TODOs.
88   set textwidth=80
89   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
90 ```
91
92 ### clang-format
93
94 ```
95 BasedOnStyle: LLVM
96 IndentWidth: 8
97 UseTab: true
98 BreakBeforeBraces: Linux
99 AllowShortIfStatementsOnASingleLine: false
100 IndentCaseLabels: false
101 BinPackParameters: false
102 BinPackArguments: false
103 SortIncludes: false
104 ```
105
106
107 ## FAQ & Statement Reference
108
109 ### Comments
110
111 Comments should always use the standard C syntax.  C++
112 style comments are not currently allowed.
113
114 The lines before a comment should be empty. If the comment directly
115 belongs to the following code, there should be no empty line
116 after the comment, except if the comment contains a summary
117 of multiple following code blocks.
118
119 This is good:
120
121 ```
122         ...
123         int i;
124
125         /*
126          * This is a multi line comment,
127          * which explains the logical steps we have to do:
128          *
129          * 1. We need to set i=5, because...
130          * 2. We need to call complex_fn1
131          */
132
133         /* This is a one line comment about i = 5. */
134         i = 5;
135
136         /*
137          * This is a multi line comment,
138          * explaining the call to complex_fn1()
139          */
140         ret = complex_fn1();
141         if (ret != 0) {
142         ...
143
144         /**
145          * @brief This is a doxygen comment.
146          *
147          * This is a more detailed explanation of
148          * this simple function.
149          *
150          * @param[in]   param1     The parameter value of the function.
151          *
152          * @param[out]  result1    The result value of the function.
153          *
154          * @return              0 on success and -1 on error.
155          */
156         int example(int param1, int *result1);
157 ```
158
159 This is bad:
160
161 ```
162         ...
163         int i;
164         /*
165          * This is a multi line comment,
166          * which explains the logical steps we have to do:
167          *
168          * 1. We need to set i=5, because...
169          * 2. We need to call complex_fn1
170          */
171         /* This is a one line comment about i = 5. */
172         i = 5;
173         /*
174          * This is a multi line comment,
175          * explaining the call to complex_fn1()
176          */
177         ret = complex_fn1();
178         if (ret != 0) {
179         ...
180
181         /*This is a one line comment.*/
182
183         /* This is a multi line comment,
184            with some more words...*/
185
186         /*
187          * This is a multi line comment,
188          * with some more words...*/
189 ```
190
191 ### Indention & Whitespace & 80 columns
192
193 To avoid confusion, indentations have to be tabs with length 8 (not 8
194 ' ' characters).  When wrapping parameters for function calls,
195 align the parameter list with the first parameter on the previous line.
196 Use tabs to get as close as possible and then fill in the final 7
197 characters or less with whitespace.  For example,
198
199 ```
200         var1 = foo(arg1, arg2,
201                    arg3);
202 ```
203
204 The previous example is intended to illustrate alignment of function
205 parameters across lines and not as encourage for gratuitous line
206 splitting.  Never split a line before columns 70 - 79 unless you
207 have a really good reason. Be smart about formatting.
208
209 One exception to the previous rule is function calls, declarations, and
210 definitions. In function calls, declarations, and definitions, either the
211 declaration is a one-liner, or each parameter is listed on its own
212 line. The rationale is that if there are many parameters, each one
213 should be on its own line to make tracking interface changes easier.
214
215
216 ## If, switch, & Code blocks
217
218 Always follow an `if` keyword with a space but don't include additional
219 spaces following or preceding the parentheses in the conditional.
220 This is good:
221
222 ```
223         if (x == 1)
224 ```
225
226 This is bad:
227
228 ```
229         if ( x == 1 )
230 ```
231
232 Yes we have a lot of code that uses the second form and we are trying
233 to clean it up without being overly intrusive.
234
235 Note that this is a rule about parentheses following keywords and not
236 functions.  Don't insert a space between the name and left parentheses when
237 invoking functions.
238
239 Braces for code blocks used by `for`, `if`, `switch`, `while`, `do..while`, etc.
240 should begin on the same line as the statement keyword and end on a line
241 of their own. You should always include braces, even if the block only
242 contains one statement.  NOTE: Functions are different and the beginning left
243 brace should be located in the first column on the next line.
244
245 If the beginning statement has to be broken across lines due to length,
246 the beginning brace should be on a line of its own.
247
248 The exception to the ending rule is when the closing brace is followed by
249 another language keyword such as else or the closing while in a `do..while`
250 loop.
251
252 Good examples:
253
254 ```
255         if (x == 1) {
256                 printf("good\n");
257         }
258
259         for (x=1; x<10; x++) {
260                 print("%d\n", x);
261         }
262
263         for (really_really_really_really_long_var_name=0;
264              really_really_really_really_long_var_name<10;
265              really_really_really_really_long_var_name++)
266         {
267                 print("%d\n", really_really_really_really_long_var_name);
268         }
269
270         do {
271                 printf("also good\n");
272         } while (1);
273 ```
274
275 Bad examples:
276
277 ```
278         while (1)
279         {
280                 print("I'm in a loop!\n"); }
281
282         for (x=1;
283              x<10;
284              x++)
285         {
286                 print("no good\n");
287         }
288
289         if (i < 10)
290                 print("I should be in braces.\n");
291 ```
292
293
294 ### Goto
295
296 While many people have been academically taught that `goto`s are
297 fundamentally evil, they can greatly enhance readability and reduce memory
298 leaks when used as the single exit point from a function. But in no Samba
299 world what so ever is a goto outside of a function or block of code a good
300 idea.
301
302 Good Examples:
303
304 ```
305         int function foo(int y)
306         {
307                 int *z = NULL;
308                 int ret = 0;
309
310                 if (y < 10) {
311                         z = malloc(sizeof(int) * y);
312                         if (z == NULL) {
313                                 ret = 1;
314                                 goto done;
315                         }
316                 }
317
318                 print("Allocated %d elements.\n", y);
319
320          done:
321                 if (z != NULL) {
322                         free(z);
323                 }
324
325                 return ret;
326         }
327 ```
328
329
330 ### Primitive Data Types
331
332 Samba has large amounts of historical code which makes use of data types
333 commonly supported by the C99 standard. However, at the time such types
334 as boolean and exact width integers did not exist and Samba developers
335 were forced to provide their own.  Now that these types are guaranteed to
336 be available either as part of the compiler C99 support or from
337 lib/replace/, new code should adhere to the following conventions:
338
339   * Booleans are of type `bool` (not `BOOL`)
340   * Boolean values are `true` and `false` (not `True` or `False`)
341   * Exact width integers are of type `[u]int[8|16|32|64]_t`
342
343 Most of the time a good name for a boolean variable is 'ok'. Here is an
344 example we often use:
345
346 ```
347         bool ok;
348
349         ok = foo();
350         if (!ok) {
351                 /* do something */
352         }
353 ```
354
355 It makes the code more readable and is easy to debug.
356
357 ### Typedefs
358
359 Samba tries to avoid `typedef struct { .. } x_t;` so we do always try to use
360 `struct x { .. };`. We know there are still such typedefs in the code,
361 but for new code, please don't do that anymore.
362
363 ### Initialize pointers
364
365 All pointer variables MUST be initialized to NULL. History has
366 demonstrated that uninitialized pointer variables have lead to various
367 bugs and security issues.
368
369 Pointers MUST be initialized even if the assignment directly follows
370 the declaration, like pointer2 in the example below, because the
371 instructions sequence may change over time.
372
373 Good Example:
374
375 ```
376         char *pointer1 = NULL;
377         char *pointer2 = NULL;
378
379         pointer2 = some_func2();
380
381         ...
382
383         pointer1 = some_func1();
384 ```
385
386 Bad Example:
387
388 ```
389         char *pointer1;
390         char *pointer2;
391
392         pointer2 = some_func2();
393
394         ...
395
396         pointer1 = some_func1();
397 ```
398
399 ### Make use of helper variables
400
401 Please try to avoid passing function calls as function parameters
402 in new code. This makes the code much easier to read and
403 it's also easier to use the "step" command within gdb.
404
405 Good Example:
406
407 ```
408         char *name = NULL;
409         int ret;
410
411         name = get_some_name();
412         if (name == NULL) {
413                 ...
414         }
415
416         ret = some_function_my_name(name);
417         ...
418 ```
419
420
421 Bad Example:
422
423 ```
424         ret = some_function_my_name(get_some_name());
425         ...
426 ```
427
428 Please try to avoid passing function return values to if- or
429 while-conditions. The reason for this is better handling of code under a
430 debugger.
431
432 Good example:
433
434 ```
435         x = malloc(sizeof(short)*10);
436         if (x == NULL) {
437                 fprintf(stderr, "Unable to alloc memory!\n");
438         }
439 ```
440
441 Bad example:
442
443 ```
444         if ((x = malloc(sizeof(short)*10)) == NULL ) {
445                 fprintf(stderr, "Unable to alloc memory!\n");
446         }
447 ```
448
449 There are exceptions to this rule. One example is walking a data structure in
450 an iterator style:
451
452 ```
453         while ((opt = poptGetNextOpt(pc)) != -1) {
454                    ... do something with opt ...
455         }
456 ```
457
458 Another exception: DBG messages for example printing a SID or a GUID:
459 Here we don't expect any surprise from the printing functions, and the
460 main reason of this guideline is to make debugging easier. That reason
461 rarely exists for this particular use case, and we gain some
462 efficiency because the DBG_ macros don't evaluate their arguments if
463 the debuglevel is not high enough.
464
465 ```
466         if (!NT_STATUS_IS_OK(status)) {
467                 struct dom_sid_buf sid_buf;
468                 struct GUID_txt_buf guid_buf;
469                 DBG_WARNING(
470                     "objectSID [%s] for GUID [%s] invalid\n",
471                     dom_sid_str_buf(objectsid, &sid_buf),
472                     GUID_buf_string(&cache->entries[idx], &guid_buf));
473         }
474 ```
475
476 But in general, please try to avoid this pattern.
477
478
479 ### Control-Flow changing macros
480
481 Macros like `NT_STATUS_NOT_OK_RETURN` that change control flow
482 (`return`/`goto`/etc) from within the macro are considered bad, because
483 they look like function calls that never change control flow. Please
484 do not use them in new code.
485
486 The only exception is the test code that depends repeated use of calls
487 like `CHECK_STATUS`, `CHECK_VAL` and others.
488
489
490 ### Error and out logic
491
492 Don't do this:
493
494 ```
495         frame = talloc_stackframe();
496
497         if (ret == LDB_SUCCESS) {
498                 if (result->count == 0) {
499                         ret = LDB_ERR_NO_SUCH_OBJECT;
500                 } else {
501                         struct ldb_message *match =
502                                 get_best_match(dn, result);
503                         if (match == NULL) {
504                                 TALLOC_FREE(frame);
505                                 return LDB_ERR_OPERATIONS_ERROR;
506                         }
507                         *msg = talloc_move(mem_ctx, &match);
508                 }
509         }
510
511         TALLOC_FREE(frame);
512         return ret;
513 ```
514
515 It should be:
516
517 ```
518         frame = talloc_stackframe();
519
520         if (ret != LDB_SUCCESS) {
521                 TALLOC_FREE(frame);
522                 return ret;
523         }
524
525         if (result->count == 0) {
526                 TALLOC_FREE(frame);
527                 return LDB_ERR_NO_SUCH_OBJECT;
528         }
529
530         match = get_best_match(dn, result);
531         if (match == NULL) {
532                 TALLOC_FREE(frame);
533                 return LDB_ERR_OPERATIONS_ERROR;
534         }
535
536         *msg = talloc_move(mem_ctx, &match);
537         TALLOC_FREE(frame);
538         return LDB_SUCCESS;
539 ```
540
541
542 ### DEBUG statements
543
544 Use these following macros instead of DEBUG:
545
546 ```
547 DBG_ERR         log level 0             error conditions
548 DBG_WARNING     log level 1             warning conditions
549 DBG_NOTICE      log level 3             normal, but significant, condition
550 DBG_INFO        log level 5             informational message
551 DBG_DEBUG       log level 10            debug-level message
552 ```
553
554 Example usage:
555
556 ```
557 DBG_ERR("Memory allocation failed\n");
558 DBG_DEBUG("Received %d bytes\n", count);
559 ```
560
561 The messages from these macros are automatically prefixed with the
562 function name.