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