]> git.ipfire.org Git - thirdparty/systemd.git/blame - docs/CODING_STYLE.md
hostnamed: update chassis table to SMBIOS 3.5
[thirdparty/systemd.git] / docs / CODING_STYLE.md
CommitLineData
c3e270f4
FB
1---
2title: Coding Style
4cdca0af 3category: Contributing
b41a3f66 4layout: default
0aff7b75 5SPDX-License-Identifier: LGPL-2.1-or-later
c3e270f4
FB
6---
7
c1d3483d 8# Coding Style
82143987 9
8c9289e7
LP
10## Formatting
11
3b69b18f
ZJS
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.
82143987 14
8c9289e7
LP
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).
82143987
FA
20
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
c90ee834 23 overdo it, ~109ch should be enough really. The `.editorconfig`, `.vimrc` and
82143987 24 `.dir-locals.el` files contained in the repository will set this limit up for
3b69b18f
ZJS
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.
82143987 28
7489ccc3
LB
29- If you break a function declaration over multiple lines, do it like this:
30
31 ```c
32 void some_function(
33 int foo,
34 bool bar,
35 char baz) {
36
37 int a, b, c;
38 ```
39
cf33b707
LP
40 (i.e. use double indentation — 16 spaces — for the parameter list.)
41
8c9289e7
LP
42- Try to write this:
43
44 ```c
45 void foo() {
46 }
47 ```
48
49 instead of this:
50
51 ```c
52 void foo()
53 {
54 }
55 ```
56
57- Single-line `if` blocks should not be enclosed in `{}`. Write this:
58
59 ```c
60 if (foobar)
61 waldo();
62 ```
63
64 instead of this:
65
66 ```c
67 if (foobar) {
68 waldo();
69 }
70 ```
71
72- Do not write `foo ()`, write `foo()`.
4dbad977
AW
73- `else` blocks should generally start on the same line as the closing `}`:
74 ```c
75 if (foobar) {
76 find();
77 waldo();
78 } else
79 dont_find_waldo();
80 ```
8c9289e7 81
b4f12824 82## Code Organization and Semantics
8c9289e7 83
40f55f69
LP
84- For our codebase we intend to use ISO C11 *with* GNU extensions (aka
85 "gnu11"). Public APIs (i.e. those we expose via `libsystemd.so`
86 i.e. `systemd/sd-*.h`) should only use ISO C89 however (with a very limited
87 set of conservative and common extensions, such as fixed size integer types
88 from `<inttypes.h>`), so that we don't force consuming programs into C11
89 mode. (This discrepancy in particular means one thing: internally we use C99
90 `bool` booleans, externally C89-compatible `int` booleans which generally
91 have different size in memory and slightly different semantics, also see
92 below.) Both for internal and external code it's OK to use even newer
93 features and GCC extension than "gnu11", as long as there's reasonable
94 fallback #ifdeffery in place to ensure compatibility is retained with older
95 compilers.
96
78e5b4d7
LP
97- Please name structures in `PascalCase` (with exceptions, such as public API
98 structs), variables and functions in `snake_case`.
82143987 99
b4f12824
LP
100- Avoid static variables, except for caches and very few other cases. Think
101 about thread-safety! While most of our code is never used in threaded
102 environments, at least the library code should make sure it works correctly
103 in them. Instead of doing a lot of locking for that, we tend to prefer using
104 TLS to do per-thread caching (which only works for small, fixed-size cache
105 objects), or we disable caching for any thread that is not the main
106 thread. Use `is_main_thread()` to detect whether the calling thread is the
107 main thread.
82143987 108
82143987 109- Do not write functions that clobber call-by-reference variables on
b4f12824 110 failure. Use temporary variables for these cases and change the passed in
cf33b707
LP
111 variables only on success. The rule is: never clobber return parameters on
112 failure, always initialize return parameters on success.
113
114- Typically, function parameters fit into three categories: input parameters,
115 mutable objects, and call-by-reference return parameters. Input parameters
116 should always carry suitable "const" declarators if they are pointers, to
117 indicate they are input-only and not changed by the function. Return
118 parameters are best prefixed with "ret_", to clarify they are return
119 parameters. (Conversely, please do not prefix parameters that aren't
120 output-only with "ret_", in particular not mutable parameters that are both
121 input as well as output). Example:
122
123 ```c
124 static int foobar_frobnicate(
125 Foobar* object, /* the associated mutable object */
126 const char *input, /* immutable input parameter */
127 char **ret_frobnicated) { /* return parameter */
128
129 return 0;
130 }
131 ```
82143987 132
82143987 133- The order in which header files are included doesn't matter too
b4f12824
LP
134 much. systemd-internal headers must not rely on an include order, so it is
135 safe to include them in any order possible. However, to not clutter global
136 includes, and to make sure internal definitions will not affect global
137 headers, please always include the headers of external components first
138 (these are all headers enclosed in <>), followed by our own exported headers
139 (usually everything that's prefixed by `sd-`), and then followed by internal
140 headers. Furthermore, in all three groups, order all includes alphabetically
82143987
FA
141 so duplicate includes can easily be detected.
142
b4f12824
LP
143- Please avoid using global variables as much as you can. And if you do use
144 them make sure they are static at least, instead of exported. Especially in
145 library-like code it is important to avoid global variables. Why are global
146 variables bad? They usually hinder generic reusability of code (since they
147 break in threaded programs, and usually would require locking there), and as
148 the code using them has side-effects make programs non-transparent. That
149 said, there are many cases where they explicitly make a lot of sense, and are
150 OK to use. For example, the log level and target in `log.c` is stored in a
151 global variable, and that's OK and probably expected by most. Also in many
152 cases we cache data in global variables. If you add more caches like this,
153 please be careful however, and think about threading. Only use static
154 variables if you are sure that thread-safety doesn't matter in your
155 case. Alternatively, consider using TLS, which is pretty easy to use with
156 gcc's `thread_local` concept. It's also OK to store data that is inherently
157 global in global variables, for example data parsed from command lines, see
82143987
FA
158 below.
159
82143987
FA
160- Our focus is on the GNU libc (glibc), not any other libcs. If other libcs are
161 incompatible with glibc it's on them. However, if there are equivalent POSIX
162 and Linux/GNU-specific APIs, we generally prefer the POSIX APIs. If there
163 aren't, we are happy to use GNU or Linux APIs, and expect non-GNU
164 implementations of libc to catch up with glibc.
165
78e5b4d7
LP
166## Using C Constructs
167
756755d0 168- Allocate local variables where it makes sense: at the top of the block, or at
9214f299
ZJS
169 the point where they can be initialized. Avoid huge variable declaration
170 lists at the top of the function.
171
172 As an exception, `r` is typically used for a local state variable, but should
173 almost always be declared as the last variable at the top of the function.
78e5b4d7
LP
174
175 ```c
176 {
9214f299 177 uint64_t a;
756755d0 178 int r;
78e5b4d7 179
9214f299
ZJS
180 r = frobnicate(&a);
181 if (r < 0)
182
183
184 uint64_t b = a + 1, c;
756755d0 185
9214f299 186 r = foobarify(a, b, &c);
756755d0
ZJS
187 if (r < 0)
188
9214f299
ZJS
189
190 const char *pretty = prettify(a, b, c);
191
78e5b4d7
LP
192 }
193 ```
194
9214f299
ZJS
195- Do not mix multiple variable definitions with function invocations or
196 complicated expressions:
78e5b4d7
LP
197
198 ```c
199 {
78e5b4d7 200 uint64_t x = 7;
756755d0
ZJS
201 int a;
202
203 a = foobar();
78e5b4d7
LP
204 }
205 ```
206
756755d0 207 instead of:
78e5b4d7
LP
208
209 ```c
210 {
756755d0 211 int a = foobar();
78e5b4d7 212 uint64_t x = 7;
78e5b4d7
LP
213 }
214 ```
215
756755d0 216- Use `goto` for cleaning up, and only use it for that. I.e. you may only jump
78e5b4d7
LP
217 to the end of a function, and little else. Never jump backwards!
218
219- To minimize strict aliasing violations, we prefer unions over casting.
220
221- Instead of using `memzero()`/`memset()` to initialize structs allocated on
222 the stack, please try to use c99 structure initializers. It's short, prettier
223 and actually even faster at execution. Hence:
224
225 ```c
226 struct foobar t = {
227 .foo = 7,
228 .bar = "bazz",
229 };
230 ```
231
232 instead of:
233
234 ```c
235 struct foobar t;
236 zero(t);
237 t.foo = 7;
238 t.bar = "bazz";
239 ```
240
241- To implement an endless loop, use `for (;;)` rather than `while (1)`. The
242 latter is a bit ugly anyway, since you probably really meant `while
243 (true)`. To avoid the discussion what the right always-true expression for an
244 infinite while loop is, our recommendation is to simply write it without any
245 such expression by using `for (;;)`.
246
247- To determine the length of a constant string `"foo"`, don't bother with
248 `sizeof("foo")-1`, please use `strlen()` instead (both gcc and clang optimize
249 the call away for fixed strings). The only exception is when declaring an
9214f299 250 array. In that case use `STRLEN()`, which evaluates to a static constant and
78e5b4d7
LP
251 doesn't force the compiler to create a VLA.
252
b5bd7a29
LP
253- Please use C's downgrade-to-bool feature only for expressions that are
254 actually booleans (or "boolean-like"), and not for variables that are really
255 numeric. Specifically, if you have an `int b` and it's only used in a boolean
256 sense, by all means check its state with `if (b) …` — but if `b` can actually
257 have more than two semantic values, and you want to compare for non-zero,
d238709c 258 then please write that explicitly with `if (b != 0) …`. This helps readability
b5bd7a29
LP
259 as the value range and semantical behaviour is directly clear from the
260 condition check. As a special addition: when dealing with pointers which you
261 want to check for non-NULL-ness, you may also use downgrade-to-bool feature.
262
263- Please do not use yoda comparisons, i.e. please prefer the more readable `if
264 (a == 7)` over the less readable `if (7 == a)`.
265
c159efe3
LP
266## Destructors
267
268- The destructors always deregister the object from the next bigger object, not
269 the other way around.
270
271- For robustness reasons, destructors should be able to destruct
272 half-initialized objects, too.
273
274- When you define a destructor or `unref()` call for an object, please accept a
275 `NULL` object and simply treat this as NOP. This is similar to how libc
276 `free()` works, which accepts `NULL` pointers and becomes a NOP for them. By
277 following this scheme a lot of `if` checks can be removed before invoking
278 your destructor, which makes the code substantially more readable and robust.
279
280- Related to this: when you define a destructor or `unref()` call for an
281 object, please make it return the same type it takes and always return `NULL`
282 from it. This allows writing code like this:
283
284 ```c
285 p = foobar_unref(p);
286 ```
287
2d1b9281 288 which will always work regardless if `p` is initialized or not, and
c159efe3
LP
289 guarantees that `p` is `NULL` afterwards, all in just one line.
290
b065e1f1
LP
291## Error Handling
292
293- Error codes are returned as negative `Exxx`. e.g. `return -EINVAL`. There are
294 some exceptions: for constructors, it is OK to return `NULL` on OOM. For
295 lookup functions, `NULL` is fine too for "not found".
296
297 Be strict with this. When you write a function that can fail due to more than
298 one cause, it *really* should have an `int` as the return value for the error
299 code.
300
947796ea
LP
301- libc system calls typically return -1 on error (with the error code in
302 `errno`), and >= 0 on success. Use the RET_NERRNO() helper if you are looking
303 for a simple way to convert this libc style error returning into systemd
304 style error returning. e.g.
305
306 ```c
307
308 r = RET_NERRNO(unlink(t));
309
310 ```
311
312 or
313
314 ```c
315
316 r = RET_NERRNO(open("/some/file", O_RDONLY|O_CLOEXEC));
317
318 ```
319
b065e1f1
LP
320- Do not bother with error checking whether writing to stdout/stderr worked.
321
322- Do not log errors from "library" code, only do so from "main program"
323 code. (With one exception: it is OK to log with DEBUG level from any code,
324 with the exception of maybe inner loops).
325
326- In public API calls, you **must** validate all your input arguments for
327 programming error with `assert_return()` and return a sensible return
328 code. In all other calls, it is recommended to check for programming errors
329 with a more brutal `assert()`. We are more forgiving to public users than for
330 ourselves! Note that `assert()` and `assert_return()` really only should be
331 used for detecting programming errors, not for runtime errors. `assert()` and
be7148eb 332 `assert_return()` by usage of `_likely_()` inform the compiler that it should
b065e1f1
LP
333 not expect these checks to fail, and they inform fellow programmers about the
334 expected validity and range of parameters.
335
336- When you invoke certain calls like `unlink()`, or `mkdir_p()` and you know it
337 is safe to ignore the error it might return (because a later call would
338 detect the failure anyway, or because the error is in an error path and you
339 thus couldn't do anything about it anyway), then make this clear by casting
340 the invocation explicitly to `(void)`. Code checks like Coverity understand
341 that, and will not complain about ignored error codes. Hence, please use
342 this:
343
344 ```c
345 (void) unlink("/foo/bar/baz");
346 ```
347
348 instead of just this:
349
350 ```c
351 unlink("/foo/bar/baz");
352 ```
353
800d0802
AZ
354 When returning from a `void` function, you may also want to shorten the error
355 path boilerplate by returning a function invocation cast to `(void)` like so:
356
357 ```c
358 if (condition_not_met)
359 return (void) log_tests_skipped("Cannot run ...");
360 ```
361
b065e1f1
LP
362 Don't cast function calls to `(void)` that return no error
363 conditions. Specifically, the various `xyz_unref()` calls that return a
364 `NULL` object shouldn't be cast to `(void)`, since not using the return value
365 does not hide any errors.
366
367- When returning a return code from `main()`, please preferably use
368 `EXIT_FAILURE` and `EXIT_SUCCESS` as defined by libc.
369
96f6cfbf
LP
370## Logging
371
372- For every function you add, think about whether it is a "logging" function or
cf33b707 373 a "non-logging" function. "Logging" functions do (non-debug) logging on their
f223fd6a 374 own, "non-logging" functions never log on their own (except at debug level)
cf33b707
LP
375 and expect their callers to log. All functions in "library" code, i.e. in
376 `src/shared/` and suchlike must be "non-logging". Every time a "logging"
377 function calls a "non-logging" function, it should log about the resulting
378 errors. If a "logging" function calls another "logging" function, then it
379 should not generate log messages, so that log messages are not generated
380 twice for the same errors. (Note that debug level logging — at syslog level
381 `LOG_DEBUG` — is not considered logging in this context, debug logging is
382 generally always fine and welcome.)
96f6cfbf
LP
383
384- If possible, do a combined log & return operation:
385
386 ```c
387 r = operation(...);
388 if (r < 0)
389 return log_(error|warning|notice|...)_errno(r, "Failed to ...: %m");
390 ```
391
392 If the error value is "synthetic", i.e. it was not received from
393 the called function, use `SYNTHETIC_ERRNO` wrapper to tell the logging
394 system to not log the errno value, but still return it:
395
396 ```c
397 n = read(..., s, sizeof s);
398 if (n != sizeof s)
399 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read ...");
400 ```
401
04858240
LP
402## Memory Allocation
403
404- Always check OOM. There is no excuse. In program code, you can use
405 `log_oom()` for then printing a short message, but not in "library" code.
406
407- Avoid fixed-size string buffers, unless you really know the maximum size and
756755d0 408 that maximum size is small. It is often nicer to use dynamic memory,
e3bde912
LP
409 `alloca_safe()` or VLAs. If you do allocate fixed-size strings on the stack,
410 then it is probably only OK if you either use a maximum size such as
411 `LINE_MAX`, or count in detail the maximum size a string can
412 have. (`DECIMAL_STR_MAX` and `DECIMAL_STR_WIDTH` macros are your friends for
413 this!)
04858240
LP
414
415 Or in other words, if you use `char buf[256]` then you are likely doing
416 something wrong!
417
418- Make use of `_cleanup_free_` and friends. It makes your code much nicer to
419 read (and shorter)!
420
e3bde912
LP
421- Do not use `alloca()`, `strdupa()` or `strndupa()` directly. Use
422 `alloca_safe()`, `strdupa_safe()` or `strndupa_safe()` instead. (The
423 difference is that the latter include an assertion that the specified size is
424 below a safety threshold, so that the program rather aborts than runs into
425 possible stack overruns.)
426
427- Use `alloca_safe()`, but never forget that it is not OK to invoke
428 `alloca_safe()` within a loop or within function call
429 parameters. `alloca_safe()` memory is released at the end of a function, and
430 not at the end of a `{}` block. Thus, if you invoke it in a loop, you keep
431 increasing the stack pointer without ever releasing memory again. (VLAs have
432 better behavior in this case, so consider using them as an alternative.)
433 Regarding not using `alloca_safe()` within function parameters, see the BUGS
434 section of the `alloca(3)` man page.
04858240
LP
435
436- If you want to concatenate two or more strings, consider using `strjoina()`
437 or `strjoin()` rather than `asprintf()`, as the latter is a lot slower. This
438 matters particularly in inner loops (but note that `strjoina()` cannot be
439 used there).
440
4467d393
LP
441## Runtime Behaviour
442
443- Avoid leaving long-running child processes around, i.e. `fork()`s that are
444 not followed quickly by an `execv()` in the child. Resource management is
445 unclear in this case, and memory CoW will result in unexpected penalties in
446 the parent much, much later on.
447
448- Don't block execution for arbitrary amounts of time using `usleep()` or a
449 similar call, unless you really know what you do. Just "giving something some
450 time", or so is a lazy excuse. Always wait for the proper event, instead of
451 doing time-based poll loops.
452
453- Whenever installing a signal handler, make sure to set `SA_RESTART` for it,
454 so that interrupted system calls are automatically restarted, and we minimize
455 hassles with handling `EINTR` (in particular as `EINTR` handling is pretty
456 broken on Linux).
457
458- When applying C-style unescaping as well as specifier expansion on the same
c90b6abc 459 string, always apply the C-style unescaping first, followed by the specifier
4467d393
LP
460 expansion. When doing the reverse, make sure to escape `%` in specifier-style
461 first (i.e. `%` → `%%`), and then do C-style escaping where necessary.
462
463- Be exceptionally careful when formatting and parsing floating point
464 numbers. Their syntax is locale dependent (i.e. `5.000` in en_US is generally
465 understood as 5, while in de_DE as 5000.).
466
467- Make sure to enforce limits on every user controllable resource. If the user
468 can allocate resources in your code, your code must enforce some form of
469 limits after which it will refuse operation. It's fine if it is hard-coded
470 (at least initially), but it needs to be there. This is particularly
471 important for objects that unprivileged users may allocate, but also matters
6ae11e12 472 for everything else any user may allocate.
4467d393 473
f42c1cd4
LP
474## Types
475
476- Think about the types you use. If a value cannot sensibly be negative, do not
477 use `int`, but use `unsigned`.
478
479- Use `char` only for actual characters. Use `uint8_t` or `int8_t` when you
480 actually mean a byte-sized signed or unsigned integers. When referring to a
481 generic byte, we generally prefer the unsigned variant `uint8_t`. Do not use
482 types based on `short`. They *never* make sense. Use `int`, `long`, `long
483 long`, all in unsigned and signed fashion, and the fixed-size types
484 `uint8_t`, `uint16_t`, `uint32_t`, `uint64_t`, `int8_t`, `int16_t`, `int32_t`
485 and so on, as well as `size_t`, but nothing else. Do not use kernel types
486 like `u32` and so on, leave that to the kernel.
487
488- Stay uniform. For example, always use `usec_t` for time values. Do not mix
489 `usec` and `msec`, and `usec` and whatnot.
490
491- Never use the `off_t` type, and particularly avoid it in public APIs. It's
492 really weirdly defined, as it usually is 64-bit and we don't support it any
493 other way, but it could in theory also be 32-bit. Which one it is depends on
494 a compiler switch chosen by the compiled program, which hence corrupts APIs
495 using it unless they can also follow the program's choice. Moreover, in
496 systemd we should parse values the same way on all architectures and cannot
497 expose `off_t` values over D-Bus. To avoid any confusion regarding conversion
498 and ABIs, always use simply `uint64_t` directly.
499
500- Unless you allocate an array, `double` is always a better choice than
501 `float`. Processors speak `double` natively anyway, so there is no speed
502 benefit, and on calls like `printf()` `float`s get promoted to `double`s
503 anyway, so there is no point.
504
505- Use the bool type for booleans, not integers. One exception: in public
506 headers (i.e those in `src/systemd/sd-*.h`) use integers after all, as `bool`
40f55f69
LP
507 is C99 and in our public APIs we try to stick to C89 (with a few extensions;
508 also see above).
f42c1cd4 509
3b75e079
LP
510## Deadlocks
511
38b38500 512- Do not issue NSS requests (that includes user name and hostname lookups)
3b75e079
LP
513 from PID 1 as this might trigger deadlocks when those lookups involve
514 synchronously talking to services that we would need to start up.
515
516- Do not synchronously talk to any other service from PID 1, due to risk of
517 deadlocks.
518
25553cd9
LP
519## File Descriptors
520
521- When you allocate a file descriptor, it should be made `O_CLOEXEC` right from
522 the beginning, as none of our files should leak to forked binaries by
523 default. Hence, whenever you open a file, `O_CLOEXEC` must be specified,
524 right from the beginning. This also applies to sockets. Effectively, this
525 means that all invocations to:
526
527 - `open()` must get `O_CLOEXEC` passed,
528 - `socket()` and `socketpair()` must get `SOCK_CLOEXEC` passed,
529 - `recvmsg()` must get `MSG_CMSG_CLOEXEC` set,
530 - `F_DUPFD_CLOEXEC` should be used instead of `F_DUPFD`, and so on,
531 - invocations of `fopen()` should take `e`.
532
533- It's a good idea to use `O_NONBLOCK` when opening 'foreign' regular files,
534 i.e. file system objects that are supposed to be regular files whose paths
d0515a28 535 were specified by the user and hence might actually refer to other types of
25553cd9
LP
536 file system objects. This is a good idea so that we don't end up blocking on
537 'strange' file nodes, for example if the user pointed us to a FIFO or device
538 node which may block when opening. Moreover even for actual regular files
539 `O_NONBLOCK` has a benefit: it bypasses any mandatory lock that might be in
540 effect on the regular file. If in doubt consider turning off `O_NONBLOCK`
541 again after opening.
542
996f119d
LP
543## Command Line
544
545- If you parse a command line, and want to store the parsed parameters in
546 global variables, please consider prefixing their names with `arg_`. We have
547 been following this naming rule in most of our tools, and we should continue
548 to do so, as it makes it easy to identify command line parameter variables,
549 and makes it clear why it is OK that they are global variables.
550
551- Command line option parsing:
552 - Do not print full `help()` on error, be specific about the error.
553 - Do not print messages to stdout on error.
554 - Do not POSIX_ME_HARDER unless necessary, i.e. avoid `+` in option string.
555
56380761
LP
556## Exporting Symbols
557
558- Variables and functions **must** be static, unless they have a prototype, and
559 are supposed to be exported.
560
561- Public API calls (i.e. functions exported by our shared libraries)
562 must be marked `_public_` and need to be prefixed with `sd_`. No
563 other functions should be prefixed like that.
564
565- When exposing public C APIs, be careful what function parameters you make
566 `const`. For example, a parameter taking a context object should probably not
567 be `const`, even if you are writing an otherwise read-only accessor function
568 for it. The reason is that making it `const` fixates the contract that your
569 call won't alter the object ever, as part of the API. However, that's often
570 quite a promise, given that this even prohibits object-internal caching or
571 lazy initialization of object variables. Moreover, it's usually not too
572 useful for client applications. Hence, please be careful and avoid `const` on
573 object parameters, unless you are very sure `const` is appropriate.
574
971dfffa
LP
575## Referencing Concepts
576
82143987
FA
577- When referring to a configuration file option in the documentation and such,
578 please always suffix it with `=`, to indicate that it is a configuration file
579 setting.
580
581- When referring to a command line option in the documentation and such, please
582 always prefix with `--` or `-` (as appropriate), to indicate that it is a
583 command line option.
584
585- When referring to a file system path that is a directory, please always
586 suffix it with `/`, to indicate that it is a directory, not a regular file
587 (or other file system object).
588
2d0dce2a
LP
589## Functions to Avoid
590
591- Use `memzero()` or even better `zero()` instead of `memset(..., 0, ...)`
592
593- Please use `streq()` and `strneq()` instead of `strcmp()`, `strncmp()` where
594 applicable (i.e. wherever you just care about equality/inequality, not about
595 the sorting order).
596
597- Never use `strtol()`, `atoi()` and similar calls. Use `safe_atoli()`,
598 `safe_atou32()` and suchlike instead. They are much nicer to use in most
599 cases and correctly check for parsing errors.
600
601- `htonl()`/`ntohl()` and `htons()`/`ntohs()` are weird. Please use `htobe32()`
602 and `htobe16()` instead, it's much more descriptive, and actually says what
603 really is happening, after all `htonl()` and `htons()` don't operate on
604 `long`s and `short`s as their name would suggest, but on `uint32_t` and
605 `uint16_t`. Also, "network byte order" is just a weird name for "big endian",
606 hence we might want to call it "big endian" right-away.
607
608- Please never use `dup()`. Use `fcntl(fd, F_DUPFD_CLOEXEC, 3)` instead. For
c1495f8e 609 two reasons: first, you want `O_CLOEXEC` set on the new `fd` (see
2d0dce2a
LP
610 above). Second, `dup()` will happily duplicate your `fd` as 0, 1, 2,
611 i.e. stdin, stdout, stderr, should those `fd`s be closed. Given the special
612 semantics of those `fd`s, it's probably a good idea to avoid
613 them. `F_DUPFD_CLOEXEC` with `3` as parameter avoids them.
614
82143987
FA
615- Don't use `fgets()`, it's too hard to properly handle errors such as overly
616 long lines. Use `read_line()` instead, which is our own function that handles
c90b6abc 617 this much more nicely.
2d0dce2a
LP
618
619- Don't invoke `exit()`, ever. It is not replacement for proper error
620 handling. Please escalate errors up your call chain, and use normal `return`
621 to exit from the main function of a process. If you `fork()`ed off a child
622 process, please use `_exit()` instead of `exit()`, so that the exit handlers
623 are not run.
624
6ae11e12 625- We never use the POSIX version of `basename()` (which glibc defines in
2d0dce2a
LP
626 `libgen.h`), only the GNU version (which glibc defines in `string.h`). The
627 only reason to include `libgen.h` is because `dirname()` is needed. Every
628 time you need that please immediately undefine `basename()`, and add a
629 comment about it, so that no code ever ends up using the POSIX version!
831781b9 630
bcef0f33
ZJS
631- Never use `FILENAME_MAX`. Use `PATH_MAX` instead (for checking maximum size
632 of paths) and `NAME_MAX` (for checking maximum size of filenames).
633 `FILENAME_MAX` is not POSIX, and is a confusingly named alias for `PATH_MAX`
6ae11e12 634 on Linux. Note that `NAME_MAX` does not include space for a trailing `NUL`,
bcef0f33 635 but `PATH_MAX` does. UNIX FTW!
b775b182 636
ff2c2d08 637## Committing to git
831781b9
LP
638
639- Commit message subject lines should be prefixed with an appropriate component
640 name of some kind. For example "journal: ", "nspawn: " and so on.
641
642- Do not use "Signed-Off-By:" in your commit messages. That's a kernel thing we
643 don't do in the systemd project.