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