s2: VFS: default. Fix vfswrap_read_dfs_pathat() to use fsp_get_pathref_fd() not fsp_g...
[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
21 should be compatible with Python 3.6 onwards.
22
23 But to save you the trouble of reading the Linux kernel style guide, here
24 are the highlights.
25
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.
31
32 * Use 8 Space Tabs to Indent
33   No whitespace fillers.
34
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.
38
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.
42
43
44
45 ## Editor Hints
46
47 ### Emacs
48
49 Add the follow to your $HOME/.emacs file:
50
51 ```
52   (add-hook 'c-mode-hook
53         (lambda ()
54                 (c-set-style "linux")
55                 (c-toggle-auto-state)))
56 ```
57
58
59 ### Vi
60
61 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
62
63 For the basic vi editor included with all variants of \*nix, add the
64 following to $HOME/.exrc:
65
66 ```
67   set tabstop=8
68   set shiftwidth=8
69 ```
70
71 For Vim, the following settings in $HOME/.vimrc will also deal with
72 displaying trailing whitespace:
73
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:…
85
86   " highlight overly long lines same as TODOs.
87   set textwidth=80
88   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
89 ```
90
91 ### clang-format
92
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
103 ```
104
105
106 ## FAQ & Statement Reference
107
108 ### Comments
109
110 Comments should always use the standard C syntax.  C++
111 style comments are not currently allowed.
112
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.
117
118 This is good:
119
120 ```
121         ...
122         int i;
123
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          */
131
132         /* This is a one line comment about i = 5. */
133         i = 5;
134
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         ...
142
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);
156 ```
157
158 This is bad:
159
160 ```
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         ...
179
180         /*This is a one line comment.*/
181
182         /* This is a multi line comment,
183            with some more words...*/
184
185         /*
186          * This is a multi line comment,
187          * with some more words...*/
188 ```
189
190 ### Indention & Whitespace & 80 columns
191
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,
197
198 ```
199         var1 = foo(arg1, arg2,
200                    arg3);
201 ```
202
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.
207
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.
213
214
215 ## If, switch, & Code blocks
216
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:
220
221 ```
222         if (x == 1)
223 ```
224
225 This is bad:
226
227 ```
228         if ( x == 1 )
229 ```
230
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.
233
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.
237
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.
243
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.
246
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.
250
251 Good examples:
252
253 ```
254         if (x == 1) {
255                 printf("good\n");
256         }
257
258         for (x=1; x<10; x++) {
259                 print("%d\n", x);
260         }
261
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         }
268
269         do {
270                 printf("also good\n");
271         } while (1);
272 ```
273
274 Bad examples:
275
276 ```
277         while (1)
278         {
279                 print("I'm in a loop!\n"); }
280
281         for (x=1;
282              x<10;
283              x++)
284         {
285                 print("no good\n");
286         }
287
288         if (i < 10)
289                 print("I should be in braces.\n");
290 ```
291
292
293 ### Goto
294
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.
300
301 Good Examples:
302
303 ```
304         int function foo(int y)
305         {
306                 int *z = NULL;
307                 int ret = 0;
308
309                 if (y < 10) {
310                         z = malloc(sizeof(int) * y);
311                         if (z == NULL) {
312                                 ret = 1;
313                                 goto done;
314                         }
315                 }
316
317                 print("Allocated %d elements.\n", y);
318
319          done:
320                 if (z != NULL) {
321                         free(z);
322                 }
323
324                 return ret;
325         }
326 ```
327
328
329 ### Primitive Data Types
330
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:
337
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`
341
342 Most of the time a good name for a boolean variable is 'ok'. Here is an
343 example we often use:
344
345 ```
346         bool ok;
347
348         ok = foo();
349         if (!ok) {
350                 /* do something */
351         }
352 ```
353
354 It makes the code more readable and is easy to debug.
355
356 ### Typedefs
357
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.
361
362 ### Initialize pointers
363
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.
367
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.
371
372 Good Example:
373
374 ```
375         char *pointer1 = NULL;
376         char *pointer2 = NULL;
377
378         pointer2 = some_func2();
379
380         ...
381
382         pointer1 = some_func1();
383 ```
384
385 Bad Example:
386
387 ```
388         char *pointer1;
389         char *pointer2;
390
391         pointer2 = some_func2();
392
393         ...
394
395         pointer1 = some_func1();
396 ```
397
398 ### Make use of helper variables
399
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.
403
404 Good Example:
405
406 ```
407         char *name = NULL;
408         int ret;
409
410         name = get_some_name();
411         if (name == NULL) {
412                 ...
413         }
414
415         ret = some_function_my_name(name);
416         ...
417 ```
418
419
420 Bad Example:
421
422 ```
423         ret = some_function_my_name(get_some_name());
424         ...
425 ```
426
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.
430
431 Good example:
432
433 ```
434         x = malloc(sizeof(short)*10);
435         if (x == NULL) {
436                 fprintf(stderr, "Unable to alloc memory!\n");
437         }
438 ```
439
440 Bad example:
441
442 ```
443         if ((x = malloc(sizeof(short)*10)) == NULL ) {
444                 fprintf(stderr, "Unable to alloc memory!\n");
445         }
446 ```
447
448 There are exceptions to this rule. One example is walking a data structure in
449 an iterator style:
450
451 ```
452         while ((opt = poptGetNextOpt(pc)) != -1) {
453                    ... do something with opt ...
454         }
455 ```
456
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.
463
464 ```
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         }
473 ```
474
475 But in general, please try to avoid this pattern.
476
477
478 ### Control-Flow changing macros
479
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.
484
485 The only exception is the test code that depends repeated use of calls
486 like `CHECK_STATUS`, `CHECK_VAL` and others.
487
488
489 ### Error and out logic
490
491 Don't do this:
492
493 ```
494         frame = talloc_stackframe();
495
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         }
509
510         TALLOC_FREE(frame);
511         return ret;
512 ```
513
514 It should be:
515
516 ```
517         frame = talloc_stackframe();
518
519         if (ret != LDB_SUCCESS) {
520                 TALLOC_FREE(frame);
521                 return ret;
522         }
523
524         if (result->count == 0) {
525                 TALLOC_FREE(frame);
526                 return LDB_ERR_NO_SUCH_OBJECT;
527         }
528
529         match = get_best_match(dn, result);
530         if (match == NULL) {
531                 TALLOC_FREE(frame);
532                 return LDB_ERR_OPERATIONS_ERROR;
533         }
534
535         *msg = talloc_move(mem_ctx, &match);
536         TALLOC_FREE(frame);
537         return LDB_SUCCESS;
538 ```
539
540
541 ### DEBUG statements
542
543 Use these following macros instead of DEBUG:
544
545 ```
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
551 ```
552
553 Example usage:
554
555 ```
556 DBG_ERR("Memory allocation failed\n");
557 DBG_DEBUG("Received %d bytes\n", count);
558 ```
559
560 The messages from these macros are automatically prefixed with the
561 function name.