vfs_ceph_new: handle case of readlinkat with empty name string
[samba.git] / README.Coding.md
blob53a829cb4f293161c9ad0a118895b4f168bc703f
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();
393 ### Initialize structs
395 All structures MUST be at least initialised to 0/NULL.
397 Current recommended initialization:
399 ```c
400         struct somestruct {
401                 int ival;
402                 bool bval;
403                 double dval;
404                 char *sval;
405         };
407         struct somestruct var1 = {};
410 avoid:
412 ```c
413         struct somestruct var1 = {0};
416 as it can be less portable, in particular if the first element of the struct in question is a nested struct.
418 Of course if specific members need non-zero initialization then use something like:
420 ```c
421         struct bar {
422             int inner;
423         };
424         struct foo {
425                 int outer;
426                 struct bar nested;
427         };
428         struct foo var2 = {
429                 .outer = 5,
430                 .nested = {
431                         .inner = 3,
432                 },
433         };
436 ### Make use of helper variables
438 Please try to avoid passing function calls as function parameters
439 in new code. This makes the code much easier to read and
440 it's also easier to use the "step" command within gdb.
442 Good Example:
445         char *name = NULL;
446         int ret;
448         name = get_some_name();
449         if (name == NULL) {
450                 ...
451         }
453         ret = some_function_my_name(name);
454         ...
458 Bad Example:
461         ret = some_function_my_name(get_some_name());
462         ...
465 Please try to avoid passing function return values to if- or
466 while-conditions. The reason for this is better handling of code under a
467 debugger.
469 Good example:
472         x = malloc(sizeof(short)*10);
473         if (x == NULL) {
474                 fprintf(stderr, "Unable to alloc memory!\n");
475         }
478 Bad example:
481         if ((x = malloc(sizeof(short)*10)) == NULL ) {
482                 fprintf(stderr, "Unable to alloc memory!\n");
483         }
486 There are exceptions to this rule. One example is walking a data structure in
487 an iterator style:
490         while ((opt = poptGetNextOpt(pc)) != -1) {
491                    ... do something with opt ...
492         }
495 Another exception: DBG messages for example printing a SID or a GUID:
496 Here we don't expect any surprise from the printing functions, and the
497 main reason of this guideline is to make debugging easier. That reason
498 rarely exists for this particular use case, and we gain some
499 efficiency because the DBG_ macros don't evaluate their arguments if
500 the debuglevel is not high enough.
503         if (!NT_STATUS_IS_OK(status)) {
504                 struct dom_sid_buf sid_buf;
505                 struct GUID_txt_buf guid_buf;
506                 DBG_WARNING(
507                     "objectSID [%s] for GUID [%s] invalid\n",
508                     dom_sid_str_buf(objectsid, &sid_buf),
509                     GUID_buf_string(&cache->entries[idx], &guid_buf));
510         }
513 But in general, please try to avoid this pattern.
516 ### Control-Flow changing macros
518 Macros like `NT_STATUS_NOT_OK_RETURN` that change control flow
519 (`return`/`goto`/etc) from within the macro are considered bad, because
520 they look like function calls that never change control flow. Please
521 do not use them in new code.
523 The only exception is the test code that depends repeated use of calls
524 like `CHECK_STATUS`, `CHECK_VAL` and others.
527 ### Error and out logic
529 Don't do this:
532         frame = talloc_stackframe();
534         if (ret == LDB_SUCCESS) {
535                 if (result->count == 0) {
536                         ret = LDB_ERR_NO_SUCH_OBJECT;
537                 } else {
538                         struct ldb_message *match =
539                                 get_best_match(dn, result);
540                         if (match == NULL) {
541                                 TALLOC_FREE(frame);
542                                 return LDB_ERR_OPERATIONS_ERROR;
543                         }
544                         *msg = talloc_move(mem_ctx, &match);
545                 }
546         }
548         TALLOC_FREE(frame);
549         return ret;
552 It should be:
555         frame = talloc_stackframe();
557         if (ret != LDB_SUCCESS) {
558                 TALLOC_FREE(frame);
559                 return ret;
560         }
562         if (result->count == 0) {
563                 TALLOC_FREE(frame);
564                 return LDB_ERR_NO_SUCH_OBJECT;
565         }
567         match = get_best_match(dn, result);
568         if (match == NULL) {
569                 TALLOC_FREE(frame);
570                 return LDB_ERR_OPERATIONS_ERROR;
571         }
573         *msg = talloc_move(mem_ctx, &match);
574         TALLOC_FREE(frame);
575         return LDB_SUCCESS;
579 ### DEBUG statements
581 Use these following macros instead of DEBUG:
584 DBG_ERR         log level 0             error conditions
585 DBG_WARNING     log level 1             warning conditions
586 DBG_NOTICE      log level 3             normal, but significant, condition
587 DBG_INFO        log level 5             informational message
588 DBG_DEBUG       log level 10            debug-level message
591 Example usage:
594 DBG_ERR("Memory allocation failed\n");
595 DBG_DEBUG("Received %d bytes\n", count);
598 The messages from these macros are automatically prefixed with the
599 function name.
603 ### PRINT format specifiers PRIuxx
605 Use %PRIu32 instead of %u for uint32_t. Do not assume that this is valid:
607 /usr/include/inttypes.h
608 104:# define PRIu32             "u"
610 It could be possible to have a platform where "unsigned" is 64-bit. In theory
611 even 16-bit. The point is that "unsigned" being 32-bit is nowhere specified.
612 The PRIuxx specifiers are standard.
614 Example usage:
617 D_DEBUG("Resolving %"PRIu32" SID(s).\n", state->num_sids);
620 Note:
622 Do not use PRIu32 for uid_t and gid_t, they do not have to be uint32_t.