1:255.16-alt1
[systemd_ALT.git] / docs / CODING_STYLE.md
blobfe35adeea56e64419ab598faaa97288fa2e1eff7
1 ---
2 title: Coding Style
3 category: Contributing
4 layout: default
5 SPDX-License-Identifier: LGPL-2.1-or-later
6 ---
8 # Coding Style
10 ## Formatting
12 - 8ch indent, no tabs, except for files in `man/` which are 2ch indent, and
13   still no tabs, and shell scripts, which are 4ch indent, and no tabs either.
15 - We prefer `/* comments */` over `// comments` in code you commit,
16   please. This way `// comments` are left for developers to use for local,
17   temporary commenting of code for debug purposes (i.e. uncommittable stuff),
18   making such comments easily discernible from explanatory, documenting code
19   comments (i.e. committable stuff).
21 - Don't break code lines too eagerly. We do **not** force line breaks at 80ch,
22   all of today's screens should be much larger than that. But then again, don't
23   overdo it, ~109ch should be enough really. The `.editorconfig`, `.vimrc` and
24   `.dir-locals.el` files contained in the repository will set this limit up for
25   you automatically, if you let them (as well as a few other things). Please
26   note that emacs loads `.dir-locals.el` automatically, but vim needs to be
27   configured to load `.vimrc`, see that file for instructions.
29 - If you break a function declaration over multiple lines, do it like this:
31   ```c
32   void some_function(
33                   int foo,
34                   bool bar,
35                   char baz) {
37           int a, b, c;
38   ```
40   (i.e. use double indentation — 16 spaces — for the parameter list.)
42 - Try to write this:
44   ```c
45   void foo() {
46   }
47   ```
49   instead of this:
51   ```c
52   void foo()
53   {
54   }
55   ```
57 - Function return types should be seen/written as whole, i.e. write this:
59   ```c
60   const char* foo(const char *input);
61   ```
63   instead of this:
65   ```c
66   const char *foo(const char *input);
67   ```
69 - Single-line `if` blocks should not be enclosed in `{}`. Write this:
71   ```c
72   if (foobar)
73           waldo();
74   ```
76   instead of this:
78   ```c
79   if (foobar) {
80           waldo();
81   }
82   ```
84 - Do not write `foo ()`, write `foo()`.
86 - `else` blocks should generally start on the same line as the closing `}`:
87   ```c
88   if (foobar) {
89           find();
90           waldo();
91   } else
92           dont_find_waldo();
93   ```
95 - Please define flags types like this:
97   ```c
98   typedef enum FoobarFlags {
99           FOOBAR_QUUX  = 1 << 0,
100           FOOBAR_WALDO = 1 << 1,
101           FOOBAR_XOXO  = 1 << 2,
102           …
103   } FoobarFlags;
104   ```
106   i.e. use an enum for it, if possible. Indicate bit values via `1 <<`
107   expressions, and align them vertically. Define both an enum and a type for
108   it.
110 - If you define (non-flags) enums, follow this template:
112   ```c
113   typedef enum FoobarMode {
114           FOOBAR_AAA,
115           FOOBAR_BBB,
116           FOOBAR_CCC,
117           …
118           _FOOBAR_MAX,
119           _FOOBAR_INVALID = -EINVAL,
120   } FoobarMode;
121   ```
123   i.e. define a `_MAX` enum for the largest defined enum value, plus one. Since
124   this is not a regular enum value, prefix it with `_`. Also, define a special
125   "invalid" enum value, and set it to `-EINVAL`. That way the enum type can
126   safely be used to propagate conversion errors.
128 - If you define an enum in a public API, be extra careful, as the size of the
129   enum might change when new values are added, which would break ABI
130   compatibility. Since we typically want to allow adding new enum values to an
131   existing enum type with later API versions, please use the
132   `_SD_ENUM_FORCE_S64()` macro in the enum definition, which forces the size of
133   the enum to be signed 64-bit wide.
135 - Empty lines to separate code blocks are a good thing, please add them
136   abundantly. However, please stick to one at a time, i.e. multiple empty lines
137   immediately following each other are not OK. Also, we try to keep function
138   calls and their immediate error handling together. Hence:
140   ```c
141   /* → empty line here is good */
142   r = some_function(…);
143   /* → empty line here would be bad */
144   if (r < 0)
145           return log_error_errno(r, "Some function failed: %m");
146   /* → empty line here is good */
147   ```
149 - In shell scripts, do not use whitespace after the redirection operator
150   (`>some/file` instead of `> some/file`, `<<EOF` instead of `<< EOF`).
152 ## Code Organization and Semantics
154 - For our codebase we intend to use ISO C11 *with* GNU extensions (aka
155   "gnu11"). Public APIs (i.e. those we expose via `libsystemd.so`
156   i.e. `systemd/sd-*.h`) should only use ISO C89 however (with a very limited
157   set of conservative and common extensions, such as fixed size integer types
158   from `<inttypes.h>`), so that we don't force consuming programs into C11
159   mode. (This discrepancy in particular means one thing: internally we use C99
160   `bool` booleans, externally C89-compatible `int` booleans which generally
161   have different size in memory and slightly different semantics, also see
162   below.)  Both for internal and external code it's OK to use even newer
163   features and GCC extension than "gnu11", as long as there's reasonable
164   fallback #ifdeffery in place to ensure compatibility is retained with older
165   compilers.
167 - Please name structures in `PascalCase` (with exceptions, such as public API
168   structs), variables and functions in `snake_case`.
170 - Avoid static variables, except for caches and very few other cases. Think
171   about thread-safety! While most of our code is never used in threaded
172   environments, at least the library code should make sure it works correctly
173   in them. Instead of doing a lot of locking for that, we tend to prefer using
174   TLS to do per-thread caching (which only works for small, fixed-size cache
175   objects), or we disable caching for any thread that is not the main
176   thread. Use `is_main_thread()` to detect whether the calling thread is the
177   main thread.
179 - Do not write functions that clobber call-by-reference variables on
180   failure. Use temporary variables for these cases and change the passed in
181   variables only on success. The rule is: never clobber return parameters on
182   failure, always initialize return parameters on success.
184 - Typically, function parameters fit into three categories: input parameters,
185   mutable objects, and call-by-reference return parameters. Input parameters
186   should always carry suitable "const" declarators if they are pointers, to
187   indicate they are input-only and not changed by the function. Return
188   parameters are best prefixed with "ret_", to clarify they are return
189   parameters. (Conversely, please do not prefix parameters that aren't
190   output-only with "ret_", in particular not mutable parameters that are both
191   input as well as output). Example:
193   ```c
194   static int foobar_frobnicate(
195                   Foobar *object,            /* the associated mutable object */
196                   const char *input,         /* immutable input parameter */
197                   char **ret_frobnicated) {  /* return parameter */
198           …
199           return 0;
200   }
201   ```
203 - The order in which header files are included doesn't matter too
204   much. systemd-internal headers must not rely on an include order, so it is
205   safe to include them in any order possible.  However, to not clutter global
206   includes, and to make sure internal definitions will not affect global
207   headers, please always include the headers of external components first
208   (these are all headers enclosed in <>), followed by our own exported headers
209   (usually everything that's prefixed by `sd-`), and then followed by internal
210   headers.  Furthermore, in all three groups, order all includes alphabetically
211   so duplicate includes can easily be detected.
213 - Please avoid using global variables as much as you can. And if you do use
214   them make sure they are static at least, instead of exported. Especially in
215   library-like code it is important to avoid global variables. Why are global
216   variables bad? They usually hinder generic reusability of code (since they
217   break in threaded programs, and usually would require locking there), and as
218   the code using them has side-effects make programs non-transparent. That
219   said, there are many cases where they explicitly make a lot of sense, and are
220   OK to use. For example, the log level and target in `log.c` is stored in a
221   global variable, and that's OK and probably expected by most. Also in many
222   cases we cache data in global variables. If you add more caches like this,
223   please be careful however, and think about threading. Only use static
224   variables if you are sure that thread-safety doesn't matter in your
225   case. Alternatively, consider using TLS, which is pretty easy to use with
226   gcc's `thread_local` concept. It's also OK to store data that is inherently
227   global in global variables, for example, data parsed from command lines, see
228   below.
230 - Our focus is on the GNU libc (glibc), not any other libcs. If other libcs are
231   incompatible with glibc it's on them. However, if there are equivalent POSIX
232   and Linux/GNU-specific APIs, we generally prefer the POSIX APIs. If there
233   aren't, we are happy to use GNU or Linux APIs, and expect non-GNU
234   implementations of libc to catch up with glibc.
236 ## Using C Constructs
238 - Allocate local variables where it makes sense: at the top of the block, or at
239   the point where they can be initialized. Avoid huge variable declaration
240   lists at the top of the function.
242   As an exception, `int r` is typically used for a local state variable, but
243   should almost always be declared as the last variable at the top of the
244   function.
246   ```c
247   {
248           uint64_t a;
249           int r;
251           r = frobnicate(&a);
252           if (r < 0)
253                   …
255           uint64_t b = a + 1, c;
257           r = foobarify(a, b, &c);
258           if (r < 0)
259                   …
261           const char *pretty = prettify(a, b, c);
262           …
263   }
264   ```
266 - Do not mix multiple variable definitions with function invocations or
267   complicated expressions:
269   ```c
270   {
271           uint64_t x = 7;
272           int a;
274           a = foobar();
275   }
276   ```
278   instead of:
280   ```c
281   {
282           int a = foobar();
283           uint64_t x = 7;
284   }
285   ```
287 - Use `goto` for cleaning up, and only use it for that. I.e. you may only jump
288   to the end of a function, and little else. Never jump backwards!
290 - To minimize strict aliasing violations, we prefer unions over casting.
292 - Instead of using `memzero()`/`memset()` to initialize structs allocated on
293   the stack, please try to use c99 structure initializers. It's short, prettier
294   and actually even faster at execution. Hence:
296   ```c
297   struct foobar t = {
298           .foo = 7,
299           .bar = "bazz",
300   };
301   ```
303   instead of:
305   ```c
306   struct foobar t;
307   zero(t);
308   t.foo = 7;
309   t.bar = "bazz";
310   ```
312 - To implement an endless loop, use `for (;;)` rather than `while (1)`. The
313   latter is a bit ugly anyway, since you probably really meant `while
314   (true)`. To avoid the discussion what the right always-true expression for an
315   infinite while loop is, our recommendation is to simply write it without any
316   such expression by using `for (;;)`.
318 - To determine the length of a constant string `"foo"`, don't bother with
319   `sizeof("foo")-1`, please use `strlen()` instead (both gcc and clang optimize
320   the call away for fixed strings). The only exception is when declaring an
321   array. In that case use `STRLEN()`, which evaluates to a static constant and
322   doesn't force the compiler to create a VLA.
324 - Please use C's downgrade-to-bool feature only for expressions that are
325   actually booleans (or "boolean-like"), and not for variables that are really
326   numeric. Specifically, if you have an `int b` and it's only used in a boolean
327   sense, by all means check its state with `if (b) …` — but if `b` can actually
328   have more than two semantic values, and you want to compare for non-zero,
329   then please write that explicitly with `if (b != 0) …`. This helps readability
330   as the value range and semantical behaviour is directly clear from the
331   condition check. As a special addition: when dealing with pointers which you
332   want to check for non-NULL-ness, you may also use downgrade-to-bool feature.
334 - Please do not use yoda comparisons, i.e. please prefer the more readable `if
335   (a == 7)` over the less readable `if (7 == a)`.
337 ## Destructors
339 - The destructors always deregister the object from the next bigger object, not
340   the other way around.
342 - For robustness reasons, destructors should be able to destruct
343   half-initialized objects, too.
345 - When you define a destructor or `unref()` call for an object, please accept a
346   `NULL` object and simply treat this as NOP. This is similar to how libc
347   `free()` works, which accepts `NULL` pointers and becomes a NOP for them. By
348   following this scheme a lot of `if` checks can be removed before invoking
349   your destructor, which makes the code substantially more readable and robust.
351 - Related to this: when you define a destructor or `unref()` call for an
352   object, please make it return the same type it takes and always return `NULL`
353   from it. This allows writing code like this:
355   ```c
356   p = foobar_unref(p);
357   ```
359   which will always work regardless if `p` is initialized or not, and
360   guarantees that `p` is `NULL` afterwards, all in just one line.
362 ## Common Function Naming
364 - Name destructor functions that destroy an object in full freeing all its
365   memory and associated resources (and thus invalidating the pointer to it)
366   `xyz_free()`. Example: `strv_free()`.
368 - Name destructor functions that destroy only the referenced content of an
369   object but leave the object itself allocated `xyz_done()`. If it resets all
370   fields so that the object can be reused later call it `xyz_clear()`.
372 - Functions that decrease the reference counter of an object by one should be
373   called `xyz_unref()`. Example: `json_variant_unref()`. Functions that
374   increase the reference counter by one should be called `xyz_ref()`. Example:
375   `json_variant_ref()`
377 ## Error Handling
379 - Error codes are returned as negative `Exxx`. e.g. `return -EINVAL`. There are
380   some exceptions: for constructors, it is OK to return `NULL` on OOM. For
381   lookup functions, `NULL` is fine too for "not found".
383   Be strict with this. When you write a function that can fail due to more than
384   one cause, it *really* should have an `int` as the return value for the error
385   code.
387 - libc system calls typically return -1 on error (with the error code in
388   `errno`), and >= 0 on success. Use the RET_NERRNO() helper if you are looking
389   for a simple way to convert this libc style error returning into systemd
390   style error returning. e.g.
392   ```c
393   …
394   r = RET_NERRNO(unlink(t));
395   …
396   ```
398   or
400   ```c
401   …
402   r = RET_NERRNO(open("/some/file", O_RDONLY|O_CLOEXEC));
403   …
404   ```
406 - Do not bother with error checking whether writing to stdout/stderr worked.
408 - Do not log errors from "library" code, only do so from "main program"
409   code. (With one exception: it is OK to log with DEBUG level from any code,
410   with the exception of maybe inner loops).
412 - In public API calls, you **must** validate all your input arguments for
413   programming error with `assert_return()` and return a sensible return
414   code. In all other calls, it is recommended to check for programming errors
415   with a more brutal `assert()`. We are more forgiving to public users than for
416   ourselves! Note that `assert()` and `assert_return()` really only should be
417   used for detecting programming errors, not for runtime errors. `assert()` and
418   `assert_return()` by usage of `_likely_()` inform the compiler that it should
419   not expect these checks to fail, and they inform fellow programmers about the
420   expected validity and range of parameters.
422 - When you invoke certain calls like `unlink()`, or `mkdir_p()` and you know it
423   is safe to ignore the error it might return (because a later call would
424   detect the failure anyway, or because the error is in an error path and you
425   thus couldn't do anything about it anyway), then make this clear by casting
426   the invocation explicitly to `(void)`. Code checks like Coverity understand
427   that, and will not complain about ignored error codes. Hence, please use
428   this:
430   ```c
431   (void) unlink("/foo/bar/baz");
432   ```
434   instead of just this:
436   ```c
437   unlink("/foo/bar/baz");
438   ```
440   When returning from a `void` function, you may also want to shorten the error
441   path boilerplate by returning a function invocation cast to `(void)` like so:
443   ```c
444   if (condition_not_met)
445           return (void) log_tests_skipped("Cannot run ...");
446   ```
448   Don't cast function calls to `(void)` that return no error
449   conditions. Specifically, the various `xyz_unref()` calls that return a
450   `NULL` object shouldn't be cast to `(void)`, since not using the return value
451   does not hide any errors.
453 - When returning a return code from `main()`, please preferably use
454   `EXIT_FAILURE` and `EXIT_SUCCESS` as defined by libc.
456 ## Logging
458 - For every function you add, think about whether it is a "logging" function or
459   a "non-logging" function. "Logging" functions do (non-debug) logging on their
460   own, "non-logging" functions never log on their own (except at debug level)
461   and expect their callers to log. All functions in "library" code, i.e. in
462   `src/shared/` and suchlike must be "non-logging". Every time a "logging"
463   function calls a "non-logging" function, it should log about the resulting
464   errors. If a "logging" function calls another "logging" function, then it
465   should not generate log messages, so that log messages are not generated
466   twice for the same errors. (Note that debug level logging — at syslog level
467   `LOG_DEBUG` — is not considered logging in this context, debug logging is
468   generally always fine and welcome.)
470 - If possible, do a combined log & return operation:
472   ```c
473   r = operation(...);
474   if (r < 0)
475           return log_(error|warning|notice|...)_errno(r, "Failed to ...: %m");
476   ```
478   If the error value is "synthetic", i.e. it was not received from
479   the called function, use `SYNTHETIC_ERRNO` wrapper to tell the logging
480   system to not log the errno value, but still return it:
482   ```c
483   n = read(..., s, sizeof s);
484   if (n != sizeof s)
485           return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read ...");
486   ```
488 ## Memory Allocation
490 - Always check OOM. There is no excuse. In program code, you can use
491   `log_oom()` for then printing a short message, but not in "library" code.
493 - Avoid fixed-size string buffers, unless you really know the maximum size and
494   that maximum size is small. It is often nicer to use dynamic memory,
495   `alloca_safe()` or VLAs. If you do allocate fixed-size strings on the stack,
496   then it is probably only OK if you either use a maximum size such as
497   `LINE_MAX`, or count in detail the maximum size a string can
498   have. (`DECIMAL_STR_MAX` and `DECIMAL_STR_WIDTH` macros are your friends for
499   this!)
501   Or in other words, if you use `char buf[256]` then you are likely doing
502   something wrong!
504 - Make use of `_cleanup_free_` and friends. It makes your code much nicer to
505   read (and shorter)!
507 - Do not use `alloca()`, `strdupa()` or `strndupa()` directly. Use
508   `alloca_safe()`, `strdupa_safe()` or `strndupa_safe()` instead. (The
509   difference is that the latter include an assertion that the specified size is
510   below a safety threshold, so that the program rather aborts than runs into
511   possible stack overruns.)
513 - Use `alloca_safe()`, but never forget that it is not OK to invoke
514   `alloca_safe()` within a loop or within function call
515   parameters. `alloca_safe()` memory is released at the end of a function, and
516   not at the end of a `{}` block. Thus, if you invoke it in a loop, you keep
517   increasing the stack pointer without ever releasing memory again. (VLAs have
518   better behavior in this case, so consider using them as an alternative.)
519   Regarding not using `alloca_safe()` within function parameters, see the BUGS
520   section of the `alloca(3)` man page.
522 - If you want to concatenate two or more strings, consider using `strjoina()`
523   or `strjoin()` rather than `asprintf()`, as the latter is a lot slower. This
524   matters particularly in inner loops (but note that `strjoina()` cannot be
525   used there).
527 ## Runtime Behaviour
529 - Avoid leaving long-running child processes around, i.e. `fork()`s that are
530   not followed quickly by an `execv()` in the child. Resource management is
531   unclear in this case, and memory CoW will result in unexpected penalties in
532   the parent much, much later on.
534 - Don't block execution for arbitrary amounts of time using `usleep()` or a
535   similar call, unless you really know what you do. Just "giving something some
536   time", or so is a lazy excuse. Always wait for the proper event, instead of
537   doing time-based poll loops.
539 - Whenever installing a signal handler, make sure to set `SA_RESTART` for it,
540   so that interrupted system calls are automatically restarted, and we minimize
541   hassles with handling `EINTR` (in particular as `EINTR` handling is pretty
542   broken on Linux).
544 - When applying C-style unescaping as well as specifier expansion on the same
545   string, always apply the C-style unescaping first, followed by the specifier
546   expansion. When doing the reverse, make sure to escape `%` in specifier-style
547   first (i.e. `%` → `%%`), and then do C-style escaping where necessary.
549 - Be exceptionally careful when formatting and parsing floating point
550   numbers. Their syntax is locale dependent (i.e. `5.000` in en_US is generally
551   understood as 5, while in de_DE as 5000.).
553 - Make sure to enforce limits on every user controllable resource. If the user
554   can allocate resources in your code, your code must enforce some form of
555   limits after which it will refuse operation. It's fine if it is hard-coded
556   (at least initially), but it needs to be there. This is particularly
557   important for objects that unprivileged users may allocate, but also matters
558   for everything else any user may allocate.
560 - Please use `secure_getenv()` for all environment variable accesses, unless
561   it's clear that `getenv()` would be the better choice. This matters in
562   particular in `src/basic/` and `src/shared/` (i.e. library code that might
563   end up in unexpected processes), but should be followed everywhere else too
564   (in order to make it unproblematic to move code around). To say this clearly:
565   the default should be `secure_getenv()`, the exception should be regular
566   `getenv()`.
568 ## Types
570 - Think about the types you use. If a value cannot sensibly be negative, do not
571   use `int`, but use `unsigned`.  We prefer `unsigned` form to `unsigned int`.
573 - Use `char` only for actual characters. Use `uint8_t` or `int8_t` when you
574   actually mean a byte-sized signed or unsigned integers. When referring to a
575   generic byte, we generally prefer the unsigned variant `uint8_t`. Do not use
576   types based on `short`. They *never* make sense. Use `int`, `long`, `long
577   long`, all in unsigned and signed fashion, and the fixed-size types
578   `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`
579   and so on, as well as `size_t`, but nothing else. Do not use kernel types
580   like `u32` and so on, leave that to the kernel.
582 - Stay uniform. For example, always use `usec_t` for time values. Do not mix
583   `usec` and `msec`, and `usec` and whatnot.
585 - Never use the `off_t` type, and particularly avoid it in public APIs. It's
586   really weirdly defined, as it usually is 64-bit and we don't support it any
587   other way, but it could in theory also be 32-bit. Which one it is depends on
588   a compiler switch chosen by the compiled program, which hence corrupts APIs
589   using it unless they can also follow the program's choice. Moreover, in
590   systemd we should parse values the same way on all architectures and cannot
591   expose `off_t` values over D-Bus. To avoid any confusion regarding conversion
592   and ABIs, always use simply `uint64_t` directly.
594 - Unless you allocate an array, `double` is always a better choice than
595   `float`. Processors speak `double` natively anyway, so there is no speed
596   benefit, and on calls like `printf()` `float`s get promoted to `double`s
597   anyway, so there is no point.
599 - Use the bool type for booleans, not integers. One exception: in public
600   headers (i.e those in `src/systemd/sd-*.h`) use integers after all, as `bool`
601   is C99 and in our public APIs we try to stick to C89 (with a few extensions;
602   also see above).
604 ## Deadlocks
606 - Do not issue NSS requests (that includes user name and hostname lookups)
607   from PID 1 as this might trigger deadlocks when those lookups involve
608   synchronously talking to services that we would need to start up.
610 - Do not synchronously talk to any other service from PID 1, due to risk of
611   deadlocks.
613 ## File Descriptors
615 - When you allocate a file descriptor, it should be made `O_CLOEXEC` right from
616   the beginning, as none of our files should leak to forked binaries by
617   default. Hence, whenever you open a file, `O_CLOEXEC` must be specified,
618   right from the beginning. This also applies to sockets. Effectively, this
619   means that all invocations to:
621   - `open()` must get `O_CLOEXEC` passed,
622   - `socket()` and `socketpair()` must get `SOCK_CLOEXEC` passed,
623   - `recvmsg()` must get `MSG_CMSG_CLOEXEC` set,
624   - `F_DUPFD_CLOEXEC` should be used instead of `F_DUPFD`, and so on,
625   - invocations of `fopen()` should take `e`.
627 - It's a good idea to use `O_NONBLOCK` when opening 'foreign' regular files,
628   i.e.  file system objects that are supposed to be regular files whose paths
629   were specified by the user and hence might actually refer to other types of
630   file system objects. This is a good idea so that we don't end up blocking on
631   'strange' file nodes, for example, if the user pointed us to a FIFO or device
632   node which may block when opening. Moreover even for actual regular files
633   `O_NONBLOCK` has a benefit: it bypasses any mandatory lock that might be in
634   effect on the regular file. If in doubt consider turning off `O_NONBLOCK`
635   again after opening.
637 - These days we generally prefer `openat()`-style file APIs, i.e. APIs that
638   accept a combination of file descriptor and path string, and where the path
639   (if not absolute) is considered relative to the specified file
640   descriptor. When implementing library calls in similar style, please make
641   sure to imply `AT_EMPTY_PATH` if an empty or `NULL` path argument is
642   specified (and convert that latter to an empty string). This differs from the
643   underlying kernel semantics, where `AT_EMPTY_PATH` must always be specified
644   explicitly, and `NULL` is not accepted as path.
646 ## Command Line
648 - If you parse a command line, and want to store the parsed parameters in
649   global variables, please consider prefixing their names with `arg_`. We have
650   been following this naming rule in most of our tools, and we should continue
651   to do so, as it makes it easy to identify command line parameter variables,
652   and makes it clear why it is OK that they are global variables.
654 - Command line option parsing:
655   - Do not print full `help()` on error, be specific about the error.
656   - Do not print messages to stdout on error.
657   - Do not POSIX_ME_HARDER unless necessary, i.e. avoid `+` in option string.
659 ## Exporting Symbols
661 - Variables and functions **must** be static, unless they have a prototype, and
662   are supposed to be exported.
664 - Public API calls (i.e. functions exported by our shared libraries)
665   must be marked `_public_` and need to be prefixed with `sd_`. No
666   other functions should be prefixed like that.
668 - When exposing public C APIs, be careful what function parameters you make
669   `const`. For example, a parameter taking a context object should probably not
670   be `const`, even if you are writing an otherwise read-only accessor function
671   for it. The reason is that making it `const` fixates the contract that your
672   call won't alter the object ever, as part of the API. However, that's often
673   quite a promise, given that this even prohibits object-internal caching or
674   lazy initialization of object variables. Moreover, it's usually not too
675   useful for client applications. Hence, please be careful and avoid `const` on
676   object parameters, unless you are very sure `const` is appropriate.
678 ## Referencing Concepts
680 - When referring to a configuration file option in the documentation and such,
681   please always suffix it with `=`, to indicate that it is a configuration file
682   setting.
684 - When referring to a command line option in the documentation and such, please
685   always prefix with `--` or `-` (as appropriate), to indicate that it is a
686   command line option.
688 - When referring to a file system path that is a directory, please always
689   suffix it with `/`, to indicate that it is a directory, not a regular file
690   (or other file system object).
692 ## Functions to Avoid
694 - Use `memzero()` or even better `zero()` instead of `memset(..., 0, ...)`
696 - Please use `streq()` and `strneq()` instead of `strcmp()`, `strncmp()` where
697   applicable (i.e. wherever you just care about equality/inequality, not about
698   the sorting order).
700 - Never use `strtol()`, `atoi()` and similar calls. Use `safe_atoli()`,
701   `safe_atou32()` and suchlike instead. They are much nicer to use in most
702   cases and correctly check for parsing errors.
704 - `htonl()`/`ntohl()` and `htons()`/`ntohs()` are weird. Please use `htobe32()`
705   and `htobe16()` instead, it's much more descriptive, and actually says what
706   really is happening, after all `htonl()` and `htons()` don't operate on
707   `long`s and `short`s as their name would suggest, but on `uint32_t` and
708   `uint16_t`. Also, "network byte order" is just a weird name for "big endian",
709   hence we might want to call it "big endian" right-away.
711 - Use `typesafe_inet_ntop()`, `typesafe_inet_ntop4()`, and
712   `typesafe_inet_ntop6()` instead of `inet_ntop()`. But better yet, use the
713   `IN_ADDR_TO_STRING()`, `IN4_ADDR_TO_STRING()`, and `IN6_ADDR_TO_STRING()`
714   macros which allocate an anonymous buffer internally.
716 - Please never use `dup()`. Use `fcntl(fd, F_DUPFD_CLOEXEC, 3)` instead. For
717   two reasons: first, you want `O_CLOEXEC` set on the new `fd` (see
718   above). Second, `dup()` will happily duplicate your `fd` as 0, 1, 2,
719   i.e. stdin, stdout, stderr, should those `fd`s be closed. Given the special
720   semantics of those `fd`s, it's probably a good idea to avoid
721   them. `F_DUPFD_CLOEXEC` with `3` as parameter avoids them.
723 - Don't use `fgets()`, it's too hard to properly handle errors such as overly
724   long lines. Use `read_line()` instead, which is our own function that handles
725   this much more nicely.
727 - Don't invoke `exit()`, ever. It is not replacement for proper error
728   handling. Please escalate errors up your call chain, and use normal `return`
729   to exit from the main function of a process. If you `fork()`ed off a child
730   process, please use `_exit()` instead of `exit()`, so that the exit handlers
731   are not run.
733 - Do not use `basename()` or `dirname()`. The semantics in corner cases are
734   full of pitfalls, and the fact that there are two quite different versions of
735   `basename()` (one POSIX and one GNU, of which the latter is much more useful)
736   doesn't make it better either. Use path_extract_filename() and
737   path_extract_directory() instead.
739 - Never use `FILENAME_MAX`. Use `PATH_MAX` instead (for checking maximum size
740   of paths) and `NAME_MAX` (for checking maximum size of filenames).
741   `FILENAME_MAX` is not POSIX, and is a confusingly named alias for `PATH_MAX`
742   on Linux. Note that `NAME_MAX` does not include space for a trailing `NUL`,
743   but `PATH_MAX` does. UNIX FTW!
745 ## Committing to git
747 - Commit message subject lines should be prefixed with an appropriate component
748   name of some kind. For example, "journal: ", "nspawn: " and so on.
750 - Do not use "Signed-Off-By:" in your commit messages. That's a kernel thing we
751   don't do in the systemd project.
753 ## Commenting
755 - The best place for code comments and explanations is in the code itself. Only
756   the second best is in git commit messages. The worst place is in the GitHub
757   PR cover letter. Hence, whenever you type a commit message consider for a
758   moment if what you are typing there wouldn't be a better fit for an in-code
759   comment. And if you type the cover letter of a PR, think hard if this
760   wouldn't be better as a commit message or even code comment. Comments are
761   supposed to be useful for somebody who reviews the code, and hence hiding
762   comments in git commits or PR cover letters makes reviews unnecessarily
763   hard. Moreover, while we rely heavily on GitHub's project management
764   infrastructure we'd like to keep everything that can reasonably be kept in
765   the git repository itself in the git repository, so that we can theoretically
766   move things elsewhere with the least effort possible.
768 - It's OK to reference GitHub PRs, GitHub issues and git commits from code
769   comments. Cross-referencing code, issues, and documentation is a good thing.
771 - Reasonable use of non-ASCII Unicode UTF-8 characters in code comments is
772   welcome. If your code comment contains an emoji or two this will certainly
773   brighten the day of the occasional reviewer of your code. Really! 😊
775 ## Threading
777 - We generally avoid using threads, to the level this is possible. In
778   particular in the service manager/PID 1 threads are not OK to use. This is
779   because you cannot mix memory allocation in threads with use of glibc's
780   `clone()` call, or manual `clone()`/`clone3()` system call wrappers. Only
781   glibc's own `fork()` call will properly synchronize the memory allocation
782   locks around the process clone operation. This means that if a process is
783   cloned via `clone()`/`clone3()` and another thread currently has the
784   `malloc()` lock taken, it will be cloned in locked state to the child, and
785   thus can never be acquired in the child, leading to deadlocks. Hence, when
786   using `clone()`/`clone3()` there are only two ways out: never use threads in the
787   parent, or never do memory allocation in the child. For our uses we need
788   `clone()`/`clone3()` and hence decided to avoid threads. Of course, sometimes the
789   concurrency threads allow is beneficial, however we suggest forking off
790   worker *processes* rather than worker *threads* for this purpose, ideally
791   even with an `execve()` to remove the CoW trap situation `fork()` easily
792   triggers.
794 - A corollary of the above is: never use `clone()` where a `fork()` would do
795   too. Also consider using `posix_spawn()` which combines `clone()` +
796   `execve()` into one and has nice properties since it avoids becoming a CoW
797   trap by using `CLONE_VFORK` and `CLONE_VM` together.
799 - While we avoid forking off threads on our own, writing thread-safe code is a
800   good idea where it might end up running inside of libsystemd.so or
801   similar. Hence, use TLS (i.e. `thread_local`) where appropriate, and maybe
802   the occasional `pthread_once()`.