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:
8 https://www.kernel.org/doc/Documentation/CodingStyle
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:
14 https://www.kernel.org/pub/linux/kernel/COPYING
16 Coding style is all about readability and maintainability using commonly
17 available tools. OpenSSL coding style is simple. Avoid tricky expressions.
20 Chapter 1: Indentation
22 Indentation is four space characters. Do not use the tab character.
24 Pre-processor directives use one space for indents:
33 Chapter 2: Breaking long lines and strings
35 Don't put multiple statements, or assignments, on a single line.
37 if (condition) do_this();
38 do_something_everytime();
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.
49 Chapter 3: Placing Braces and Spaces
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:
61 This applies to all non-function statement blocks (if, switch, for,
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.
85 There is one special case, however. Functions have the
86 opening brace at the beginning of the next line:
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:
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.
116 Do not unnecessarily use braces around a single statement:
128 If one of the branches is a compound statement, then use braces on both parts:
137 Nested compound statements should often have braces for clarity, particularly
138 to avoid the dangling-else problem:
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:
154 if, switch, case, for, do, while, return
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
162 SOMETYPE *p = OPENSSL_malloc(sizeof(*p) * num_of_elements);
165 Do not add spaces around the inside of parenthesized expressions.
166 This example is wrong:
168 s = sizeof( struct file );
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:
173 char *openssl_banner;
174 unsigned long long memparse(char *ptr, char **retptr);
175 char *match_strdup(substring_t *s);
177 Use one space on either side of binary and ternary operators,
178 such as this partial list:
180 = + - < > * / % | & ^ <= >= == != ? : +=
182 Do not put a space after unary operators:
186 Do not put a space before the postfix increment and decrement unary
187 operators or after the prefix increment and decrement unary operators:
192 Do not put a space around the '.' and "->" structure member operators:
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.
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.
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.
214 Except when otherwise required, avoid mixed-case names.
216 Do not encode the type into a name (so-called Hungarian notation).
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().
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.
229 If you are afraid that someone might mix up your local variable names,
230 perhaps the function is too long; see Chapter 6.
235 OpenSSL uses typedef's extensively. For structures, they are all uppercase
236 and are usually declared like this:
238 typedef struct name_st NAME;
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.
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
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.
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.
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.
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.
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.
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
290 In source files, separate functions with one blank line.
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
299 Chapter 7: Centralized exiting of functions
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
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 ;)
317 char *buffer = OPENSSL_malloc(SIZE);
331 OPENSSL_free(buffer);
335 Chapter 8: Commenting
337 Use the classic "/* ... */" comment markers. Don't use "// ..." markers.
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.
344 The preferred style for long (multi-line) comments is:
347 * This is the preferred style for multi-line
348 * comments in the OpenSSL source code.
349 * Please use it consistently.
351 * Description: A column of asterisks on the left side,
352 * with beginning and ending almost-blank lines.
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.
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.
373 Chapter 12: Macros and Enums
375 Names of macros defining constants and labels in enums are in uppercase:
377 #define CONSTANT 0x12345
379 Enums are preferred when defining several related constants.
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.
385 Macros with multiple statements should be enclosed in a do - while block:
387 #define macrofun(a, b, c) \
393 Do not write macros that affect control flow:
401 Do not write macros that depend on having a local variable with a magic name:
403 #define FOO(val) bar(index, val)
405 It is confusing to the reader and is prone to breakage from seemingly
408 Do not write macros that are l-values:
412 This will cause problems if, e.g., FOO becomes an inline function.
414 Be careful of precedence. Macros defining constants using expressions
415 must enclose the expression in parentheses:
417 #define CONSTANT 0x4000
418 #define CONSTEXP (CONSTANT | 3)
420 Beware of similar issues with macros using parameters. The GNU cpp manual
421 deals with macros exhaustively.
427 Chapter 14: Allocating memory
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.
437 Chapter 16: Function return values and names
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:
446 Sometimes an additional value is used:
448 -1: something bad (e.g., internal error or memory allocation failure)
450 Other APIs use the following pattern:
452 >= 1: success, with value returning additional information
453 <= 0: failure with return value indicating why things failed
455 Sometimes a return value of -1 can mean "should retry" (e.g., BIO, SSL, et al).
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.
467 Chapter 18: Editor modelines
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:
479 compile-command: "gcc -DMAGIC_DEBUG_FLAG foo.c"
483 Vim interprets markers that look like this:
485 /* vim:set sw=8 noet */
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.
494 Chapter 19: Processor-specific code
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.
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.
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:
514 asm ("magic %reg1, #42\n\t"
515 "more_magic %reg2, %reg3"
516 : /* outputs */ : /* inputs */ : /* clobbers */);
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.
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.
535 Chapter 20: Portability
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.
543 Chapter 21: Miscellaneous
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:
548 if (!(p = BN_new())) ...
549 if (!strcmp(a, "FOO")) ...
553 if ((p = BN_new()) == NULL)...
554 if (strcmp(a, "FOO") == 0) ...
557 Appendix A: References
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/
565 The Practice of Programming
566 by Brian W. Kernighan and Rob Pike.
567 Addison-Wesley, Inc., 1999.
569 URL: http://cm.bell-labs.com/cm/cs/tpop/
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/
574 WG14 is the international standardization working group for the programming
575 language C, URL: http://www.open-std.org/JTC1/SC22/WG14/