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