s3:utils: Allow to run smbpasswd as user
[sfrench/samba-autobuild/.git] / README.Coding
1 Coding conventions in the Samba tree
2 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3
4 .. contents::
5
6 ===========
7 Quick Start
8 ===========
9
10 Coding style guidelines are about reducing the number of unnecessary
11 reformatting patches and making things easier for developers to work
12 together.
13 You don't have to like them or even agree with them, but once put in place
14 we all have to abide by them (or vote to change them).  However, coding
15 style should never outweigh coding itself and so the guidelines
16 described here are hopefully easy enough to follow as they are very
17 common and supported by tools and editors.
18
19 The basic style for C code, also mentioned in prog_guide4.txt, is the Linux kernel
20 coding style (See Documentation/CodingStyle in the kernel source tree). This
21 closely matches what most Samba developers use already anyways, with a few
22 exceptions as mentioned below.
23
24 The coding style for Python code is documented in PEP8,
25 http://www.python.org/pep/pep8 (with spaces). 
26 If you have ever worked on another free software Python project, you are
27 probably already familiar with it.
28
29 But to save you the trouble of reading the Linux kernel style guide, here
30 are the highlights.
31
32 * Maximum Line Width is 80 Characters
33   The reason is not about people with low-res screens but rather sticking
34   to 80 columns prevents you from easily nesting more than one level of
35   if statements or other code blocks.  Use source3/script/count_80_col.pl
36   to check your changes.
37
38 * Use 8 Space Tabs to Indent
39   No whitespace fillers.
40
41 * No Trailing Whitespace
42   Use source3/script/strip_trail_ws.pl to clean up your files before
43   committing.
44
45 * Follow the K&R guidelines.  We won't go through all of them here. Do you
46   have a copy of "The C Programming Language" anyways right? You can also use
47   the format_indent.sh script found in source3/script/ if all else fails.
48
49
50
51 ============
52 Editor Hints
53 ============
54
55 Emacs
56 -----
57 Add the follow to your $HOME/.emacs file:
58
59   (add-hook 'c-mode-hook
60         (lambda ()
61                 (c-set-style "linux")
62                 (c-toggle-auto-state)))
63
64
65 Vi
66 --
67 (Thanks to SATOH Fumiyasu <fumiyas@osstech.jp> for these hints):
68
69 For the basic vi editor included with all variants of \*nix, add the
70 following to $HOME/.exrc:
71
72   set tabstop=8
73   set shiftwidth=8
74
75 For Vim, the following settings in $HOME/.vimrc will also deal with
76 displaying trailing whitespace:
77
78   if has("syntax") && (&t_Co > 2 || has("gui_running"))
79         syntax on
80         function! ActivateInvisibleCharIndicator()
81                 syntax match TrailingSpace "[ \t]\+$" display containedin=ALL
82                 highlight TrailingSpace ctermbg=Red
83         endf
84         autocmd BufNewFile,BufRead * call ActivateInvisibleCharIndicator()
85   endif
86   " Show tabs, trailing whitespace, and continued lines visually
87   set list listchars=tab:»·,trail:·,extends:…
88
89   " highlight overly long lines same as TODOs.
90   set textwidth=80
91   autocmd BufNewFile,BufRead *.c,*.h exec 'match Todo /\%>' . &textwidth . 'v.\+/'
92
93 clang-format
94 ------------
95 BasedOnStyle: LLVM
96 IndentWidth: 8
97 UseTab: true
98 BreakBeforeBraces: Linux
99 AllowShortIfStatementsOnASingleLine: false
100 IndentCaseLabels: false
101 BinPackParameters: false
102
103
104 =========================
105 FAQ & Statement Reference
106 =========================
107
108 Comments
109 --------
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         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 This is bad:
158
159         ...
160         int i;
161         /*
162          * This is a multi line comment,
163          * which explains the logical steps we have to do:
164          *
165          * 1. We need to set i=5, because...
166          * 2. We need to call complex_fn1
167          */
168         /* This is a one line comment about i = 5. */
169         i = 5;
170         /*
171          * This is a multi line comment,
172          * explaining the call to complex_fn1()
173          */
174         ret = complex_fn1();
175         if (ret != 0) {
176         ...
177
178         /*This is a one line comment.*/
179
180         /* This is a multi line comment,
181            with some more words...*/
182
183         /*
184          * This is a multi line comment,
185          * with some more words...*/
186
187 Indention & Whitespace & 80 columns
188 -----------------------------------
189
190 To avoid confusion, indentations have to be tabs with length 8 (not 8
191 ' ' characters).  When wrapping parameters for function calls,
192 align the parameter list with the first parameter on the previous line.
193 Use tabs to get as close as possible and then fill in the final 7
194 characters or less with whitespace.  For example,
195
196         var1 = foo(arg1, arg2,
197                    arg3);
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 declarations and
205 definitions. In function 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
214 Always follow an 'if' keyword with a space but don't include additional
215 spaces following or preceding the parentheses in the conditional.
216 This is good:
217
218         if (x == 1)
219
220 This is bad:
221
222         if ( x == 1 )
223
224 Yes we have a lot of code that uses the second form and we are trying
225 to clean it up without being overly intrusive.
226
227 Note that this is a rule about parentheses following keywords and not
228 functions.  Don't insert a space between the name and left parentheses when
229 invoking functions.
230
231 Braces for code blocks used by for, if, switch, while, do..while, etc.
232 should begin on the same line as the statement keyword and end on a line
233 of their own. You should always include braces, even if the block only
234 contains one statement.  NOTE: Functions are different and the beginning left
235 brace should be located in the first column on the next line.
236
237 If the beginning statement has to be broken across lines due to length,
238 the beginning brace should be on a line of its own.
239
240 The exception to the ending rule is when the closing brace is followed by
241 another language keyword such as else or the closing while in a do..while
242 loop.
243
244 Good examples:
245
246         if (x == 1) {
247                 printf("good\n");
248         }
249
250         for (x=1; x<10; x++) {
251                 print("%d\n", x);
252         }
253
254         for (really_really_really_really_long_var_name=0;
255              really_really_really_really_long_var_name<10;
256              really_really_really_really_long_var_name++)
257         {
258                 print("%d\n", really_really_really_really_long_var_name);
259         }
260
261         do {
262                 printf("also good\n");
263         } while (1);
264
265 Bad examples:
266
267         while (1)
268         {
269                 print("I'm in a loop!\n"); }
270
271         for (x=1;
272              x<10;
273              x++)
274         {
275                 print("no good\n");
276         }
277
278         if (i < 10)
279                 print("I should be in braces.\n");
280
281
282 Goto
283 ----
284
285 While many people have been academically taught that "goto"s are
286 fundamentally evil, they can greatly enhance readability and reduce memory
287 leaks when used as the single exit point from a function. But in no Samba
288 world what so ever is a goto outside of a function or block of code a good
289 idea.
290
291 Good Examples:
292
293         int function foo(int y)
294         {
295                 int *z = NULL;
296                 int ret = 0;
297
298                 if (y < 10) {
299                         z = malloc(sizeof(int) * y);
300                         if (z == NULL) {
301                                 ret = 1;
302                                 goto done;
303                         }
304                 }
305
306                 print("Allocated %d elements.\n", y);
307
308          done:
309                 if (z != NULL) {
310                         free(z);
311                 }
312
313                 return ret;
314         }
315
316
317 Primitive Data Types
318 --------------------
319
320 Samba has large amounts of historical code which makes use of data types
321 commonly supported by the C99 standard. However, at the time such types
322 as boolean and exact width integers did not exist and Samba developers
323 were forced to provide their own.  Now that these types are guaranteed to
324 be available either as part of the compiler C99 support or from
325 lib/replace/, new code should adhere to the following conventions:
326
327   * Booleans are of type "bool" (not BOOL)
328   * Boolean values are "true" and "false" (not True or False)
329   * Exact width integers are of type [u]int[8|16|32|64]_t
330
331 Most of the time a good name for a boolean variable is 'ok'. Here is an
332 example we often use:
333
334         bool ok;
335
336         ok = foo();
337         if (!ok) {
338                 /* do something */
339         }
340
341 It makes the code more readable and is easy to debug.
342
343 Typedefs
344 --------
345
346 Samba tries to avoid "typedef struct { .. } x_t;" so we do always try to use
347 "struct x { .. };". We know there are still such typedefs in the code,
348 but for new code, please don't do that anymore.
349
350 Initialize pointers
351 -------------------
352
353 All pointer variables MUST be initialized to NULL. History has
354 demonstrated that uninitialized pointer variables have lead to various
355 bugs and security issues.
356
357 Pointers MUST be initialized even if the assignment directly follows
358 the declaration, like pointer2 in the example below, because the
359 instructions sequence may change over time.
360
361 Good Example:
362
363         char *pointer1 = NULL;
364         char *pointer2 = NULL;
365
366         pointer2 = some_func2();
367
368         ...
369
370         pointer1 = some_func1();
371
372 Bad Example:
373
374         char *pointer1;
375         char *pointer2;
376
377         pointer2 = some_func2();
378
379         ...
380
381         pointer1 = some_func1();
382
383 Make use of helper variables
384 ----------------------------
385
386 Please try to avoid passing function calls as function parameters
387 in new code. This makes the code much easier to read and
388 it's also easier to use the "step" command within gdb.
389
390 Good Example:
391
392         char *name = NULL;
393         int ret;
394
395         name = get_some_name();
396         if (name == NULL) {
397                 ...
398         }
399
400         ret = some_function_my_name(name);
401         ...
402
403
404 Bad Example:
405
406         ret = some_function_my_name(get_some_name());
407         ...
408
409 Please try to avoid passing function return values to if- or
410 while-conditions. The reason for this is better handling of code under a
411 debugger.
412
413 Good example:
414
415         x = malloc(sizeof(short)*10);
416         if (x == NULL) {
417                 fprintf(stderr, "Unable to alloc memory!\n");
418         }
419
420 Bad example:
421
422         if ((x = malloc(sizeof(short)*10)) == NULL ) {
423                 fprintf(stderr, "Unable to alloc memory!\n");
424         }
425
426 There are exceptions to this rule. One example is walking a data structure in
427 an iterator style:
428
429         while ((opt = poptGetNextOpt(pc)) != -1) {
430                    ... do something with opt ...
431         }
432
433 But in general, please try to avoid this pattern.
434
435
436 Control-Flow changing macros
437 ----------------------------
438
439 Macros like NT_STATUS_NOT_OK_RETURN that change control flow
440 (return/goto/etc) from within the macro are considered bad, because
441 they look like function calls that never change control flow. Please
442 do not use them in new code.
443
444 The only exception is the test code that depends repeated use of calls
445 like CHECK_STATUS, CHECK_VAL and others.
446
447
448 Error and out logic
449 -------------------
450
451 Don't do this:
452
453         frame = talloc_stackframe();
454
455         if (ret == LDB_SUCCESS) {
456                 if (result->count == 0) {
457                         ret = LDB_ERR_NO_SUCH_OBJECT;
458                 } else {
459                         struct ldb_message *match =
460                                 get_best_match(dn, result);
461                         if (match == NULL) {
462                                 TALLOC_FREE(frame);
463                                 return LDB_ERR_OPERATIONS_ERROR;
464                         }
465                         *msg = talloc_move(mem_ctx, &match);
466                 }
467         }
468
469         TALLOC_FREE(frame);
470         return ret;
471
472 It should be:
473
474         frame = talloc_stackframe();
475
476         if (ret != LDB_SUCCESS) {
477                 TALLOC_FREE(frame);
478                 return ret;
479         }
480
481         if (result->count == 0) {
482                 TALLOC_FREE(frame);
483                 return LDB_ERR_NO_SUCH_OBJECT;
484         }
485
486         match = get_best_match(dn, result);
487         if (match == NULL) {
488                 TALLOC_FREE(frame);
489                 return LDB_ERR_OPERATIONS_ERROR;
490         }
491
492         *msg = talloc_move(mem_ctx, &match);
493         TALLOC_FREE(frame);
494         return LDB_SUCCESS;
495
496
497 DEBUG statements
498 ----------------
499
500 Use these following macros instead of DEBUG:
501
502 DBG_ERR log level 0             error conditions
503 DBG_WARNING     log level 1             warning conditions
504 DBG_NOTICE      log level 3             normal, but significant, condition
505 DBG_INFO        log level 5             informational message
506 DBG_DEBUG       log level 10            debug-level message
507
508 Example usage:
509
510 DBG_ERR("Memory allocation failed\n");
511 DBG_DEBUG("Received %d bytes\n", count);
512
513 The messages from these macros are automatically prefixed with the
514 function name.