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