Remove CLA mention; it's in CONTRIBUTING now.
[openssl-web.git] / policies / codingstyle.txt
1
2                 OpenSSL coding style
3                 Jan 12 2015
4
5 This document describes the coding style for the OpenSSL project. It is
6 derived from the Linux kernel coding style, which can be found at:
7
8     https://www.kernel.org/doc/Documentation/CodingStyle
9
10 This guide is not distributed as part of OpenSSL itself. Since it is
11 derived from the Linux Kernel Coding Style, it is distributed under the
12 terms of the kernel license, available here:
13
14     https://www.kernel.org/pub/linux/kernel/COPYING
15
16 Coding style is all about readability and maintainability using commonly
17 available tools. OpenSSL coding style is simple. Avoid tricky expressions.
18
19
20                 Chapter 1: Indentation
21
22 Indentation is four space characters. Do not use the tab character.
23
24 Pre-processor directives use one space for indents:
25
26     #if
27     # define
28     #else
29     # define
30     #endif
31
32
33                 Chapter 2: Breaking long lines and strings
34
35 Don't put multiple statements, or assignments, on a single line.
36
37     if (condition) do_this();
38     do_something_everytime();
39
40 The limit on the length of lines is 80 columns. Statements longer
41 than 80 columns must be broken into sensible chunks, unless exceeding
42 80 columns significantly increases readability and does not hide
43 information. Descendants are always substantially shorter than the parent
44 and are placed substantially to the right. The same applies to function
45 headers with a long argument list. Never break user-visible strings,
46 however, because that breaks the ability to grep for them.
47
48
49                 Chapter 3: Placing Braces and Spaces
50
51 The other issue that always comes up in C styling is the placement
52 of braces. Unlike the indent size, there are few technical reasons to
53 choose one placement strategy over the other, but the preferred way,
54 following Kernighan and Ritchie, is to put the opening brace last on the
55 line, and the closing brace first:
56
57     if (x is true) {
58         we do y
59     }
60
61 This applies to all non-function statement blocks (if, switch, for,
62 while, do):
63
64     switch (suffix) {
65     case 'G':
66     case 'g':
67         mem <<= 30;
68         break;
69     case 'M':
70     case 'm':
71         mem <<= 20;
72         break;
73     case 'K':
74     case 'k':
75         mem <<= 10;
76         /* fall through */
77     default:
78         break;
79     }
80
81 Note, from the above example, that the way to indent a switch statement
82 is to align the switch and its subordinate case labels in the same column
83 instead of "double-indenting" the case bodies.
84
85 There is one special case, however. Functions have the
86 opening brace at the beginning of the next line:
87
88     int function(int x)
89     {
90         body of function
91     }
92
93 Note that the closing brace is empty on a line of its own, EXCEPT in the
94 cases where it is followed by a continuation of the same statement, such
95 as a "while" in a do-statement or an "else" in an if-statement, like this:
96
97     do {
98         ...
99     } while (condition);
100
101 and
102
103     if (x == y) {
104         ...
105     } else if (x > y) {
106         ...
107     } else {
108         ...
109     }
110
111 In addition to being consistent with K&R, note that that this brace-placement
112 also minimizes the number of empty (or almost empty) lines. Since the
113 supply of new-lines on your screen is not a renewable resource (think
114 25-line terminal screens here), you have more empty lines to put comments on.
115
116 Do not unnecessarily use braces around a single statement:
117
118     if (condition)
119         action();
120
121 and
122
123     if (condition)
124         do_this();
125     else
126         do_that();
127
128 If one of the branches is a compound statement, then use braces on both parts:
129
130     if (condition) {
131         do_this();
132         do_that();
133     } else {
134         otherwise();
135     }
136
137 Nested compound statements should often have braces for clarity, particularly
138 to avoid the dangling-else problem:
139
140     if (condition) {
141         do_this();
142         if (anothertest)
143             do_that();
144     } else {
145         otherwise();
146     }
147
148
149                 Chapter 3.1:  Spaces
150
151 OpenSSL style for use of spaces depends (mostly) on whether the name is
152 a function or keyword. Use a space after most keywords:
153
154     if, switch, case, for, do, while, return
155
156 Do not use a space after sizeof, typeof, alignof, or __attribute__.
157 They look somewhat like functions and should have parentheses
158 in OpenSSL, although they are not required by the language. For sizeof,
159 use a variable when at all possible, to ensure that type changes are
160 properly reflected:
161
162     SOMETYPE *p = OPENSSL_malloc(sizeof(*p) * num_of_elements);
163
164
165 Do not add spaces around the inside of parenthesized expressions.
166 This example is wrong:
167
168     s = sizeof( struct file );
169
170 When declaring pointer data or a function that returns a pointer type, the
171 the asterisk goes next to the data or function name, and not the type:
172
173     char *openssl_banner;
174     unsigned long long memparse(char *ptr, char **retptr);
175     char *match_strdup(substring_t *s);
176
177 Use one space on either side of binary and ternary operators,
178 such as this partial list:
179
180     =  +  -  <  >  *  /  %  |  &  ^  <=  >=  ==  !=  ?  : +=
181
182 Do not put a space after unary operators:
183
184     &  *  +  -  ~  !  defined
185
186 Do not put a space before the postfix increment and decrement unary
187 operators or after the prefix increment and decrement unary operators:
188
189     foo++
190     --bar
191
192 Do not put a space around the '.' and "->" structure member operators:
193     foo.bar
194     foo->bar
195
196 Do not leave trailing whitespace at the ends of lines. Some editors with
197 "smart" indentation will insert whitespace at the beginning of new lines
198 as appropriate, so you can start typing the next line of code right away.
199 But they may not remove that whitespace if you leave a blank line, however,
200 and you end up with lines containing trailing, or nothing but, whitespace.
201
202 Git will warn you about patches that introduce trailing whitespace, and
203 can optionally strip the trailing whitespace; however, if applying
204 a series of patches, this may make later patches in the series fail by
205 changing their context lines.
206
207
208                 Chapter 4: Naming
209
210 C is a Spartan language, and so should your naming be. Do not use long
211 names like ThisVariableIsATemporaryCounter. Use a name like tmp, which
212 is much easier to write, and not more difficult to understand.
213
214 Except when otherwise required, avoid mixed-case names.
215
216 Do not encode the type into a name (so-called Hungarian notation).
217
218 Global variables (to be used only if you REALLY need them) need to
219 have descriptive names, as do global functions. If you have a function
220 that counts the number of active users, you should call that
221 count_active_users() or similar, you should NOT call it cntusr().
222
223 Local variable names should be short, and to the point. If you have
224 some random integer loop counter, it should probably be called i.
225 Calling it loop_counter is non-productive, if there is no chance of it
226 being mis-understood. Similarly, tmp can be just about any type of
227 variable that is used to hold a temporary value.
228
229 If you are afraid that someone might mix up your local variable names,
230 perhaps the function is too long; see Chapter 6.
231
232
233                 Chapter 5: Typedefs
234
235 OpenSSL uses typedef's extensively. For structures, they are all uppercase
236 and are usually declared like this:
237
238     typedef struct name_st NAME;
239
240 For examples, look in ossl_type.h, but note that there are many exceptions
241 such as BN_CTX. Typedef'd enum is used much less often and there is no
242 convention, so consider not using a typedef. When doing that, the enum
243 name should be lowercase and the values (mostly) uppercase.
244
245 The ASN.1 structures are an exception to this. The rationale is that if
246 a structure (and its fields) is already defined in a standard it's more
247 convenient to use a similar name. For example, in the CMS code, a CMS_
248 prefix is used so ContentInfo becomes CMS_ContentInfo, RecipientInfo
249 becomes CMS_RecipientInfo etc. Some older code uses an all uppercase
250 name instead. For example, RecipientInfo for the PKCS#7 code uses
251 PKCS7_RECIP_INFO.
252
253 Be careful about common names which might cause conflicts. For example,
254 Windows headers use X509 and X590_NAME. Consider using a prefix, as with
255 CMS_ContentInfo, if the name is common or generic. Of course, you often
256 don't find out until the code is ported to other platforms.
257
258 A final word on struct's. OpenSSL has has historically made all struct
259 definitions public; this has caused problems with maintaining binary
260 compatibility and adding features. Our stated direction is to have struct's
261 be opaque and only expose pointers in the API. The actual struct definition
262 should be defined in a local header file that is not exported.
263
264
265                 Chapter 6: Functions
266
267 Ideally, functions should be short and sweet, and do just one thing.
268 A rule of thumb is that they should fit on one or two screenfuls of text
269 (25 lines as we all know), and do one thing and do that well.
270
271 The maximum length of a function is often inversely proportional to the
272 complexity and indentation level of that function. So, if you have a
273 conceptually simple function that is just one long (but simple) switch
274 statement, where you have to do lots of small things for a lot of different
275 cases, it's OK to have a longer function.
276
277 If you have a complex function, however, consider using helper functions
278 with descriptive names. You can ask the compiler to in-line them if you
279 think it's performance-critical, and it will probably do a better job of
280 it than you would have done.
281
282 Another measure of complexity is the number of local variables. If there are
283 more than five to 10, consider splitting it into smaller pieces. A human
284 brain can generally easily keep track of about seven different things;
285 anything more and it gets confused. Often things which are simple and
286 clear now are much less obvious two weeks from now, or to someone else.
287 An exception to this is the command-line applications which support many
288 options.
289
290 In source files, separate functions with one blank line.
291
292 In function prototypes, include parameter names with their data types.
293 Although this is not required by the C language, it is preferred in OpenSSL
294 because it is a simple way to add valuable information for the reader.
295 The name in the prototype declaration should match the name in the function
296 definition.
297
298
299                 Chapter 7: Centralized exiting of functions
300
301 The goto statement comes in handy when a function exits from multiple
302 locations and some common work such as cleanup has to be done. If there
303 is no cleanup needed then just return directly. The rationale for this is
304 as follows:
305
306     - Unconditional statements are easier to understand and follow
307     - It can reduce excessive control structures and nesting
308     - It avoids errors caused by failing to updated multiple exit points
309       when the code is modified
310     - It saves the compiler work to optimize redundant code away ;)
311
312 For example:
313
314     int fun(int a)
315     {
316         int result = 0;
317         char *buffer = OPENSSL_malloc(SIZE);
318
319         if (buffer == NULL)
320             return -1;
321
322         if (condition1) {
323             while (loop1) {
324                 ...
325             }
326             result = 1;
327             goto out;
328         }
329         ...
330     out:
331         OPENSSL_free(buffer);
332         return result;
333     }
334
335                 Chapter 8: Commenting
336
337 Use the classic "/* ... */" comment markers.  Don't use "// ..." markers.
338
339 Comments are good, but there is also a danger of over-commenting. NEVER try
340 to explain HOW your code works in a comment. It is much better to write
341 the code so that it is obvious, and it's a waste of time to explain badly
342 written code. You want your comments to tell WHAT your code does, not HOW.
343
344 The preferred style for long (multi-line) comments is:
345
346     /*-
347      * This is the preferred style for multi-line
348      * comments in the OpenSSL source code.
349      * Please use it consistently.
350      *
351      * Description:  A column of asterisks on the left side,
352      * with beginning and ending almost-blank lines.
353      */
354
355 Note the initial hypen to prevent indent from modifying the comment.
356 Use this if the comment has particular formatting that must be preserved.
357
358 It's also important to comment data, whether they are basic types or
359 derived types. To this end, use just one data declaration per line (no
360 commas for multiple data declarations). This leaves you room for a small
361 comment on each item, explaining its use.
362
363
364                 Chapter 9: Deleted
365
366
367                 Chapter 10: Deleted
368
369
370                 Chapter 11: Deleted
371
372
373                 Chapter 12: Macros and Enums
374
375 Names of macros defining constants and labels in enums are in uppercase:
376
377     #define CONSTANT 0x12345
378
379 Enums are preferred when defining several related constants.
380
381 Macro names should be in uppercase, but macros resembling functions may
382 be written in lower case. Generally, inline functions are preferable to
383 macros resembling functions.
384
385 Macros with multiple statements should be enclosed in a do - while block:
386
387     #define macrofun(a, b, c)   \
388         do {                    \
389             if (a == 5)         \
390                 do_this(b, c);  \
391         } while (0)
392
393 Do not write macros that affect control flow:
394
395     #define FOO(x)                 \
396         do {                       \
397             if (blah(x) < 0)       \
398                 return -EBUGGERED; \
399         } while(0)
400
401 Do not write macros that depend on having a local variable with a magic name:
402
403     #define FOO(val) bar(index, val)
404
405 It is confusing to the reader and is prone to breakage from seemingly
406 innocent changes.
407
408 Do not write macros that are l-values:
409
410     FOO(x) = y
411
412 This will cause problems if, e.g., FOO becomes an inline function.
413
414 Be careful of precedence. Macros defining constants using expressions
415 must enclose the expression in parentheses:
416
417     #define CONSTANT 0x4000
418     #define CONSTEXP (CONSTANT | 3)
419
420 Beware of similar issues with macros using parameters. The GNU cpp manual
421 deals with macros exhaustively.
422
423
424                 Chapter 13: Deleted
425
426
427                 Chapter 14: Allocating memory
428
429 OpenSSL provides the following general purpose memory allocators:
430 OPENSSL_malloc(), OPENSSL_realloc(), OPENSSL_strdup() and OPENSSL_free().
431 Please refer to the API documentation for further information about them.
432
433
434                 Chapter 15: Deleted
435
436
437                 Chapter 16: Function return values and names
438
439 Functions can return values of many different kinds, and one of the
440 most common is a value indicating whether the function succeeded or
441 failed. Usually this is:
442
443     1: success
444     0: failure
445
446 Sometimes an additional value is used:
447
448     -1: something bad (e.g., internal error or memory allocation failure)
449
450 Other APIs use the following pattern:
451
452     >= 1: success, with value returning additional information
453     <= 0: failure with return value indicating why things failed
454
455 Sometimes a return value of -1 can mean "should retry" (e.g., BIO, SSL, et al).
456
457 Functions whose return value is the actual result of a computation,
458 rather than an indication of whether the computation succeeded, are not
459 subject to these rules. Generally they indicate failure by returning some
460 out-of-range result. The simplest example is functions that return pointers;
461 they return NULL to report failure.
462
463
464                 Chapter 17:  Deleted
465
466
467                 Chapter 18:  Editor modelines
468
469 Some editors can interpret configuration information embedded in source
470 files, indicated with special markers. For example, emacs interprets
471 lines marked like this:
472
473     -*- mode: c -*-
474
475 Or like this:
476
477     /*
478     Local Variables:
479     compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
480     End:
481     */
482
483 Vim interprets markers that look like this:
484
485     /* vim:set sw=8 noet */
486
487 Do not include any of these in source files. People have their own personal
488 editor configurations, and your source files should not override them.
489 This includes markers for indentation and mode configuration. People may
490 use their own custom mode, or may have some other magic method for making
491 indentation work correctly.
492
493
494                 Chapter 19:  Processor-specific code
495
496 In OpenSSL's case the only reason to resort to processor-specific code
497 is for performance. As it still exists in a general platform-independent
498 algorithm context, it always has to be backed up by a neutral pure C one.
499 This implies certain limitations. The most common way to resolve this
500 conflict is to opt for short inline assembly function-like snippets,
501 customarily implemented as macros, so that they can be easily interchanged
502 with other platform-specific or neutral code. As with any macro, try to
503 implement it as single expression.
504
505 You may need to mark your asm statement as volatile, to prevent GCC from
506 removing it if GCC doesn't notice any side effects. You don't always need
507 to do so, though, and doing so unnecessarily can limit optimization.
508
509 When writing a single inline assembly statement containing multiple
510 instructions, put each instruction on a separate line in a separate quoted
511 string, and end each string except the last with \n\t to properly indent
512 the next instruction in the assembly output:
513
514         asm ("magic %reg1, #42\n\t"
515              "more_magic %reg2, %reg3"
516              : /* outputs */ : /* inputs */ : /* clobbers */);
517
518 Large, non-trivial assembly functions go in pure assembly modules, with
519 corresponding C prototypes defined in C. The preferred way to implement this
520 is so-called "perlasm": instead of writing real .s file, you write a perl
521 script that generates one. This allows use symbolic names for variables
522 (register as well as locals allocated on stack) that are independent on
523 specific assembler. It simplifies implementation of recurring instruction
524 sequences with regular permutation of inputs. By adhering to specific
525 coding rules, perlasm is also used to support multiple ABIs and assemblers,
526 see crypto/perlasm/x86_64-xlate.pl for an example.
527
528 Another option for processor-specific (primarily SIMD) capabilities is
529 called "compiler intrinsics." We avoid this, because it's not very much
530 less complicated than coding pure assembly, and it doesn't provide the
531 same performance guarantee across different micro-architecture. Nor is
532 it portable enough to meet our multi-platform support goals.
533
534
535                 Chapter 20:  Portability
536
537 To maximise portability the version of C defined in ISO/IEC 9899:1990
538 should be used. This is more commonly referred to as C90. ISO/IEC 9899:1999
539 (also known as C99) is not supported on some platforms that OpenSSL is
540 used on and therefore should be avoided.
541
542
543                 Chapter 21: Miscellaneous
544
545 Do not use ! to check if a pointer is NULL, or to see if a str...cmp
546 function found a match.  For example, these are wrong:
547
548     if (!(p = BN_new())) ...
549     if (!strcmp(a, "FOO")) ...
550
551 Do this instead:
552
553     if ((p = BN_new()) == NULL)...
554     if (strcmp(a, "FOO") == 0) ...
555
556
557                 Appendix A: References
558
559 The C Programming Language, Second Edition
560 by Brian W. Kernighan and Dennis M. Ritchie.
561 Prentice Hall, Inc., 1988.
562 ISBN 0-13-110362-8 (paperback), 0-13-110370-9 (hardback).
563 URL: http://cm.bell-labs.com/cm/cs/cbook/
564
565 The Practice of Programming
566 by Brian W. Kernighan and Rob Pike.
567 Addison-Wesley, Inc., 1999.
568 ISBN 0-201-61586-X.
569 URL: http://cm.bell-labs.com/cm/cs/tpop/
570
571 GNU manuals - where in compliance with K&R and this text - for cpp, gcc,
572 gcc internals and indent, all available from https://www.gnu.org/manual/
573
574 WG14 is the international standardization working group for the programming
575 language C, URL: http://www.open-std.org/JTC1/SC22/WG14/