You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

441 lines
19 KiB

  1. - 8ch indent, no tabs, except for files in man/ which are 2ch indent,
  2. and still no tabs
  3. - We prefer /* comments */ over // comments, please. This is not C++, after
  4. all. (Yes we know that C99 supports both kinds of comments, but still,
  5. please!)
  6. - Don't break code lines too eagerly. We do *not* force line breaks at
  7. 80ch, all of today's screens should be much larger than that. But
  8. then again, don't overdo it, ~119ch should be enough really.
  9. - Variables and functions *must* be static, unless they have a
  10. prototype, and are supposed to be exported.
  11. - structs in MixedCase (with exceptions, such as public API structs),
  12. variables + functions in lower_case.
  13. - The destructors always unregister the object from the next bigger
  14. object, not the other way around
  15. - To minimize strict aliasing violations, we prefer unions over casting
  16. - For robustness reasons, destructors should be able to destruct
  17. half-initialized objects, too
  18. - Error codes are returned as negative Exxx. e.g. return -EINVAL. There
  19. are some exceptions: for constructors, it is OK to return NULL on
  20. OOM. For lookup functions, NULL is fine too for "not found".
  21. Be strict with this. When you write a function that can fail due to
  22. more than one cause, it *really* should have "int" as return value
  23. for the error code.
  24. - Do not bother with error checking whether writing to stdout/stderr
  25. worked.
  26. - Do not log errors from "library" code, only do so from "main
  27. program" code. (With one exception: it is OK to log with DEBUG level
  28. from any code, with the exception of maybe inner loops).
  29. - Always check OOM. There is no excuse. In program code, you can use
  30. "log_oom()" for then printing a short message, but not in "library" code.
  31. - Do not issue NSS requests (that includes user name and host name
  32. lookups) from PID 1 as this might trigger deadlocks when those
  33. lookups involve synchronously talking to services that we would need
  34. to start up
  35. - Do not synchronously talk to any other service from PID 1, due to
  36. risk of deadlocks
  37. - Avoid fixed-size string buffers, unless you really know the maximum
  38. size and that maximum size is small. They are a source of errors,
  39. since they possibly result in truncated strings. It is often nicer
  40. to use dynamic memory, alloca() or VLAs. If you do allocate fixed-size
  41. strings on the stack, then it is probably only OK if you either
  42. use a maximum size such as LINE_MAX, or count in detail the maximum
  43. size a string can have. (DECIMAL_STR_MAX and DECIMAL_STR_WIDTH
  44. macros are your friends for this!)
  45. Or in other words, if you use "char buf[256]" then you are likely
  46. doing something wrong!
  47. - Stay uniform. For example, always use "usec_t" for time
  48. values. Do not mix usec and msec, and usec and whatnot.
  49. - Make use of _cleanup_free_ and friends. It makes your code much
  50. nicer to read!
  51. - Be exceptionally careful when formatting and parsing floating point
  52. numbers. Their syntax is locale dependent (i.e. "5.000" in en_US is
  53. generally understood as 5, while on de_DE as 5000.).
  54. - Try to use this:
  55. void foo() {
  56. }
  57. instead of this:
  58. void foo()
  59. {
  60. }
  61. But it is OK if you do not.
  62. - Single-line "if" blocks should not be enclosed in {}. Use this:
  63. if (foobar)
  64. waldo();
  65. instead of this:
  66. if (foobar) {
  67. waldo();
  68. }
  69. - Do not write "foo ()", write "foo()".
  70. - Please use streq() and strneq() instead of strcmp(), strncmp() where applicable.
  71. - Please do not allocate variables on the stack in the middle of code,
  72. even if C99 allows it. Wrong:
  73. {
  74. a = 5;
  75. int b;
  76. b = a;
  77. }
  78. Right:
  79. {
  80. int b;
  81. a = 5;
  82. b = a;
  83. }
  84. - Unless you allocate an array, "double" is always the better choice
  85. than "float". Processors speak "double" natively anyway, so this is
  86. no speed benefit, and on calls like printf() "float"s get promoted
  87. to "double"s anyway, so there is no point.
  88. - Do not mix function invocations with variable definitions in one
  89. line. Wrong:
  90. {
  91. int a = foobar();
  92. uint64_t x = 7;
  93. }
  94. Right:
  95. {
  96. int a;
  97. uint64_t x = 7;
  98. a = foobar();
  99. }
  100. - Use "goto" for cleaning up, and only use it for that. i.e. you may
  101. only jump to the end of a function, and little else. Never jump
  102. backwards!
  103. - Think about the types you use. If a value cannot sensibly be
  104. negative, do not use "int", but use "unsigned".
  105. - Use "char" only for actual characters. Use "uint8_t" or "int8_t"
  106. when you actually mean a byte-sized signed or unsigned
  107. integers. When referring to a generic byte, we generally prefer the
  108. unsigned variant "uint8_t". Do not use types based on "short". They
  109. *never* make sense. Use ints, longs, long longs, all in
  110. unsigned+signed fashion, and the fixed size types
  111. uint8_t/uint16_t/uint32_t/uint64_t/int8_t/int16_t/int32_t and so on,
  112. as well as size_t, but nothing else. Do not use kernel types like
  113. u32 and so on, leave that to the kernel.
  114. - Public API calls (i.e. functions exported by our shared libraries)
  115. must be marked "_public_" and need to be prefixed with "sd_". No
  116. other functions should be prefixed like that.
  117. - In public API calls, you *must* validate all your input arguments for
  118. programming error with assert_return() and return a sensible return
  119. code. In all other calls, it is recommended to check for programming
  120. errors with a more brutal assert(). We are more forgiving to public
  121. users than for ourselves! Note that assert() and assert_return()
  122. really only should be used for detecting programming errors, not for
  123. runtime errors. assert() and assert_return() by usage of _likely_()
  124. inform the compiler that he should not expect these checks to fail,
  125. and they inform fellow programmers about the expected validity and
  126. range of parameters.
  127. - Never use strtol(), atoi() and similar calls. Use safe_atoli(),
  128. safe_atou32() and suchlike instead. They are much nicer to use in
  129. most cases and correctly check for parsing errors.
  130. - For every function you add, think about whether it is a "logging"
  131. function or a "non-logging" function. "Logging" functions do logging
  132. on their own, "non-logging" function never log on their own and
  133. expect their callers to log. All functions in "library" code,
  134. i.e. in src/shared/ and suchlike must be "non-logging". Every time a
  135. "logging" function calls a "non-logging" function, it should log
  136. about the resulting errors. If a "logging" function calls another
  137. "logging" function, then it should not generate log messages, so
  138. that log messages are not generated twice for the same errors.
  139. - Avoid static variables, except for caches and very few other
  140. cases. Think about thread-safety! While most of our code is never
  141. used in threaded environments, at least the library code should make
  142. sure it works correctly in them. Instead of doing a lot of locking
  143. for that, we tend to prefer using TLS to do per-thread caching (which
  144. only works for small, fixed-size cache objects), or we disable
  145. caching for any thread that is not the main thread. Use
  146. is_main_thread() to detect whether the calling thread is the main
  147. thread.
  148. - Command line option parsing:
  149. - Do not print full help() on error, be specific about the error.
  150. - Do not print messages to stdout on error.
  151. - Do not POSIX_ME_HARDER unless necessary, i.e. avoid "+" in option string.
  152. - Do not write functions that clobber call-by-reference variables on
  153. failure. Use temporary variables for these cases and change the
  154. passed in variables only on success.
  155. - When you allocate a file descriptor, it should be made O_CLOEXEC
  156. right from the beginning, as none of our files should leak to forked
  157. binaries by default. Hence, whenever you open a file, O_CLOEXEC must
  158. be specified, right from the beginning. This also applies to
  159. sockets. Effectively this means that all invocations to:
  160. a) open() must get O_CLOEXEC passed
  161. b) socket() and socketpair() must get SOCK_CLOEXEC passed
  162. c) recvmsg() must get MSG_CMSG_CLOEXEC set
  163. d) F_DUPFD_CLOEXEC should be used instead of F_DUPFD, and so on
  164. f) invocations of fopen() should take "e"
  165. - We never use the POSIX version of basename() (which glibc defines it in
  166. libgen.h), only the GNU version (which glibc defines in string.h).
  167. The only reason to include libgen.h is because dirname()
  168. is needed. Every time you need that please immediately undefine
  169. basename(), and add a comment about it, so that no code ever ends up
  170. using the POSIX version!
  171. - Use the bool type for booleans, not integers. One exception: in public
  172. headers (i.e those in src/systemd/sd-*.h) use integers after all, as "bool"
  173. is C99 and in our public APIs we try to stick to C89 (with a few extension).
  174. - When you invoke certain calls like unlink(), or mkdir_p() and you
  175. know it is safe to ignore the error it might return (because a later
  176. call would detect the failure anyway, or because the error is in an
  177. error path and you thus couldn't do anything about it anyway), then
  178. make this clear by casting the invocation explicitly to (void). Code
  179. checks like Coverity understand that, and will not complain about
  180. ignored error codes. Hence, please use this:
  181. (void) unlink("/foo/bar/baz");
  182. instead of just this:
  183. unlink("/foo/bar/baz");
  184. Don't cast function calls to (void) that return no error
  185. conditions. Specifically, the various xyz_unref() calls that return a NULL
  186. object shouldn't be cast to (void), since not using the return value does not
  187. hide any errors.
  188. - Don't invoke exit(), ever. It is not replacement for proper error
  189. handling. Please escalate errors up your call chain, and use normal
  190. "return" to exit from the main function of a process. If you
  191. fork()ed off a child process, please use _exit() instead of exit(),
  192. so that the exit handlers are not run.
  193. - Please never use dup(). Use fcntl(fd, F_DUPFD_CLOEXEC, 3)
  194. instead. For two reason: first, you want O_CLOEXEC set on the new fd
  195. (see above). Second, dup() will happily duplicate your fd as 0, 1,
  196. 2, i.e. stdin, stdout, stderr, should those fds be closed. Given the
  197. special semantics of those fds, it's probably a good idea to avoid
  198. them. F_DUPFD_CLOEXEC with "3" as parameter avoids them.
  199. - When you define a destructor or unref() call for an object, please
  200. accept a NULL object and simply treat this as NOP. This is similar
  201. to how libc free() works, which accepts NULL pointers and becomes a
  202. NOP for them. By following this scheme a lot of if checks can be
  203. removed before invoking your destructor, which makes the code
  204. substantially more readable and robust.
  205. - Related to this: when you define a destructor or unref() call for an
  206. object, please make it return the same type it takes and always
  207. return NULL from it. This allows writing code like this:
  208. p = foobar_unref(p);
  209. which will always work regardless if p is initialized or not, and
  210. guarantees that p is NULL afterwards, all in just one line.
  211. - Use alloca(), but never forget that it is not OK to invoke alloca()
  212. within a loop or within function call parameters. alloca() memory is
  213. released at the end of a function, and not at the end of a {}
  214. block. Thus, if you invoke it in a loop, you keep increasing the
  215. stack pointer without ever releasing memory again. (VLAs have better
  216. behaviour in this case, so consider using them as an alternative.)
  217. Regarding not using alloca() within function parameters, see the
  218. BUGS section of the alloca(3) man page.
  219. - Use memzero() or even better zero() instead of memset(..., 0, ...)
  220. - Instead of using memzero()/memset() to initialize structs allocated
  221. on the stack, please try to use c99 structure initializers. It's
  222. short, prettier and actually even faster at execution. Hence:
  223. struct foobar t = {
  224. .foo = 7,
  225. .bar = "bazz",
  226. };
  227. instead of:
  228. struct foobar t;
  229. zero(t);
  230. = 7;
  231. = "bazz";
  232. - When returning a return code from main(), please preferably use
  233. EXIT_FAILURE and EXIT_SUCCESS as defined by libc.
  234. - The order in which header files are included doesn't matter too
  235. much. systemd-internal headers must not rely on an include order, so
  236. it is safe to include them in any order possible.
  237. However, to not clutter global includes, and to make sure internal
  238. definitions will not affect global headers, please always include the
  239. headers of external components first (these are all headers enclosed
  240. in <>), followed by our own exported headers (usually everything
  241. that's prefixed by "sd-"), and then followed by internal headers.
  242. Furthermore, in all three groups, order all includes alphabetically
  243. so duplicate includes can easily be detected.
  244. - To implement an endless loop, use "for (;;)" rather than "while
  245. (1)". The latter is a bit ugly anyway, since you probably really
  246. meant "while (true)"... To avoid the discussion what the right
  247. always-true expression for an infinite while() loop is our
  248. recommendation is to simply write it without any such expression by
  249. using "for (;;)".
  250. - Never use the "off_t" type, and particularly avoid it in public
  251. APIs. It's really weirdly defined, as it usually is 64bit and we
  252. don't support it any other way, but it could in theory also be
  253. 32bit. Which one it is depends on a compiler switch chosen by the
  254. compiled program, which hence corrupts APIs using it unless they can
  255. also follow the program's choice. Moreover, in systemd we should
  256. parse values the same way on all architectures and cannot expose
  257. off_t values over D-Bus. To avoid any confusion regarding conversion
  258. and ABIs, always use simply uint64_t directly.
  259. - Commit message subject lines should be prefixed with an appropriate
  260. component name of some kind. For example "journal: ", "nspawn: " and
  261. so on.
  262. - Do not use "Signed-Off-By:" in your commit messages. That's a kernel
  263. thing we don't do in the systemd project.
  264. - Avoid leaving long-running child processes around, i.e. fork()s that
  265. are not followed quickly by an execv() in the child. Resource
  266. management is unclear in this case, and memory CoW will result in
  267. unexpected penalties in the parent much much later on.
  268. - Don't block execution for arbitrary amounts of time using usleep()
  269. or a similar call, unless you really know what you do. Just "giving
  270. something some time", or so is a lazy excuse. Always wait for the
  271. proper event, instead of doing time-based poll loops.
  272. - To determine the length of a constant string "foo", don't bother
  273. with sizeof("foo")-1, please use STRLEN() instead.
  274. - If you want to concatenate two or more strings, consider using
  275. strjoin() rather than asprintf(), as the latter is a lot
  276. slower. This matters particularly in inner loops.
  277. - Please avoid using global variables as much as you can. And if you
  278. do use them make sure they are static at least, instead of
  279. exported. Especially in library-like code it is important to avoid
  280. global variables. Why are global variables bad? They usually hinder
  281. generic reusability of code (since they break in threaded programs,
  282. and usually would require locking there), and as the code using them
  283. has side-effects make programs non-transparent. That said, there are
  284. many cases where they explicitly make a lot of sense, and are OK to
  285. use. For example, the log level and target in log.c is stored in a
  286. global variable, and that's OK and probably expected by most. Also
  287. in many cases we cache data in global variables. If you add more
  288. caches like this, please be careful however, and think about
  289. threading. Only use static variables if you are sure that
  290. thread-safety doesn't matter in your case. Alternatively consider
  291. using TLS, which is pretty easy to use with gcc's "thread_local"
  292. concept. It's also OK to store data that is inherently global in
  293. global variables, for example data parsed from command lines, see
  294. below.
  295. - If you parse a command line, and want to store the parsed parameters
  296. in global variables, please consider prefixing their names with
  297. "arg_". We have been following this naming rule in most of our
  298. tools, and we should continue to do so, as it makes it easy to
  299. identify command line parameter variables, and makes it clear why it
  300. is OK that they are global variables.
  301. - When exposing public C APIs, be careful what function parameters you make
  302. "const". For example, a parameter taking a context object should probably not
  303. be "const", even if you are writing an otherwise read-only accessor function
  304. for it. The reason is that making it "const" fixates the contract that your
  305. call won't alter the object ever, as part of the API. However, that's often
  306. quite a promise, given that this even prohibits object-internal caching or
  307. lazy initialization of object variables. Moreover it's usually not too useful
  308. for client applications. Hence: please be careful and avoid "const" on object
  309. parameters, unless you are very sure "const" is appropriate.
  310. - Make sure to enforce limits on every user controllable resource. If the user
  311. can allocate resources in your code, your code must enforce some form of
  312. limits after which it will refuse operation. It's fine if it is hard-coded (at
  313. least initially), but it needs to be there. This is particularly important
  314. for objects that unprivileged users may allocate, but also matters for
  315. everything else any user may allocated.
  316. - htonl()/ntohl() and htons()/ntohs() are weird. Please use htobe32() and
  317. htobe16() instead, it's much more descriptive, and actually says what really
  318. is happening, after all htonl() and htons() don't operate on longs and
  319. shorts as their name would suggest, but on uint32_t and uint16_t. Also,
  320. "network byte order" is just a weird name for "big endian", hence we might
  321. want to call it "big endian" right-away.
  322. - You might wonder what kind of common code belongs in src/shared/ and what
  323. belongs in src/basic/. The split is like this: anything that uses public APIs
  324. we expose (i.e. any of the sd-bus, sd-login, sd-id128, ... APIs) must be
  325. located in src/shared/. All stuff that only uses external libraries from
  326. other projects (such as glibc's APIs), or APIs from src/basic/ itself should
  327. be placed in src/basic/. Conversely, src/libsystemd/ may only use symbols
  328. from src/basic, but not from src/shared/. To summarize:
  329. src/basic/ → may be used by all code in the tree
  330. → may not use any code outside of src/basic/
  331. src/libsystemd/ → may be used by all code in the tree, except for code in src/basic/
  332. → may not use any code outside of src/basic/, src/libsystemd/
  333. src/shared/ → may be used by all code in the tree, except for code in src/basic/, src/libsystemd/
  334. → may not use any code outside of src/basic/, src/libsystemd/, src/shared/
  335. - Our focus is on the GNU libc (glibc), not any other libcs. If other libcs are
  336. incompatible with glibc it's on them. However, if there are equivalent POSIX
  337. and Linux/GNU-specific APIs, we generally prefer the POSIX APIs. If there
  338. aren't, we are happy to use GNU or Linux APIs, and expect non-GNU
  339. implementations of libc to catch up with glibc.
  340. - Whenever installing a signal handler, make sure to set SA_RESTART for it, so
  341. that interrupted system calls are automatically restarted, and we minimize
  342. hassles with handling EINTR (in particular as EINTR handling is pretty broken
  343. on Linux).
  344. - When applying C-style unescaping as well as specifier expansion on the same
  345. string, always apply the C-style unescaping fist, followed by the specifier
  346. expansion. When doing the reverse, make sure to escape '%' in specifier-style
  347. first (i.e. '%' → '%%'), and then do C-style escaping where necessary.