]> git.ipfire.org Git - thirdparty/systemd.git/blame - CODING_STYLE
coredump: make sure we vacuum by default
[thirdparty/systemd.git] / CODING_STYLE
CommitLineData
798d3a52
ZJS
1- 8ch indent, no tabs, except for files in man/ which are 2ch indent,
2 and still no tabs
60918275 3
2708526c
LP
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
3fdbc820
LP
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
c170f3a4 12- Variables and functions *must* be static, unless they have a
f168c273 13 prototype, and are supposed to be exported.
60918275 14
d3a48513
LP
15- structs in MixedCase (with exceptions, such as public API structs),
16 variables + functions in lower_case.
c170f3a4
LP
17
18- The destructors always unregister the object from the next bigger
60918275
LP
19 object, not the other way around
20
8d0e0ddd 21- To minimize strict aliasing violations, we prefer unions over casting
60918275 22
8d0e0ddd 23- For robustness reasons, destructors should be able to destruct
60918275
LP
24 half-initialized objects, too
25
61f33134 26- Error codes are returned as negative Exxx. e.g. return -EINVAL. There
8d0e0ddd
JE
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".
c170f3a4
LP
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
8e5edf8d 34- Do not bother with error checking whether writing to stdout/stderr
d3a48513 35 worked.
c170f3a4
LP
36
37- Do not log errors from "library" code, only do so from "main
8e5edf8d 38 program" code. (With one exception: it is OK to log with DEBUG level
d3a48513 39 from any code, with the exception of maybe inner loops).
c170f3a4 40
8e5edf8d 41- Always check OOM. There is no excuse. In program code, you can use
d3a48513 42 "log_oom()" for then printing a short message, but not in "library" code.
debf93a4
LP
43
44- Do not issue NSS requests (that includes user name and host name
d3a48513
LP
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
debf93a4 48
8e5edf8d 49- Do not synchronously talk to any other service from PID 1, due to
d3a48513 50 risk of deadlocks
c170f3a4 51
45df8656 52- Avoid fixed-size string buffers, unless you really know the maximum
c170f3a4 53 size and that maximum size is small. They are a source of errors,
45df8656
JE
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
8e5edf8d 56 strings on the stack, then it is probably only OK if you either
d3a48513
LP
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!
c170f3a4
LP
63
64- Stay uniform. For example, always use "usec_t" for time
61f33134 65 values. Do not mix usec and msec, and usec and whatnot.
c170f3a4
LP
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
8e5edf8d 85 But it is OK if you do not.
c170f3a4 86
61f33134
LP
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
8e5edf8d 98- Do not write "foo ()", write "foo()".
c170f3a4
LP
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
45df8656 121 no speed benefit, and on calls like printf() "float"s get promoted
c170f3a4
LP
122 to "double"s anyway, so there is no point.
123
42706f47
LP
124- Do not mix function invocations with variable definitions in one
125 line. Wrong:
c170f3a4
LP
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
d3a48513
LP
142 only jump to the end of a function, and little else. Never jump
143 backwards!
c170f3a4
LP
144
145- Think about the types you use. If a value cannot sensibly be
8e5edf8d 146 negative, do not use "int", but use "unsigned".
c170f3a4 147
8e5edf8d 148- Do not use types like "short". They *never* make sense. Use ints,
c170f3a4 149 longs, long longs, all in unsigned+signed fashion, and the fixed
8d0e0ddd 150 size types uint32_t and so on, as well as size_t, but nothing else.
d3a48513
LP
151
152- Public API calls (i.e. functions exported by our shared libraries)
153 must be marked "_public_" and need to be prefixed with "sd_". No
154 other functions should be prefixed like that.
155
8d0e0ddd 156- In public API calls, you *must* validate all your input arguments for
d3a48513 157 programming error with assert_return() and return a sensible return
8d0e0ddd 158 code. In all other calls, it is recommended to check for programming
d3a48513
LP
159 errors with a more brutal assert(). We are more forgiving to public
160 users then for ourselves! Note that assert() and assert_return()
161 really only should be used for detecting programming errors, not for
162 runtime errors. assert() and assert_return() by usage of _likely_()
8e5edf8d 163 inform the compiler that he should not expect these checks to fail,
d3a48513
LP
164 and they inform fellow programmers about the expected validity and
165 range of parameters.
166
167- Never use strtol(), atoi() and similar calls. Use safe_atoli(),
168 safe_atou32() and suchlike instead. They are much nicer to use in
169 most cases and correctly check for parsing errors.
170
171- For every function you add, think about whether it is a "logging"
172 function or a "non-logging" function. "Logging" functions do logging
173 on their own, "non-logging" function never log on their own and
174 expect their callers to log. All functions in "library" code,
06b643e7 175 i.e. in src/shared/ and suchlike must be "non-logging". Every time a
8d0e0ddd 176 "logging" function calls a "non-logging" function, it should log
d3a48513
LP
177 about the resulting errors. If a "logging" function calls another
178 "logging" function, then it should not generate log messages, so
179 that log messages are not generated twice for the same errors.
180
181- Avoid static variables, except for caches and very few other
182 cases. Think about thread-safety! While most of our code is never
8d0e0ddd 183 used in threaded environments, at least the library code should make
d3a48513 184 sure it works correctly in them. Instead of doing a lot of locking
8d0e0ddd 185 for that, we tend to prefer using TLS to do per-thread caching (which
d3a48513
LP
186 only works for small, fixed-size cache objects), or we disable
187 caching for any thread that is not the main thread. Use
188 is_main_thread() to detect whether the calling thread is the main
189 thread.
601185b4 190
7f8bf08f 191- Command line option parsing:
601185b4
ZJS
192 - Do not print full help() on error, be specific about the error.
193 - Do not print messages to stdout on error.
194 - Do not POSIX_ME_HARDER unless necessary, i.e. avoid "+" in option string.
7f8bf08f
LP
195
196- Do not write functions that clobber call-by-reference variables on
197 failure. Use temporary variables for these cases and change the
198 passed in variables only on success.
dd4540da
LP
199
200- When you allocate a file descriptor, it should be made O_CLOEXEC
201 right from the beginning, as none of our files should leak to forked
202 binaries by default. Hence, whenever you open a file, O_CLOEXEC must
699eee62
LP
203 be specified, right from the beginning. This also applies to
204 sockets. Effectively this means that all invocations to:
205
206 a) open() must get O_CLOEXEC passed
207 b) socket() and socketpair() must get SOCK_CLOEXEC passed
208 c) recvmsg() must get MSG_CMSG_CLOEXEC set
209 d) F_DUPFD_CLOEXEC should be used instead of F_DUPFD, and so on
eef46c37
LP
210
211- We never use the XDG version of basename(). glibc defines it in
212 libgen.h. The only reason to include that file is because dirname()
213 is needed. Everytime you need that please immediately undefine
214 basename(), and add a comment about it, so that no code ever ends up
215 using the XDG version!
ddb64d82
LP
216
217- Use the bool type for booleans, not integers. One exception: in public
218 headers (i.e those in src/systemd/sd-*.h) use integers after all, as "bool"
219 is C99 and in our public APIs we try to stick to C89 (with a few extension).
918315e4
LP
220
221- When you invoke certain calls like unlink(), or mkdir_p() and you
222 know it is safe to ignore the error it might return (because a later
223 call would detect the failure anyway, or because the error is in an
224 error path and you thus couldn't do anything about it anyway), then
225 make this clear by casting the invocation explicitly to (void). Code
226 checks like Coverity understand that, and will not complain about
227 ignored error codes. Hence, please use this:
228
229 (void) unlink("/foo/bar/baz");
230
231 instead of just this:
232
233 unlink("/foo/bar/baz");
3dbafa39
LP
234
235- Don't invoke exit(), ever. It is not replacement for proper error
236 handling. Please escalate errors up your call chain, and use normal
237 "return" to exit from the main function of a process. If you
238 fork()ed off a child process, please use _exit() instead of exit(),
239 so that the exit handlers are not run.
9ff3e22a
LP
240
241- Please never use dup(). Use fcntl(fd, F_DUPFD_CLOEXEC, 3)
242 instead. For two reason: first, you want O_CLOEXEC set on the new fd
243 (see above). Second, dup() will happily duplicate your fd as 0, 1,
244 2, i.e. stdin, stdout, stderr, should those fds be closed. Given the
245 special semantics of those fds, it's probably a good idea to avoid
246 them. F_DUPFD_CLOEXEC with "3" as parameter avoids them.
ba780c11
LP
247
248- When you define a destructor or unref() call for an object, please
249 accept a NULL object and simply treat this as NOP. This is similar
250 to how libc free() works, which accepts NULL pointers and becomes a
251 NOP for them. By following this scheme a lot of if checks can be
252 removed before invoking your destructor, which makes the code
253 substantially more readable and robust.
254
255- Related to this: when you define a destructor or unref() call for an
256 object, please make it return the same type it takes and always
257 return NULL from it. This allows writing code like this:
258
259 p = foobar_unref(p);
260
261 which will always work regardless if p is initialized or not, and
262 guarantees that p is NULL afterwards, all in just one line.
42706f47
LP
263
264- Use alloca(), but never forget that it is not OK to invoke alloca()
265 within a loop or within function call parameters. alloca() memory is
266 released at the end of a function, and not at the end of a {}
267 block. Thus, if you invoke it in a loop, you keep increasing the
268 stack pointer without ever releasing memory again. (VLAs have better
269 behaviour in this case, so consider using them as an alternative.)
270 Regarding not using alloca() within function parameters, see the
271 BUGS section of the alloca(3) man page.