]> git.ipfire.org Git - thirdparty/systemd.git/blob - docs/HACKING.md
Merge pull request #29529 from yuwata/core-namespace-check-priv
[thirdparty/systemd.git] / docs / HACKING.md
1 ---
2 title: Hacking on systemd
3 category: Contributing
4 layout: default
5 SPDX-License-Identifier: LGPL-2.1-or-later
6 ---
7
8 # Hacking on systemd
9
10 We welcome all contributions to systemd. If you notice a bug or a missing
11 feature, please feel invited to fix it, and submit your work as a
12 [GitHub Pull Request (PR)](https://github.com/systemd/systemd/pull/new).
13
14 Please make sure to follow our [Coding Style](CODING_STYLE.md) when submitting
15 patches. Also have a look at our [Contribution Guidelines](CONTRIBUTING.md).
16
17 When adding new functionality, tests should be added. For shared functionality
18 (in `src/basic/` and `src/shared/`) unit tests should be sufficient. The general
19 policy is to keep tests in matching files underneath `src/test/`,
20 e.g. `src/test/test-path-util.c` contains tests for any functions in
21 `src/basic/path-util.c`. If adding a new source file, consider adding a matching
22 test executable. For features at a higher level, tests in `src/test/` are very
23 strongly recommended. If that is not possible, integration tests in `test/` are
24 encouraged.
25
26 Please also have a look at our list of [code quality tools](CODE_QUALITY.md) we
27 have setup for systemd, to ensure our codebase stays in good shape.
28
29 Please always test your work before submitting a PR. For many of the components
30 of systemd testing is straightforward as you can simply compile systemd and
31 run the relevant tool from the build directory.
32
33 For some components (most importantly, systemd/PID 1 itself) this is not
34 possible, however. In order to simplify testing for cases like this we provide
35 a set of `mkosi` build files directly in the source tree.
36 [mkosi](https://github.com/systemd/mkosi) is a tool for building clean OS images
37 from an upstream distribution in combination with a fresh build of the project
38 in the local working directory. To make use of this, please install `mkosi` v18
39 or newer using your distribution's package manager or from the
40 [GitHub repository](https://github.com/systemd/mkosi). `mkosi` will build an
41 image for the host distro by default. First, run `mkosi genkey` to generate a key
42 and certificate to be used for secure boot and verity signing. After that is done,
43 it is sufficient to type `mkosi` in the systemd project directory to generate a disk
44 image you can boot either in `systemd-nspawn` or in a UEFI-capable VM:
45
46 ```sh
47 $ sudo mkosi boot # nspawn still needs sudo for now
48 ```
49
50 or:
51
52 ```sh
53 $ mkosi qemu
54 ```
55
56 Every time you rerun the `mkosi` command a fresh image is built, incorporating
57 all current changes you made to the project tree.
58
59 Putting this all together, here's a series of commands for preparing a patch
60 for systemd:
61
62 ```sh
63 $ git clone https://github.com/systemd/mkosi.git # If mkosi v18 or newer is not packaged by your distribution
64 $ ln -s $PWD/mkosi/bin/mkosi /usr/local/bin/mkosi # If mkosi v18 or newer is not packaged by your distribution
65 $ git clone https://github.com/systemd/systemd.git
66 $ cd systemd
67 $ git checkout -b <BRANCH> # where BRANCH is the name of the branch
68 $ vim src/core/main.c # or wherever you'd like to make your changes
69 $ mkosi -f qemu # (re-)build and boot up the test image in qemu
70 $ git add -p # interactively put together your patch
71 $ git commit # commit it
72 $ git push -u <REMOTE> # where REMOTE is your "fork" on GitHub
73 ```
74
75 And after that, head over to your repo on GitHub and click "Compare & pull request"
76
77 If you want to do a local build without mkosi, most distributions also provide
78 very simple and convenient ways to install most development packages necessary
79 to build systemd:
80
81 ```sh
82 # Fedora
83 $ sudo dnf builddep systemd
84 # Debian/Ubuntu
85 $ sudo apt-get build-dep systemd
86 # Arch
87 $ sudo pacman -S devtools
88 $ pkgctl repo clone --protocol=https systemd
89 $ cd systemd
90 $ makepkg -seoc
91 ```
92
93 After installing the development packages, systemd can be built from source as follows:
94
95 ```sh
96 $ meson setup build <options>
97 $ ninja -C build
98 $ meson test -C build
99 ```
100
101 Happy hacking!
102
103 ## Templating engines in .in files
104
105 Some source files are generated during build. We use two templating engines:
106 * meson's `configure_file()` directive uses syntax with `@VARIABLE@`.
107
108 See the
109 [Meson docs for `configure_file()`](https://mesonbuild.com/Reference-manual.html#configure_file)
110 for details.
111
112 {% raw %}
113 * most files are rendered using jinja2, with `{{VARIABLE}}` and `{% if … %}`,
114 `{% elif … %}`, `{% else … %}`, `{% endif … %}` blocks. `{# … #}` is a
115 jinja2 comment, i.e. that block will not be visible in the rendered
116 output. `{% raw %} … `{% endraw %}`{{ '{' }}{{ '% endraw %' }}}` creates a block
117 where jinja2 syntax is not interpreted.
118
119 See the
120 [Jinja Template Designer Documentation](https://jinja2docs.readthedocs.io/en/stable/templates.html#synopsis)
121 for details.
122
123 Please note that files for both template engines use the `.in` extension.
124
125 ## Developer and release modes
126
127 In the default meson configuration (`-Dmode=developer`), certain checks are
128 enabled that are suitable when hacking on systemd (such as internal
129 documentation consistency checks). Those are not useful when compiling for
130 distribution and can be disabled by setting `-Dmode=release`.
131
132 ## Sanitizers in mkosi
133
134 See [Testing systemd using sanitizers](TESTING_WITH_SANITIZERS.md) for more information
135 on how to build with sanitizers enabled in mkosi.
136
137 ## Fuzzers
138
139 systemd includes fuzzers in `src/fuzz/` that use libFuzzer and are automatically
140 run by [OSS-Fuzz](https://github.com/google/oss-fuzz) with sanitizers.
141 To add a fuzz target, create a new `src/fuzz/fuzz-foo.c` file with a `LLVMFuzzerTestOneInput`
142 function and add it to the list in `src/fuzz/meson.build`.
143
144 Whenever possible, a seed corpus and a dictionary should also be added with new
145 fuzz targets. The dictionary should be named `src/fuzz/fuzz-foo.dict` and the seed
146 corpus should be built and exported as `$OUT/fuzz-foo_seed_corpus.zip` in
147 `tools/oss-fuzz.sh`.
148
149 The fuzzers can be built locally if you have libFuzzer installed by running
150 `tools/oss-fuzz.sh`, or by running:
151
152 ```
153 CC=clang CXX=clang++ \
154 meson setup build-libfuzz -Dllvm-fuzz=true -Db_sanitize=address,undefined -Db_lundef=false \
155 -Dc_args='-fno-omit-frame-pointer -DFUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION'
156 ninja -C build-libfuzz fuzzers
157 ```
158
159 Each fuzzer then can be then run manually together with a directory containing
160 the initial corpus:
161
162 ```
163 export UBSAN_OPTIONS=print_stacktrace=1:print_summary=1:halt_on_error=1
164 build-libfuzz/fuzz-varlink-idl test/fuzz/fuzz-varlink-idl/
165 ```
166
167 Note: the `halt_on_error=1` UBSan option is especially important, otherwise
168 the fuzzer won't crash when undefined behavior is triggered.
169
170 You should also confirm that the fuzzers can be built and run using
171 [the OSS-Fuzz toolchain](https://google.github.io/oss-fuzz/advanced-topics/reproducing/#building-using-docker):
172
173 ```
174 path_to_systemd=...
175
176 git clone --depth=1 https://github.com/google/oss-fuzz
177 cd oss-fuzz
178
179 for sanitizer in address undefined memory; do
180 for engine in libfuzzer afl honggfuzz; do
181 ./infra/helper.py build_fuzzers --sanitizer "$sanitizer" --engine "$engine" \
182 --clean systemd "$path_to_systemd"
183
184 ./infra/helper.py check_build --sanitizer "$sanitizer" --engine "$engine" \
185 -e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0 systemd
186 done
187 done
188
189 ./infra/helper.py build_fuzzers --clean --architecture i386 systemd "$path_to_systemd"
190 ./infra/helper.py check_build --architecture i386 -e ALLOWED_BROKEN_TARGETS_PERCENTAGE=0 systemd
191
192 ./infra/helper.py build_fuzzers --clean --sanitizer coverage systemd "$path_to_systemd"
193 ./infra/helper.py coverage --no-corpus-download systemd
194 ```
195
196 If you find a bug that impacts the security of systemd, please follow the
197 guidance in [CONTRIBUTING.md](CONTRIBUTING.md) on how to report a security vulnerability.
198
199 For more details on building fuzzers and integrating with OSS-Fuzz, visit:
200
201 - [Setting up a new project - OSS-Fuzz](https://google.github.io/oss-fuzz/getting-started/new-project-guide/)
202 - [Tutorials - OSS-Fuzz](https://google.github.io/oss-fuzz/reference/useful-links/#tutorials)
203
204 ## Debugging binaries that need to run as root in vscode
205
206 When trying to debug binaries that need to run as root, we need to do some custom configuration in vscode to
207 have it try to run the applications as root and to ask the user for the root password when trying to start
208 the binary. To achieve this, we'll use a custom debugger path which points to a script that starts `gdb` as
209 root using `pkexec`. pkexec will prompt the user for their root password via a graphical interface. This
210 guide assumes the C/C++ extension is used for debugging.
211
212 First, create a file `sgdb` in the root of the systemd repository with the following contents and make it
213 executable:
214
215 ```
216 #!/bin/sh
217 exec pkexec gdb "$@"
218 ```
219
220 Then, open launch.json in vscode, and set `miDebuggerPath` to `${workspaceFolder}/sgdb` for the corresponding
221 debug configuration. Now, whenever you try to debug the application, vscode will try to start gdb as root via
222 pkexec which will prompt you for your password via a graphical interface. After entering your password,
223 vscode should be able to start debugging the application.
224
225 For more information on how to set up a debug configuration for C binaries, please refer to the official
226 vscode documentation [here](https://code.visualstudio.com/docs/cpp/launch-json-reference)
227
228 ## Debugging systemd with mkosi + vscode
229
230 To simplify debugging systemd when testing changes using mkosi, we're going to show how to attach
231 [VSCode](https://code.visualstudio.com/)'s debugger to an instance of systemd running in a mkosi image using
232 QEMU.
233
234 To allow VSCode's debugger to attach to systemd running in a mkosi image, we have to make sure it can access
235 the virtual machine spawned by mkosi where systemd is running. mkosi makes this possible via a handy SSH
236 option that makes the generated image accessible via SSH when booted. Thus you must build the image with
237 `mkosi --ssh`. The easiest way to set the option is to create a file `mkosi.conf` in the root of the
238 repository and add the following contents:
239
240 ```
241 [Host]
242 Ssh=yes
243 RuntimeTrees=.
244 ```
245
246 Also make sure that the SSH agent is running on your system and that you've added your SSH key to it with
247 `ssh-add`. Also make sure that `virtiofsd` is installed.
248
249 After rebuilding the image and booting it with `mkosi qemu`, you should now be able to connect to it by
250 running `mkosi ssh` from the same directory in another terminal window.
251
252 Now we need to configure VSCode. First, make sure the C/C++ extension is installed. If you're already using
253 a different extension for code completion and other IDE features for C in VSCode, make sure to disable the
254 corresponding parts of the C/C++ extension in your VSCode user settings by adding the following entries:
255
256 ```json
257 "C_Cpp.formatting": "Disabled",
258 "C_Cpp.intelliSenseEngine": "Disabled",
259 "C_Cpp.enhancedColorization": "Disabled",
260 "C_Cpp.suggestSnippets": false,
261 ```
262
263 With the extension set up, we can create the launch.json file in the .vscode/ directory to tell the VSCode
264 debugger how to attach to the systemd instance running in our mkosi container/VM. Create the file, and possibly
265 the directory, and add the following contents:
266
267 ```json
268 {
269 "version": "0.2.0",
270 "configurations": [
271 {
272 "type": "cppdbg",
273 "program": "/usr/lib/systemd/systemd",
274 "processId": "${command:pickRemoteProcess}",
275 "request": "attach",
276 "name": "systemd",
277 "pipeTransport": {
278 "pipeProgram": "mkosi",
279 "pipeArgs": [
280 "-C",
281 "/path/to/systemd/repo/directory/on/host/system/",
282 "ssh"
283 ],
284 "debuggerPath": "/usr/bin/gdb"
285 },
286 "MIMode": "gdb",
287 "sourceFileMap": {
288 "/root/src/systemd": {
289 "editorPath": "${workspaceFolder}",
290 "useForBreakpoints": false
291 },
292 }
293 }
294 ]
295 }
296 ```
297
298 Now that the debugger knows how to connect to our process in the container/VM and we've set up the necessary
299 source mappings, go to the "Run and Debug" window and run the "systemd" debug configuration. If everything
300 goes well, the debugger should now be attached to the systemd instance running in the container/VM. You can
301 attach breakpoints from the editor and enjoy all the other features of VSCode's debugger.
302
303 To debug systemd components other than PID 1, set "program" to the full path of the component you want to
304 debug and set "processId" to "${command:pickProcess}". Now, when starting the debugger, VSCode will ask you
305 the PID of the process you want to debug. Run `systemctl show --property MainPID --value <component>` in the
306 container to figure out the PID and enter it when asked and VSCode will attach to that process instead.
307
308 ## Debugging systemd-boot
309
310 During boot, systemd-boot and the stub loader will output messages like
311 `systemd-boot@0x0A` and `systemd-stub@0x0B`, providing the base of the loaded
312 code. This location can then be used to attach to a QEMU session (provided it
313 was run with `-s`). See `debug-sd-boot.sh` script in the tools folder which
314 automates this processes.
315
316 If the debugger is too slow to attach to examine an early boot code passage,
317 the call to `DEFINE_EFI_MAIN_FUNCTION()` can be modified to enable waiting. As
318 soon as the debugger has control, we can then run `set variable wait = 0` or
319 `return` to continue. Once the debugger has attached, setting breakpoints will
320 work like usual.
321
322 To debug systemd-boot in an IDE such as VSCode we can use a launch configuration like this:
323 ```json
324 {
325 "name": "systemd-boot",
326 "type": "cppdbg",
327 "request": "launch",
328 "program": "${workspaceFolder}/build/src/boot/efi/systemd-bootx64.efi",
329 "cwd": "${workspaceFolder}",
330 "MIMode": "gdb",
331 "miDebuggerServerAddress": ":1234",
332 "setupCommands": [
333 { "text": "shell mkfifo /tmp/sdboot.{in,out}" },
334 { "text": "shell qemu-system-x86_64 [...] -s -serial pipe:/tmp/sdboot" },
335 { "text": "shell ${workspaceFolder}/tools/debug-sd-boot.sh ${workspaceFolder}/build/src/boot/efi/systemd-bootx64.efi /tmp/sdboot.out systemd-boot.gdb" },
336 { "text": "source /tmp/systemd-boot.gdb" },
337 ]
338 }
339 ```
340
341 ## Hacking on the kernel + systemd
342
343 If you're hacking on the kernel in tandem with systemd, you can clone a kernel repository in mkosi.kernel/ in
344 the systemd repository, and mkosi will automatically build that kernel and install it into the final image.
345 To prevent the distribution's kernel from being installed (which isn't necessary since we're building our
346 own kernel), you can add the following snippets to mkosi.conf.d/20-local.conf:
347
348 (This snippet is for Fedora, the list of packages will need to be changed for other distributions)
349
350 ```
351 [Distribution]
352 CacheInitrd=no
353
354 [Content]
355 BasePackages=conditional
356 Packages=systemd
357 util-linux
358 dracut
359 ```