ldb-samba: ldif_read_objectSid avoids VLA
[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 ### How to use clang-format
92
93 Install 'git-format-clang' which is part of the clang suite (Fedora:
94 git-clang-format, openSUSE: clang-tools).
95
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.
98
99 Now the formatting changed can be viewed with `git diff` against the
100 staged changes.
101
102 ## FAQ & Statement Reference
103
104 ### Comments
105
106 Comments should always use the standard C syntax.  C++
107 style comments are not currently allowed.
108
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.
113
114 This is good:
115
116 ```
117         ...
118         int i;
119
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          */
127
128         /* This is a one line comment about i = 5. */
129         i = 5;
130
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         ...
138
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);
152 ```
153
154 This is bad:
155
156 ```
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         ...
175
176         /*This is a one line comment.*/
177
178         /* This is a multi line comment,
179            with some more words...*/
180
181         /*
182          * This is a multi line comment,
183          * with some more words...*/
184 ```
185
186 ### Indentation & Whitespace & 80 columns
187
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,
193
194 ```
195         var1 = foo(arg1, arg2,
196                    arg3);
197 ```
198
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.
203
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.
209
210
211 ## If, switch, & Code blocks
212
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:
216
217 ```
218         if (x == 1)
219 ```
220
221 This is bad:
222
223 ```
224         if ( x == 1 )
225 ```
226
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.
229
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.
233
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.
239
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.
242
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.
246
247 Good examples:
248
249 ```
250         if (x == 1) {
251                 printf("good\n");
252         }
253
254         for (x=1; x<10; x++) {
255                 print("%d\n", x);
256         }
257
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         }
264
265         do {
266                 printf("also good\n");
267         } while (1);
268 ```
269
270 Bad examples:
271
272 ```
273         while (1)
274         {
275                 print("I'm in a loop!\n"); }
276
277         for (x=1;
278              x<10;
279              x++)
280         {
281                 print("no good\n");
282         }
283
284         if (i < 10)
285                 print("I should be in braces.\n");
286 ```
287
288
289 ### Goto
290
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.
296
297 Good Examples:
298
299 ```
300         int function foo(int y)
301         {
302                 int *z = NULL;
303                 int ret = 0;
304
305                 if (y < 10) {
306                         z = malloc(sizeof(int) * y);
307                         if (z == NULL) {
308                                 ret = 1;
309                                 goto done;
310                         }
311                 }
312
313                 print("Allocated %d elements.\n", y);
314
315          done:
316                 if (z != NULL) {
317                         free(z);
318                 }
319
320                 return ret;
321         }
322 ```
323
324
325 ### Primitive Data Types
326
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:
333
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`
337
338 Most of the time a good name for a boolean variable is 'ok'. Here is an
339 example we often use:
340
341 ```
342         bool ok;
343
344         ok = foo();
345         if (!ok) {
346                 /* do something */
347         }
348 ```
349
350 It makes the code more readable and is easy to debug.
351
352 ### Typedefs
353
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.
357
358 ### Initialize pointers
359
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.
363
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.
367
368 Good Example:
369
370 ```
371         char *pointer1 = NULL;
372         char *pointer2 = NULL;
373
374         pointer2 = some_func2();
375
376         ...
377
378         pointer1 = some_func1();
379 ```
380
381 Bad Example:
382
383 ```
384         char *pointer1;
385         char *pointer2;
386
387         pointer2 = some_func2();
388
389         ...
390
391         pointer1 = some_func1();
392 ```
393
394 ### Make use of helper variables
395
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.
399
400 Good Example:
401
402 ```
403         char *name = NULL;
404         int ret;
405
406         name = get_some_name();
407         if (name == NULL) {
408                 ...
409         }
410
411         ret = some_function_my_name(name);
412         ...
413 ```
414
415
416 Bad Example:
417
418 ```
419         ret = some_function_my_name(get_some_name());
420         ...
421 ```
422
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.
426
427 Good example:
428
429 ```
430         x = malloc(sizeof(short)*10);
431         if (x == NULL) {
432                 fprintf(stderr, "Unable to alloc memory!\n");
433         }
434 ```
435
436 Bad example:
437
438 ```
439         if ((x = malloc(sizeof(short)*10)) == NULL ) {
440                 fprintf(stderr, "Unable to alloc memory!\n");
441         }
442 ```
443
444 There are exceptions to this rule. One example is walking a data structure in
445 an iterator style:
446
447 ```
448         while ((opt = poptGetNextOpt(pc)) != -1) {
449                    ... do something with opt ...
450         }
451 ```
452
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.
459
460 ```
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         }
469 ```
470
471 But in general, please try to avoid this pattern.
472
473
474 ### Control-Flow changing macros
475
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.
480
481 The only exception is the test code that depends repeated use of calls
482 like `CHECK_STATUS`, `CHECK_VAL` and others.
483
484
485 ### Error and out logic
486
487 Don't do this:
488
489 ```
490         frame = talloc_stackframe();
491
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         }
505
506         TALLOC_FREE(frame);
507         return ret;
508 ```
509
510 It should be:
511
512 ```
513         frame = talloc_stackframe();
514
515         if (ret != LDB_SUCCESS) {
516                 TALLOC_FREE(frame);
517                 return ret;
518         }
519
520         if (result->count == 0) {
521                 TALLOC_FREE(frame);
522                 return LDB_ERR_NO_SUCH_OBJECT;
523         }
524
525         match = get_best_match(dn, result);
526         if (match == NULL) {
527                 TALLOC_FREE(frame);
528                 return LDB_ERR_OPERATIONS_ERROR;
529         }
530
531         *msg = talloc_move(mem_ctx, &match);
532         TALLOC_FREE(frame);
533         return LDB_SUCCESS;
534 ```
535
536
537 ### DEBUG statements
538
539 Use these following macros instead of DEBUG:
540
541 ```
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
547 ```
548
549 Example usage:
550
551 ```
552 DBG_ERR("Memory allocation failed\n");
553 DBG_DEBUG("Received %d bytes\n", count);
554 ```
555
556 The messages from these macros are automatically prefixed with the
557 function name.
558
559
560
561 ### PRINT format specifiers PRIuxx
562
563 Use %PRIu32 instead of %u for uint32_t. Do not assume that this is valid:
564
565 /usr/include/inttypes.h
566 104:# define PRIu32             "u"
567
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.
571
572 Example usage:
573
574 ```
575 D_DEBUG("Resolving %"PRIu32" SID(s).\n", state->num_sids);
576 ```
577
578 Note:
579
580 Do not use PRIu32 for uid_t and gid_t, they do not have to be uint32_t.