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