]> git.ipfire.org Git - thirdparty/systemd.git/blob - docs/CODING_STYLE.md
CODING_STYLE: export section about exporting symbols
[thirdparty/systemd.git] / docs / CODING_STYLE.md
1 ---
2 title: Coding Style
3 ---
4
5 # Coding Style
6
7 ## Formatting
8
9 - 8ch indent, no tabs, except for files in `man/` which are 2ch indent, and
10 still no tabs, and shell scripts, which are 4ch indent, and no tabs either.
11
12 - We prefer `/* comments */` over `// comments` in code you commit,
13 please. This way `// comments` are left for developers to use for local,
14 temporary commenting of code for debug purposes (i.e. uncommittable stuff),
15 making such comments easily discernible from explanatory, documenting code
16 comments (i.e. committable stuff).
17
18 - Don't break code lines too eagerly. We do **not** force line breaks at 80ch,
19 all of today's screens should be much larger than that. But then again, don't
20 overdo it, ~109ch should be enough really. The `.editorconfig`, `.vimrc` and
21 `.dir-locals.el` files contained in the repository will set this limit up for
22 you automatically, if you let them (as well as a few other things). Please
23 note that emacs loads `.dir-locals.el` automatically, but vim needs to be
24 configured to load `.vimrc`, see that file for instructions.
25
26 - Try to write this:
27
28 ```c
29 void foo() {
30 }
31 ```
32
33 instead of this:
34
35 ```c
36 void foo()
37 {
38 }
39 ```
40
41 - Single-line `if` blocks should not be enclosed in `{}`. Write this:
42
43 ```c
44 if (foobar)
45 waldo();
46 ```
47
48 instead of this:
49
50 ```c
51 if (foobar) {
52 waldo();
53 }
54 ```
55
56 - Do not write `foo ()`, write `foo()`.
57
58 - Preferably allocate local variables on the top of the block:
59
60 ```c
61 {
62 int a, b;
63
64 a = 5;
65 b = a;
66 }
67 ```
68
69 ## Other
70
71 - structs in `PascalCase` (with exceptions, such as public API structs),
72 variables and functions in `snake_case`.
73
74 - To minimize strict aliasing violations, we prefer unions over casting.
75
76 - Do not issue NSS requests (that includes user name and host name
77 lookups) from PID 1 as this might trigger deadlocks when those
78 lookups involve synchronously talking to services that we would need
79 to start up.
80
81 - Do not synchronously talk to any other service from PID 1, due to
82 risk of deadlocks.
83
84 - Be exceptionally careful when formatting and parsing floating point
85 numbers. Their syntax is locale dependent (i.e. `5.000` in en_US is
86 generally understood as 5, while in de_DE as 5000.).
87
88 - Do not mix function invocations with variable definitions in one
89 line. Wrong:
90
91 ```c
92 {
93 int a = foobar();
94 uint64_t x = 7;
95 }
96 ```
97
98 Right:
99
100 ```c
101 {
102 int a;
103 uint64_t x = 7;
104
105 a = foobar();
106 }
107 ```
108
109 - Use `goto` for cleaning up, and only use it for that. i.e. you may
110 only jump to the end of a function, and little else. Never jump
111 backwards!
112
113 - For every function you add, think about whether it is a "logging"
114 function or a "non-logging" function. "Logging" functions do logging
115 on their own, "non-logging" function never log on their own and
116 expect their callers to log. All functions in "library" code,
117 i.e. in `src/shared/` and suchlike must be "non-logging". Every time a
118 "logging" function calls a "non-logging" function, it should log
119 about the resulting errors. If a "logging" function calls another
120 "logging" function, then it should not generate log messages, so
121 that log messages are not generated twice for the same errors.
122
123 - If possible, do a combined log & return operation:
124
125 ```c
126 r = operation(...);
127 if (r < 0)
128 return log_(error|warning|notice|...)_errno(r, "Failed to ...: %m");
129 ```
130
131 If the error value is "synthetic", i.e. it was not received from
132 the called function, use `SYNTHETIC_ERRNO` wrapper to tell the logging
133 system to not log the errno value, but still return it:
134
135 ```c
136 n = read(..., s, sizeof s);
137 if (n != sizeof s)
138 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read ...");
139 ```
140
141 - Avoid static variables, except for caches and very few other
142 cases. Think about thread-safety! While most of our code is never
143 used in threaded environments, at least the library code should make
144 sure it works correctly in them. Instead of doing a lot of locking
145 for that, we tend to prefer using TLS to do per-thread caching (which
146 only works for small, fixed-size cache objects), or we disable
147 caching for any thread that is not the main thread. Use
148 `is_main_thread()` to detect whether the calling thread is the main
149 thread.
150
151 - Do not write functions that clobber call-by-reference variables on
152 failure. Use temporary variables for these cases and change the
153 passed in variables only on success.
154
155
156 - Instead of using `memzero()`/`memset()` to initialize structs allocated
157 on the stack, please try to use c99 structure initializers. It's
158 short, prettier and actually even faster at execution. Hence:
159
160 ```c
161 struct foobar t = {
162 .foo = 7,
163 .bar = "bazz",
164 };
165 ```
166
167 instead of:
168
169 ```c
170 struct foobar t;
171 zero(t);
172 t.foo = 7;
173 t.bar = "bazz";
174 ```
175
176 - The order in which header files are included doesn't matter too
177 much. systemd-internal headers must not rely on an include order, so
178 it is safe to include them in any order possible.
179 However, to not clutter global includes, and to make sure internal
180 definitions will not affect global headers, please always include the
181 headers of external components first (these are all headers enclosed
182 in <>), followed by our own exported headers (usually everything
183 that's prefixed by `sd-`), and then followed by internal headers.
184 Furthermore, in all three groups, order all includes alphabetically
185 so duplicate includes can easily be detected.
186
187 - To implement an endless loop, use `for (;;)` rather than `while (1)`.
188 The latter is a bit ugly anyway, since you probably really
189 meant `while (true)`. To avoid the discussion what the right
190 always-true expression for an infinite while loop is, our
191 recommendation is to simply write it without any such expression by
192 using `for (;;)`.
193
194 - Avoid leaving long-running child processes around, i.e. `fork()`s that
195 are not followed quickly by an `execv()` in the child. Resource
196 management is unclear in this case, and memory CoW will result in
197 unexpected penalties in the parent much, much later on.
198
199 - Don't block execution for arbitrary amounts of time using `usleep()`
200 or a similar call, unless you really know what you do. Just "giving
201 something some time", or so is a lazy excuse. Always wait for the
202 proper event, instead of doing time-based poll loops.
203
204 - To determine the length of a constant string `"foo"`, don't bother with
205 `sizeof("foo")-1`, please use `strlen()` instead (both gcc and clang optimize
206 the call away for fixed strings). The only exception is when declaring an
207 array. In that case use STRLEN, which evaluates to a static constant and
208 doesn't force the compiler to create a VLA.
209
210 - Please avoid using global variables as much as you can. And if you
211 do use them make sure they are static at least, instead of
212 exported. Especially in library-like code it is important to avoid
213 global variables. Why are global variables bad? They usually hinder
214 generic reusability of code (since they break in threaded programs,
215 and usually would require locking there), and as the code using them
216 has side-effects make programs non-transparent. That said, there are
217 many cases where they explicitly make a lot of sense, and are OK to
218 use. For example, the log level and target in `log.c` is stored in a
219 global variable, and that's OK and probably expected by most. Also
220 in many cases we cache data in global variables. If you add more
221 caches like this, please be careful however, and think about
222 threading. Only use static variables if you are sure that
223 thread-safety doesn't matter in your case. Alternatively, consider
224 using TLS, which is pretty easy to use with gcc's `thread_local`
225 concept. It's also OK to store data that is inherently global in
226 global variables, for example data parsed from command lines, see
227 below.
228
229 - Make sure to enforce limits on every user controllable resource. If the user
230 can allocate resources in your code, your code must enforce some form of
231 limits after which it will refuse operation. It's fine if it is hard-coded (at
232 least initially), but it needs to be there. This is particularly important
233 for objects that unprivileged users may allocate, but also matters for
234 everything else any user may allocated.
235
236 - You might wonder what kind of common code belongs in `src/shared/` and what
237 belongs in `src/basic/`. The split is like this: anything that is used to
238 implement the public shared object we provide (sd-bus, sd-login, sd-id128,
239 nss-systemd, nss-mymachines, nss-resolve, nss-myhostname, pam_systemd), must
240 be located in `src/basic` (those objects are not allowed to link to
241 libsystemd-shared.so). Conversely, anything which is shared between multiple
242 components and does not need to be in `src/basic/`, should be in
243 `src/shared/`.
244
245 To summarize:
246
247 `src/basic/`
248 - may be used by all code in the tree
249 - may not use any code outside of `src/basic/`
250
251 `src/libsystemd/`
252 - may be used by all code in the tree, except for code in `src/basic/`
253 - may not use any code outside of `src/basic/`, `src/libsystemd/`
254
255 `src/shared/`
256 - may be used by all code in the tree, except for code in `src/basic/`,
257 `src/libsystemd/`, `src/nss-*`, `src/login/pam_systemd.*`, and files under
258 `src/journal/` that end up in `libjournal-client.a` convenience library.
259 - may not use any code outside of `src/basic/`, `src/libsystemd/`, `src/shared/`
260
261 - Our focus is on the GNU libc (glibc), not any other libcs. If other libcs are
262 incompatible with glibc it's on them. However, if there are equivalent POSIX
263 and Linux/GNU-specific APIs, we generally prefer the POSIX APIs. If there
264 aren't, we are happy to use GNU or Linux APIs, and expect non-GNU
265 implementations of libc to catch up with glibc.
266
267 - Whenever installing a signal handler, make sure to set `SA_RESTART` for it, so
268 that interrupted system calls are automatically restarted, and we minimize
269 hassles with handling `EINTR` (in particular as `EINTR` handling is pretty broken
270 on Linux).
271
272 - When applying C-style unescaping as well as specifier expansion on the same
273 string, always apply the C-style unescaping fist, followed by the specifier
274 expansion. When doing the reverse, make sure to escape `%` in specifier-style
275 first (i.e. `%` → `%%`), and then do C-style escaping where necessary.
276
277 ## Destructors
278
279 - The destructors always deregister the object from the next bigger object, not
280 the other way around.
281
282 - For robustness reasons, destructors should be able to destruct
283 half-initialized objects, too.
284
285 - When you define a destructor or `unref()` call for an object, please accept a
286 `NULL` object and simply treat this as NOP. This is similar to how libc
287 `free()` works, which accepts `NULL` pointers and becomes a NOP for them. By
288 following this scheme a lot of `if` checks can be removed before invoking
289 your destructor, which makes the code substantially more readable and robust.
290
291 - Related to this: when you define a destructor or `unref()` call for an
292 object, please make it return the same type it takes and always return `NULL`
293 from it. This allows writing code like this:
294
295 ```c
296 p = foobar_unref(p);
297 ```
298
299 which will always work regardless if `p` is initialized or not,x and
300 guarantees that `p` is `NULL` afterwards, all in just one line.
301
302 ## Error Handling
303
304 - Error codes are returned as negative `Exxx`. e.g. `return -EINVAL`. There are
305 some exceptions: for constructors, it is OK to return `NULL` on OOM. For
306 lookup functions, `NULL` is fine too for "not found".
307
308 Be strict with this. When you write a function that can fail due to more than
309 one cause, it *really* should have an `int` as the return value for the error
310 code.
311
312 - Do not bother with error checking whether writing to stdout/stderr worked.
313
314 - Do not log errors from "library" code, only do so from "main program"
315 code. (With one exception: it is OK to log with DEBUG level from any code,
316 with the exception of maybe inner loops).
317
318 - In public API calls, you **must** validate all your input arguments for
319 programming error with `assert_return()` and return a sensible return
320 code. In all other calls, it is recommended to check for programming errors
321 with a more brutal `assert()`. We are more forgiving to public users than for
322 ourselves! Note that `assert()` and `assert_return()` really only should be
323 used for detecting programming errors, not for runtime errors. `assert()` and
324 `assert_return()` by usage of `_likely_()` inform the compiler that he should
325 not expect these checks to fail, and they inform fellow programmers about the
326 expected validity and range of parameters.
327
328 - When you invoke certain calls like `unlink()`, or `mkdir_p()` and you know it
329 is safe to ignore the error it might return (because a later call would
330 detect the failure anyway, or because the error is in an error path and you
331 thus couldn't do anything about it anyway), then make this clear by casting
332 the invocation explicitly to `(void)`. Code checks like Coverity understand
333 that, and will not complain about ignored error codes. Hence, please use
334 this:
335
336 ```c
337 (void) unlink("/foo/bar/baz");
338 ```
339
340 instead of just this:
341
342 ```c
343 unlink("/foo/bar/baz");
344 ```
345
346 Don't cast function calls to `(void)` that return no error
347 conditions. Specifically, the various `xyz_unref()` calls that return a
348 `NULL` object shouldn't be cast to `(void)`, since not using the return value
349 does not hide any errors.
350
351 - When returning a return code from `main()`, please preferably use
352 `EXIT_FAILURE` and `EXIT_SUCCESS` as defined by libc.
353
354 ## Memory Allocation
355
356 - Always check OOM. There is no excuse. In program code, you can use
357 `log_oom()` for then printing a short message, but not in "library" code.
358
359 - Avoid fixed-size string buffers, unless you really know the maximum size and
360 that maximum size is small. They are a source of errors, since they possibly
361 result in truncated strings. It is often nicer to use dynamic memory,
362 `alloca()` or VLAs. If you do allocate fixed-size strings on the stack, then
363 it is probably only OK if you either use a maximum size such as `LINE_MAX`,
364 or count in detail the maximum size a string can have. (`DECIMAL_STR_MAX` and
365 `DECIMAL_STR_WIDTH` macros are your friends for this!)
366
367 Or in other words, if you use `char buf[256]` then you are likely doing
368 something wrong!
369
370 - Make use of `_cleanup_free_` and friends. It makes your code much nicer to
371 read (and shorter)!
372
373 - Use `alloca()`, but never forget that it is not OK to invoke `alloca()`
374 within a loop or within function call parameters. `alloca()` memory is
375 released at the end of a function, and not at the end of a `{}` block. Thus,
376 if you invoke it in a loop, you keep increasing the stack pointer without
377 ever releasing memory again. (VLAs have better behavior in this case, so
378 consider using them as an alternative.) Regarding not using `alloca()`
379 within function parameters, see the BUGS section of the `alloca(3)` man page.
380
381 - If you want to concatenate two or more strings, consider using `strjoina()`
382 or `strjoin()` rather than `asprintf()`, as the latter is a lot slower. This
383 matters particularly in inner loops (but note that `strjoina()` cannot be
384 used there).
385
386 ## Types
387
388 - Think about the types you use. If a value cannot sensibly be negative, do not
389 use `int`, but use `unsigned`.
390
391 - Use `char` only for actual characters. Use `uint8_t` or `int8_t` when you
392 actually mean a byte-sized signed or unsigned integers. When referring to a
393 generic byte, we generally prefer the unsigned variant `uint8_t`. Do not use
394 types based on `short`. They *never* make sense. Use `int`, `long`, `long
395 long`, all in unsigned and signed fashion, and the fixed-size types
396 `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`
397 and so on, as well as `size_t`, but nothing else. Do not use kernel types
398 like `u32` and so on, leave that to the kernel.
399
400 - Stay uniform. For example, always use `usec_t` for time values. Do not mix
401 `usec` and `msec`, and `usec` and whatnot.
402
403 - Never use the `off_t` type, and particularly avoid it in public APIs. It's
404 really weirdly defined, as it usually is 64-bit and we don't support it any
405 other way, but it could in theory also be 32-bit. Which one it is depends on
406 a compiler switch chosen by the compiled program, which hence corrupts APIs
407 using it unless they can also follow the program's choice. Moreover, in
408 systemd we should parse values the same way on all architectures and cannot
409 expose `off_t` values over D-Bus. To avoid any confusion regarding conversion
410 and ABIs, always use simply `uint64_t` directly.
411
412 - Unless you allocate an array, `double` is always a better choice than
413 `float`. Processors speak `double` natively anyway, so there is no speed
414 benefit, and on calls like `printf()` `float`s get promoted to `double`s
415 anyway, so there is no point.
416
417 - Use the bool type for booleans, not integers. One exception: in public
418 headers (i.e those in `src/systemd/sd-*.h`) use integers after all, as `bool`
419 is C99 and in our public APIs we try to stick to C89 (with a few extension).
420
421 ## File Descriptors
422
423 - When you allocate a file descriptor, it should be made `O_CLOEXEC` right from
424 the beginning, as none of our files should leak to forked binaries by
425 default. Hence, whenever you open a file, `O_CLOEXEC` must be specified,
426 right from the beginning. This also applies to sockets. Effectively, this
427 means that all invocations to:
428
429 - `open()` must get `O_CLOEXEC` passed,
430 - `socket()` and `socketpair()` must get `SOCK_CLOEXEC` passed,
431 - `recvmsg()` must get `MSG_CMSG_CLOEXEC` set,
432 - `F_DUPFD_CLOEXEC` should be used instead of `F_DUPFD`, and so on,
433 - invocations of `fopen()` should take `e`.
434
435 - It's a good idea to use `O_NONBLOCK` when opening 'foreign' regular files,
436 i.e. file system objects that are supposed to be regular files whose paths
437 where specified by the user and hence might actually refer to other types of
438 file system objects. This is a good idea so that we don't end up blocking on
439 'strange' file nodes, for example if the user pointed us to a FIFO or device
440 node which may block when opening. Moreover even for actual regular files
441 `O_NONBLOCK` has a benefit: it bypasses any mandatory lock that might be in
442 effect on the regular file. If in doubt consider turning off `O_NONBLOCK`
443 again after opening.
444
445 ## Command Line
446
447 - If you parse a command line, and want to store the parsed parameters in
448 global variables, please consider prefixing their names with `arg_`. We have
449 been following this naming rule in most of our tools, and we should continue
450 to do so, as it makes it easy to identify command line parameter variables,
451 and makes it clear why it is OK that they are global variables.
452
453 - Command line option parsing:
454 - Do not print full `help()` on error, be specific about the error.
455 - Do not print messages to stdout on error.
456 - Do not POSIX_ME_HARDER unless necessary, i.e. avoid `+` in option string.
457
458 ## Exporting Symbols
459
460 - Variables and functions **must** be static, unless they have a prototype, and
461 are supposed to be exported.
462
463 - Public API calls (i.e. functions exported by our shared libraries)
464 must be marked `_public_` and need to be prefixed with `sd_`. No
465 other functions should be prefixed like that.
466
467 - When exposing public C APIs, be careful what function parameters you make
468 `const`. For example, a parameter taking a context object should probably not
469 be `const`, even if you are writing an otherwise read-only accessor function
470 for it. The reason is that making it `const` fixates the contract that your
471 call won't alter the object ever, as part of the API. However, that's often
472 quite a promise, given that this even prohibits object-internal caching or
473 lazy initialization of object variables. Moreover, it's usually not too
474 useful for client applications. Hence, please be careful and avoid `const` on
475 object parameters, unless you are very sure `const` is appropriate.
476
477 ## Referencing Concepts
478
479 - When referring to a configuration file option in the documentation and such,
480 please always suffix it with `=`, to indicate that it is a configuration file
481 setting.
482
483 - When referring to a command line option in the documentation and such, please
484 always prefix with `--` or `-` (as appropriate), to indicate that it is a
485 command line option.
486
487 - When referring to a file system path that is a directory, please always
488 suffix it with `/`, to indicate that it is a directory, not a regular file
489 (or other file system object).
490
491 ## Functions to Avoid
492
493 - Use `memzero()` or even better `zero()` instead of `memset(..., 0, ...)`
494
495 - Please use `streq()` and `strneq()` instead of `strcmp()`, `strncmp()` where
496 applicable (i.e. wherever you just care about equality/inequality, not about
497 the sorting order).
498
499 - Never use `strtol()`, `atoi()` and similar calls. Use `safe_atoli()`,
500 `safe_atou32()` and suchlike instead. They are much nicer to use in most
501 cases and correctly check for parsing errors.
502
503 - `htonl()`/`ntohl()` and `htons()`/`ntohs()` are weird. Please use `htobe32()`
504 and `htobe16()` instead, it's much more descriptive, and actually says what
505 really is happening, after all `htonl()` and `htons()` don't operate on
506 `long`s and `short`s as their name would suggest, but on `uint32_t` and
507 `uint16_t`. Also, "network byte order" is just a weird name for "big endian",
508 hence we might want to call it "big endian" right-away.
509
510 - Please never use `dup()`. Use `fcntl(fd, F_DUPFD_CLOEXEC, 3)` instead. For
511 two reason: first, you want `O_CLOEXEC` set on the new `fd` (see
512 above). Second, `dup()` will happily duplicate your `fd` as 0, 1, 2,
513 i.e. stdin, stdout, stderr, should those `fd`s be closed. Given the special
514 semantics of those `fd`s, it's probably a good idea to avoid
515 them. `F_DUPFD_CLOEXEC` with `3` as parameter avoids them.
516
517 - Don't use `fgets()`, it's too hard to properly handle errors such as overly
518 long lines. Use `read_line()` instead, which is our own function that handles
519 this much nicer.
520
521 - Don't invoke `exit()`, ever. It is not replacement for proper error
522 handling. Please escalate errors up your call chain, and use normal `return`
523 to exit from the main function of a process. If you `fork()`ed off a child
524 process, please use `_exit()` instead of `exit()`, so that the exit handlers
525 are not run.
526
527 - We never use the POSIX version of `basename()` (which glibc defines it in
528 `libgen.h`), only the GNU version (which glibc defines in `string.h`). The
529 only reason to include `libgen.h` is because `dirname()` is needed. Every
530 time you need that please immediately undefine `basename()`, and add a
531 comment about it, so that no code ever ends up using the POSIX version!
532
533 # Committing to git
534
535 - Commit message subject lines should be prefixed with an appropriate component
536 name of some kind. For example "journal: ", "nspawn: " and so on.
537
538 - Do not use "Signed-Off-By:" in your commit messages. That's a kernel thing we
539 don't do in the systemd project.