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