chiark / gitweb /
pager: port fallback pager to use copy_bytes()
[elogind.git] / CODING_STYLE
1 - 8ch indent, no tabs, except for files in man/ which are 2ch indent,
2   and still no tabs
3
4 - We prefer /* comments */ over // comments, please. This is not C++, after
5   all. (Yes we know that C99 supports both kinds of comments, but still,
6   please!)
7
8 - Don't break code lines too eagerly. We do *not* force line breaks at
9   80ch, all of today's screens should be much larger than that. But
10   then again, don't overdo it, ~140ch should be enough really.
11
12 - Variables and functions *must* be static, unless they have a
13   prototype, and are supposed to be exported.
14
15 - structs in MixedCase (with exceptions, such as public API structs),
16   variables + functions in lower_case.
17
18 - The destructors always unregister the object from the next bigger
19   object, not the other way around
20
21 - To minimize strict aliasing violations, we prefer unions over casting
22
23 - For robustness reasons, destructors should be able to destruct
24   half-initialized objects, too
25
26 - Error codes are returned as negative Exxx. e.g. return -EINVAL. There
27   are some exceptions: for constructors, it is OK to return NULL on
28   OOM. For lookup functions, NULL is fine too for "not found".
29
30   Be strict with this. When you write a function that can fail due to
31   more than one cause, it *really* should have "int" as return value
32   for the error code.
33
34 - Do not bother with error checking whether writing to stdout/stderr
35   worked.
36
37 - Do not log errors from "library" code, only do so from "main
38   program" code. (With one exception: it is OK to log with DEBUG level
39   from any code, with the exception of maybe inner loops).
40
41 - Always check OOM. There is no excuse. In program code, you can use
42   "log_oom()" for then printing a short message, but not in "library" code.
43
44 - Do not issue NSS requests (that includes user name and host name
45   lookups) from PID 1 as this might trigger deadlocks when those
46   lookups involve synchronously talking to services that we would need
47   to start up
48
49 - Do not synchronously talk to any other service from PID 1, due to
50   risk of deadlocks
51
52 - Avoid fixed-size string buffers, unless you really know the maximum
53   size and that maximum size is small. They are a source of errors,
54   since they possibly result in truncated strings. It is often nicer
55   to use dynamic memory, alloca() or VLAs. If you do allocate fixed-size
56   strings on the stack, then it is probably only OK if you either
57   use a maximum size such as LINE_MAX, or count in detail the maximum
58   size a string can have. (DECIMAL_STR_MAX and DECIMAL_STR_WIDTH
59   macros are your friends for this!)
60
61   Or in other words, if you use "char buf[256]" then you are likely
62   doing something wrong!
63
64 - Stay uniform. For example, always use "usec_t" for time
65   values. Do not mix usec and msec, and usec and whatnot.
66
67 - Make use of _cleanup_free_ and friends. It makes your code much
68   nicer to read!
69
70 - Be exceptionally careful when formatting and parsing floating point
71   numbers. Their syntax is locale dependent (i.e. "5.000" in en_US is
72   generally understood as 5, while on de_DE as 5000.).
73
74 - Try to use this:
75
76       void foo() {
77       }
78
79   instead of this:
80
81       void foo()
82       {
83       }
84
85   But it is OK if you do not.
86
87 - Single-line "if" blocks should not be enclosed in {}. Use this:
88
89   if (foobar)
90           waldo();
91
92   instead of this:
93
94   if (foobar) {
95           waldo();
96   }
97
98 - Do not write "foo ()", write "foo()".
99
100 - Please use streq() and strneq() instead of strcmp(), strncmp() where applicable.
101
102 - Please do not allocate variables on the stack in the middle of code,
103   even if C99 allows it. Wrong:
104
105   {
106           a = 5;
107           int b;
108           b = a;
109   }
110
111   Right:
112
113   {
114           int b;
115           a = 5;
116           b = a;
117   }
118
119 - Unless you allocate an array, "double" is always the better choice
120   than "float". Processors speak "double" natively anyway, so this is
121   no speed benefit, and on calls like printf() "float"s get promoted
122   to "double"s anyway, so there is no point.
123
124 - Do not mix function invocations with variable definitions in one
125   line. Wrong:
126
127   {
128           int a = foobar();
129           uint64_t x = 7;
130   }
131
132   Right:
133
134   {
135           int a;
136           uint64_t x = 7;
137
138           a = foobar();
139   }
140
141 - Use "goto" for cleaning up, and only use it for that. i.e. you may
142   only jump to the end of a function, and little else. Never jump
143   backwards!
144
145 - Think about the types you use. If a value cannot sensibly be
146   negative, do not use "int", but use "unsigned".
147
148 - Do not use types like "short". They *never* make sense. Use ints,
149   longs, long longs, all in unsigned+signed fashion, and the fixed
150   size types uint32_t and so on, as well as size_t, but nothing
151   else. Do not use kernel types like u32 and so on, leave that to the
152   kernel.
153
154 - Public API calls (i.e. functions exported by our shared libraries)
155   must be marked "_public_" and need to be prefixed with "sd_". No
156   other functions should be prefixed like that.
157
158 - In public API calls, you *must* validate all your input arguments for
159   programming error with assert_return() and return a sensible return
160   code. In all other calls, it is recommended to check for programming
161   errors with a more brutal assert(). We are more forgiving to public
162   users then for ourselves! Note that assert() and assert_return()
163   really only should be used for detecting programming errors, not for
164   runtime errors. assert() and assert_return() by usage of _likely_()
165   inform the compiler that he should not expect these checks to fail,
166   and they inform fellow programmers about the expected validity and
167   range of parameters.
168
169 - Never use strtol(), atoi() and similar calls. Use safe_atoli(),
170   safe_atou32() and suchlike instead. They are much nicer to use in
171   most cases and correctly check for parsing errors.
172
173 - For every function you add, think about whether it is a "logging"
174   function or a "non-logging" function. "Logging" functions do logging
175   on their own, "non-logging" function never log on their own and
176   expect their callers to log. All functions in "library" code,
177   i.e. in src/shared/ and suchlike must be "non-logging". Every time a
178   "logging" function calls a "non-logging" function, it should log
179   about the resulting errors. If a "logging" function calls another
180   "logging" function, then it should not generate log messages, so
181   that log messages are not generated twice for the same errors.
182
183 - Avoid static variables, except for caches and very few other
184   cases. Think about thread-safety! While most of our code is never
185   used in threaded environments, at least the library code should make
186   sure it works correctly in them. Instead of doing a lot of locking
187   for that, we tend to prefer using TLS to do per-thread caching (which
188   only works for small, fixed-size cache objects), or we disable
189   caching for any thread that is not the main thread. Use
190   is_main_thread() to detect whether the calling thread is the main
191   thread.
192
193 - Command line option parsing:
194   - Do not print full help() on error, be specific about the error.
195   - Do not print messages to stdout on error.
196   - Do not POSIX_ME_HARDER unless necessary, i.e. avoid "+" in option string.
197
198 - Do not write functions that clobber call-by-reference variables on
199   failure. Use temporary variables for these cases and change the
200   passed in variables only on success.
201
202 - When you allocate a file descriptor, it should be made O_CLOEXEC
203   right from the beginning, as none of our files should leak to forked
204   binaries by default. Hence, whenever you open a file, O_CLOEXEC must
205   be specified, right from the beginning. This also applies to
206   sockets. Effectively this means that all invocations to:
207
208   a) open() must get O_CLOEXEC passed
209   b) socket() and socketpair() must get SOCK_CLOEXEC passed
210   c) recvmsg() must get MSG_CMSG_CLOEXEC set
211   d) F_DUPFD_CLOEXEC should be used instead of F_DUPFD, and so on
212
213 - We never use the POSIX version of basename() (which glibc defines it in
214   libgen.h), only the GNU version (which glibc defines in string.h).
215   The only reason to include libgen.h is because dirname()
216   is needed. Everytime you need that please immediately undefine
217   basename(), and add a comment about it, so that no code ever ends up
218   using the POSIX version!
219
220 - Use the bool type for booleans, not integers. One exception: in public
221   headers (i.e those in src/systemd/sd-*.h) use integers after all, as "bool"
222   is C99 and in our public APIs we try to stick to C89 (with a few extension).
223
224 - When you invoke certain calls like unlink(), or mkdir_p() and you
225   know it is safe to ignore the error it might return (because a later
226   call would detect the failure anyway, or because the error is in an
227   error path and you thus couldn't do anything about it anyway), then
228   make this clear by casting the invocation explicitly to (void). Code
229   checks like Coverity understand that, and will not complain about
230   ignored error codes. Hence, please use this:
231
232       (void) unlink("/foo/bar/baz");
233
234   instead of just this:
235
236       unlink("/foo/bar/baz");
237
238 - Don't invoke exit(), ever. It is not replacement for proper error
239   handling. Please escalate errors up your call chain, and use normal
240   "return" to exit from the main function of a process. If you
241   fork()ed off a child process, please use _exit() instead of exit(),
242   so that the exit handlers are not run.
243
244 - Please never use dup(). Use fcntl(fd, F_DUPFD_CLOEXEC, 3)
245   instead. For two reason: first, you want O_CLOEXEC set on the new fd
246   (see above). Second, dup() will happily duplicate your fd as 0, 1,
247   2, i.e. stdin, stdout, stderr, should those fds be closed. Given the
248   special semantics of those fds, it's probably a good idea to avoid
249   them. F_DUPFD_CLOEXEC with "3" as parameter avoids them.
250
251 - When you define a destructor or unref() call for an object, please
252   accept a NULL object and simply treat this as NOP. This is similar
253   to how libc free() works, which accepts NULL pointers and becomes a
254   NOP for them. By following this scheme a lot of if checks can be
255   removed before invoking your destructor, which makes the code
256   substantially more readable and robust.
257
258 - Related to this: when you define a destructor or unref() call for an
259   object, please make it return the same type it takes and always
260   return NULL from it. This allows writing code like this:
261
262             p = foobar_unref(p);
263
264   which will always work regardless if p is initialized or not, and
265   guarantees that p is NULL afterwards, all in just one line.
266
267 - Use alloca(), but never forget that it is not OK to invoke alloca()
268   within a loop or within function call parameters. alloca() memory is
269   released at the end of a function, and not at the end of a {}
270   block. Thus, if you invoke it in a loop, you keep increasing the
271   stack pointer without ever releasing memory again. (VLAs have better
272   behaviour in this case, so consider using them as an alternative.)
273   Regarding not using alloca() within function parameters, see the
274   BUGS section of the alloca(3) man page.
275
276 - Use memzero() or even better zero() instead of memset(..., 0, ...)
277
278 - Instead of using memzero()/memset() to initialize structs allocated
279   on the stack, please try to use c99 structure initializers. It's
280   short, prettier and actually even faster at execution. Hence:
281
282           struct foobar t = {
283                   .foo = 7,
284                   .bar = "bazz",
285           };
286
287   instead of:
288
289           struct foobar t;
290           zero(t);
291           t.foo = 7;
292           t.bar = "bazz";
293
294 - When returning a return code from main(), please preferably use
295   EXIT_FAILURE and EXIT_SUCCESS as defined by libc.
296
297 - The order in which header files are included doesn't matter too
298   much. However, please try to include the headers of external
299   libraries first (these are all headers enclosed in <>), followed by
300   the headers of our own public headers (these are all headers
301   starting with "sd-"), internal utility libraries from src/shared/,
302   followed by the headers of the specific component. Or in other
303   words:
304
305           #include <stdio.h>
306           #include "sd-daemon.h"
307           #include "util.h"
308           #include "frobnicator.h"
309
310   Where stdio.h is a public glibc API, sd-daemon.h is a public API of
311   our own, util.h is a utility library header from src/shared, and
312   frobnicator.h is an placeholder name for any systemd component. The
313   benefit of following this ordering is that more local definitions
314   are always defined after more global ones. Thus, our local
315   definitions will never "leak" into the global header files, possibly
316   altering their effect due to #ifdeffery.
317
318 - To implement an endless loop, use "for (;;)" rather than "while
319   (1)". The latter is a bit ugly anyway, since you probably really
320   meant "while (true)"... To avoid the discussion what the right
321   always-true expression for an infinite while() loop is our
322   recommendation is to simply write it without any such expression by
323   using "for (;;)".