• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 16533846256

25 Jul 2025 07:44PM UTC coverage: 72.199% (+0.03%) from 72.165%
16533846256

push

github

bluca
bootctl: automatically set --graceful when running in chroot

Installing stuff in a chroot should not fail because efivars are
not available. When running in a container touching efivars is
completely disabled, but there are some cases (recovery) where
it is needed to touch them in a chroot, so don't disable them but
avoid failing the run instead.

1 of 3 new or added lines in 1 file covered. (33.33%)

223 existing lines in 36 files now uncovered.

302658 of 419200 relevant lines covered (72.2%)

732672.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

91.49
/src/core/unit.h
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2
#pragma once
3

4
#include "sd-id128.h"
5

6
#include "core-forward.h"
7
#include "emergency-action.h"
8
#include "execute.h"
9
#include "hashmap.h"
10
#include "install.h"
11
#include "iterator.h"
12
#include "job.h"
13
#include "list.h"
14
#include "log.h"
15
#include "log-context.h"
16
#include "ratelimit.h"
17
#include "time-util.h"
18
#include "unit-def.h"
19
#include "unit-dependency-atom.h"
20
#include "unit-file.h"
21

22
typedef enum UnitMountDependencyType {
23
        UNIT_MOUNT_WANTS,
24
        UNIT_MOUNT_REQUIRES,
25
        _UNIT_MOUNT_DEPENDENCY_TYPE_MAX,
26
        _UNIT_MOUNT_DEPENDENCY_TYPE_INVALID = -EINVAL,
27
} UnitMountDependencyType;
28

29
typedef enum KillOperation {
30
        KILL_TERMINATE,
31
        KILL_TERMINATE_AND_LOG,
32
        KILL_RESTART,
33
        KILL_KILL,
34
        KILL_WATCHDOG,
35
        _KILL_OPERATION_MAX,
36
        _KILL_OPERATION_INVALID = -EINVAL,
37
} KillOperation;
38

39
typedef enum CollectMode {
40
        COLLECT_INACTIVE,
41
        COLLECT_INACTIVE_OR_FAILED,
42
        _COLLECT_MODE_MAX,
43
        _COLLECT_MODE_INVALID = -EINVAL,
44
} CollectMode;
45

46
typedef enum OOMPolicy {
47
        OOM_CONTINUE,          /* The kernel or systemd-oomd kills the process it wants to kill, and that's it */
48
        OOM_STOP,              /* The kernel or systemd-oomd kills the process it wants to kill, and we stop the unit */
49
        OOM_KILL,              /* The kernel or systemd-oomd kills the process it wants to kill, and all others in the unit, and we stop the unit */
50
        _OOM_POLICY_MAX,
51
        _OOM_POLICY_INVALID = -EINVAL,
52
} OOMPolicy;
53

54
typedef enum StatusType {
55
        STATUS_TYPE_EPHEMERAL,
56
        STATUS_TYPE_NORMAL,
57
        STATUS_TYPE_NOTICE,
58
        STATUS_TYPE_EMERGENCY,
59
} StatusType;
60

61
static inline bool UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t) {
440,804✔
62
        return IN_SET(t, UNIT_ACTIVE, UNIT_RELOADING, UNIT_REFRESHING);
666,286✔
63
}
64

65
static inline bool UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t) {
491,084✔
66
        return IN_SET(t, UNIT_ACTIVE, UNIT_ACTIVATING, UNIT_RELOADING, UNIT_REFRESHING);
491,084✔
67
}
68

69
static inline bool UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t) {
33,592✔
70
        return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED, UNIT_DEACTIVATING);
33,592✔
71
}
72

73
static inline bool UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t) {
1,152,766✔
74
        return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED);
1,590,717✔
75
}
76

77
static inline bool UNIT_IS_LOAD_COMPLETE(UnitLoadState t) {
114,710✔
78
        return t >= 0 && t < _UNIT_LOAD_STATE_MAX && !IN_SET(t, UNIT_STUB, UNIT_MERGED);
114,710✔
79
}
80

81
static inline bool UNIT_IS_LOAD_ERROR(UnitLoadState t) {
67,048✔
82
        return IN_SET(t, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR);
67,048✔
83
}
84

85
/* Stores the 'reason' a dependency was created as a bit mask, i.e. due to which configuration source it came to be. We
86
 * use this so that we can selectively flush out parts of dependencies again. Note that the same dependency might be
87
 * created as a result of multiple "reasons", hence the bitmask. */
88
typedef enum UnitDependencyMask {
89
        /* Configured directly by the unit file, .wants/.requires symlink or drop-in, or as an immediate result of a
90
         * non-dependency option configured that way.  */
91
        UNIT_DEPENDENCY_FILE               = 1 << 0,
92

93
        /* As unconditional implicit dependency (not affected by unit configuration — except by the unit name and
94
         * type) */
95
        UNIT_DEPENDENCY_IMPLICIT           = 1 << 1,
96

97
        /* A dependency affected by DefaultDependencies=yes. Note that dependencies marked this way are conceptually
98
         * just a subset of UNIT_DEPENDENCY_FILE, as DefaultDependencies= is itself a unit file setting that can only
99
         * be set in unit files. We make this two separate bits only to help debugging how dependencies came to be. */
100
        UNIT_DEPENDENCY_DEFAULT            = 1 << 2,
101

102
        /* A dependency created from udev rules */
103
        UNIT_DEPENDENCY_UDEV               = 1 << 3,
104

105
        /* A dependency created because of some unit's RequiresMountsFor= setting */
106
        UNIT_DEPENDENCY_PATH               = 1 << 4,
107

108
        /* A dependency initially configured from the mount unit file however the dependency will be updated
109
         * from /proc/self/mountinfo as soon as the kernel will make the entry for that mount available in
110
         * the /proc file */
111
        UNIT_DEPENDENCY_MOUNT_FILE         = 1 << 5,
112

113
        /* A dependency created or updated because of data read from /proc/self/mountinfo */
114
        UNIT_DEPENDENCY_MOUNTINFO          = 1 << 6,
115

116
        /* A dependency created because of data read from /proc/swaps and no other configuration source */
117
        UNIT_DEPENDENCY_PROC_SWAP          = 1 << 7,
118

119
        /* A dependency for units in slices assigned by directly setting Slice= */
120
        UNIT_DEPENDENCY_SLICE_PROPERTY     = 1 << 8,
121

122
        _UNIT_DEPENDENCY_MASK_FULL         = (1 << 9) - 1,
123
} UnitDependencyMask;
124

125
/* The Unit's dependencies[] hashmaps use this structure as value. It has the same size as a void pointer, and thus can
126
 * be stored directly as hashmap value, without any indirection. Note that this stores two masks, as both the origin
127
 * and the destination of a dependency might have created it. */
128
typedef union UnitDependencyInfo {
129
        void *data;
130
        struct {
131
                UnitDependencyMask origin_mask:16;
132
                UnitDependencyMask destination_mask:16;
133
        } _packed_;
134
} UnitDependencyInfo;
135

136
/* Store information about why a unit was activated.
137
 * We start with trigger units (.path/.timer), eventually it will be expanded to include more metadata. */
138
typedef struct ActivationDetails {
139
        unsigned n_ref;
140
        UnitType trigger_unit_type;
141
        char *trigger_unit_name;
142
} ActivationDetails;
143

144
/* For casting an activation event into the various unit-specific types */
145
#define DEFINE_ACTIVATION_DETAILS_CAST(UPPERCASE, MixedCase, UNIT_TYPE)         \
146
        static inline MixedCase* UPPERCASE(const ActivationDetails *a) {              \
147
                if (_unlikely_(!a || a->trigger_unit_type != UNIT_##UNIT_TYPE)) \
148
                        return NULL;                                            \
149
                                                                                \
150
                return (MixedCase*) a;                                          \
151
        }
152

153
/* For casting the various unit types into a unit */
154
#define ACTIVATION_DETAILS(u)                                         \
155
        ({                                                            \
156
                typeof(u) _u_ = (u);                                  \
157
                ActivationDetails *_w_ = _u_ ? &(_u_)->meta : NULL;   \
158
                _w_;                                                  \
159
        })
160

161
ActivationDetails *activation_details_new(Unit *trigger_unit);
162
ActivationDetails *activation_details_ref(ActivationDetails *p);
163
ActivationDetails *activation_details_unref(ActivationDetails *p);
164
void activation_details_serialize(const ActivationDetails *p, FILE *f);
165
int activation_details_deserialize(const char *key, const char *value, ActivationDetails **info);
166
int activation_details_append_env(const ActivationDetails *info, char ***strv);
167
int activation_details_append_pair(const ActivationDetails *info, char ***strv);
168
DEFINE_TRIVIAL_CLEANUP_FUNC(ActivationDetails*, activation_details_unref);
15✔
169

170
typedef struct ActivationDetailsVTable {
171
        /* How much memory does an object of this activation type need */
172
        size_t object_size;
173

174
        /* This should reset all type-specific variables. This should not allocate memory, and is called
175
         * with zero-initialized data. It should hence only initialize variables that need to be set != 0. */
176
        void (*init)(ActivationDetails *info, Unit *trigger_unit);
177

178
        /* This should free all type-specific variables. It should be idempotent. */
179
        void (*done)(ActivationDetails *info);
180

181
        /* This should serialize all type-specific variables. */
182
        void (*serialize)(const ActivationDetails *info, FILE *f);
183

184
        /* This should deserialize all type-specific variables, one at a time. */
185
        int (*deserialize)(const char *key, const char *value, ActivationDetails **info);
186

187
        /* This should format the type-specific variables for the env block of the spawned service,
188
         * and return the number of added items. */
189
        int (*append_env)(const ActivationDetails *info, char ***strv);
190

191
        /* This should append type-specific variables as key/value pairs for the D-Bus property of the job,
192
         * and return the number of added pairs. */
193
        int (*append_pair)(const ActivationDetails *info, char ***strv);
194
} ActivationDetailsVTable;
195

196
extern const ActivationDetailsVTable * const activation_details_vtable[_UNIT_TYPE_MAX];
197

198
static inline const ActivationDetailsVTable* ACTIVATION_DETAILS_VTABLE(const ActivationDetails *a) {
45✔
199
        assert(a);
45✔
200
        assert(a->trigger_unit_type < _UNIT_TYPE_MAX);
45✔
201

202
        return activation_details_vtable[a->trigger_unit_type];
45✔
203
}
204

205
/* Newer LLVM versions don't like implicit casts from large pointer types to smaller enums, hence let's add
206
 * explicit type-safe helpers for that. */
207
static inline UnitDependency UNIT_DEPENDENCY_FROM_PTR(const void *p) {
3,864,095✔
208
        return PTR_TO_INT(p);
3,864,095✔
209
}
210

211
static inline void* UNIT_DEPENDENCY_TO_PTR(UnitDependency d) {
5,915,477✔
212
        return INT_TO_PTR(d);
5,915,477✔
213
}
214

215
typedef struct UnitRef {
216
        /* Keeps tracks of references to a unit. This is useful so
217
         * that we can merge two units if necessary and correct all
218
         * references to them */
219

220
        Unit *source, *target;
221
        LIST_FIELDS(UnitRef, refs_by_target);
222
} UnitRef;
223

224
/* The generic, dynamic definition of the unit */
225
typedef struct Unit {
226
        Manager *manager;
227

228
        UnitType type;
229
        UnitLoadState load_state;
230
        Unit *merged_into;
231

232
        char *id;   /* The one special name that we use for identification */
233
        char *instance;
234

235
        Set *aliases; /* All the other names. */
236

237
        /* For each dependency type we can look up another Hashmap with this, whose key is a Unit* object,
238
         * and whose value encodes why the dependency exists, using the UnitDependencyInfo type. i.e. a
239
         * Hashmap(UnitDependency → Hashmap(Unit* → UnitDependencyInfo)) */
240
        Hashmap *dependencies;
241
        uint64_t dependency_generation;
242

243
        /* Similar, for RequiresMountsFor= and WantsMountsFor= path dependencies. The key is the path, the
244
         * value the UnitDependencyInfo type */
245
        Hashmap *mounts_for[_UNIT_MOUNT_DEPENDENCY_TYPE_MAX];
246

247
        char *description;
248
        char **documentation;
249

250
        /* The SELinux context used for checking access to this unit read off the unit file at load time (do
251
         * not confuse with the selinux_context field in ExecContext which is the SELinux context we'll set
252
         * for processes) */
253
        char *access_selinux_context;
254

255
        char *fragment_path; /* if loaded from a config file this is the primary path to it */
256
        char *source_path; /* if converted, the source file */
257
        char **dropin_paths;
258

259
        usec_t fragment_not_found_timestamp_hash;
260
        usec_t fragment_mtime;
261
        usec_t source_mtime;
262
        usec_t dropin_mtime;
263

264
        /* If this is a transient unit we are currently writing, this is where we are writing it to */
265
        FILE *transient_file;
266

267
        /* Freezer state */
268
        sd_bus_message *pending_freezer_invocation;
269
        FreezerState freezer_state;
270

271
        /* Job timeout and action to take */
272
        EmergencyAction job_timeout_action;
273
        usec_t job_timeout;
274
        usec_t job_running_timeout;
275
        char *job_timeout_reboot_arg;
276

277
        /* If there is something to do with this unit, then this is the installed job for it */
278
        Job *job;
279

280
        /* JOB_NOP jobs are special and can be installed without disturbing the real job. */
281
        Job *nop_job;
282

283
        /* The slot used for watching NameOwnerChanged signals */
284
        sd_bus_slot *match_bus_slot;
285
        sd_bus_slot *get_name_owner_slot;
286

287
        /* References to this unit from clients */
288
        sd_bus_track *bus_track;
289
        char **deserialized_refs;
290

291
        /* References to this */
292
        LIST_HEAD(UnitRef, refs_by_target);
293

294
        /* Conditions to check */
295
        LIST_HEAD(Condition, conditions);
296
        LIST_HEAD(Condition, asserts);
297

298
        dual_timestamp condition_timestamp;
299
        dual_timestamp assert_timestamp;
300

301
        /* Updated whenever the low-level state changes */
302
        dual_timestamp state_change_timestamp;
303

304
        /* Updated whenever the (high-level) active state enters or leaves the active or inactive states */
305
        dual_timestamp inactive_exit_timestamp;
306
        dual_timestamp active_enter_timestamp;
307
        dual_timestamp active_exit_timestamp;
308
        dual_timestamp inactive_enter_timestamp;
309

310
        /* Per type list */
311
        LIST_FIELDS(Unit, units_by_type);
312

313
        /* Load queue */
314
        LIST_FIELDS(Unit, load_queue);
315

316
        /* D-Bus queue */
317
        LIST_FIELDS(Unit, dbus_queue);
318

319
        /* Cleanup queue */
320
        LIST_FIELDS(Unit, cleanup_queue);
321

322
        /* GC queue */
323
        LIST_FIELDS(Unit, gc_queue);
324

325
        /* CGroup realize members queue */
326
        LIST_FIELDS(Unit, cgroup_realize_queue);
327

328
        /* cgroup empty queue */
329
        LIST_FIELDS(Unit, cgroup_empty_queue);
330

331
        /* cgroup OOM queue */
332
        LIST_FIELDS(Unit, cgroup_oom_queue);
333

334
        /* Target dependencies queue */
335
        LIST_FIELDS(Unit, target_deps_queue);
336

337
        /* Queue of units with StopWhenUnneeded= set that shall be checked for clean-up. */
338
        LIST_FIELDS(Unit, stop_when_unneeded_queue);
339

340
        /* Queue of units that have an Uphold= dependency from some other unit, and should be checked for starting */
341
        LIST_FIELDS(Unit, start_when_upheld_queue);
342

343
        /* Queue of units that have a BindTo= dependency on some other unit, and should possibly be shut down */
344
        LIST_FIELDS(Unit, stop_when_bound_queue);
345

346
        /* Queue of units that should be checked if they can release resources now */
347
        LIST_FIELDS(Unit, release_resources_queue);
348

349
        /* Queue of units that should be informed when other units stop */
350
        LIST_FIELDS(Unit, stop_notify_queue);
351

352
        /* PIDs we keep an eye on. Note that a unit might have many more, but these are the ones we care
353
         * enough about to process SIGCHLD for */
354
        Set *pids; /* → PidRef* */
355

356
        /* Used in SIGCHLD and sd_notify() message event invocation logic to avoid that we dispatch the same event
357
         * multiple times on the same unit. */
358
        unsigned sigchldgen;
359
        unsigned notifygen;
360

361
        /* Used during GC sweeps */
362
        unsigned gc_marker;
363

364
        /* Error code when we didn't manage to load the unit (negative) */
365
        int load_error;
366

367
        /* Put a ratelimit on unit starting */
368
        RateLimit start_ratelimit;
369
        EmergencyAction start_limit_action;
370

371
        /* The unit has been marked for reload, restart, etc. Stored as 1u << marker1 | 1u << marker2. */
372
        unsigned markers;
373

374
        /* What to do on failure or success */
375
        EmergencyAction success_action, failure_action;
376
        int success_action_exit_status, failure_action_exit_status;
377
        char *reboot_arg;
378

379
        /* Make sure we never enter endless loops with the StopWhenUnneeded=, BindsTo=, Uphold= logic */
380
        RateLimit auto_start_stop_ratelimit;
381
        sd_event_source *auto_start_stop_event_source;
382

383
        /* Reference to a specific UID/GID */
384
        uid_t ref_uid;
385
        gid_t ref_gid;
386

387
        /* Cached unit file state and preset */
388
        UnitFileState unit_file_state;
389
        PresetAction unit_file_preset;
390

391
        /* How to start OnSuccess=/OnFailure= units */
392
        JobMode on_success_job_mode;
393
        JobMode on_failure_job_mode;
394

395
        /* If the job had a specific trigger that needs to be advertised (eg: a path unit), store it. */
396
        ActivationDetails *activation_details;
397

398
        /* Tweaking the GC logic */
399
        CollectMode collect_mode;
400

401
        /* The current invocation ID */
402
        sd_id128_t invocation_id;
403
        char invocation_id_string[SD_ID128_STRING_MAX]; /* useful when logging */
404

405
        /* Garbage collect us we nobody wants or requires us anymore */
406
        bool stop_when_unneeded;
407

408
        /* Create default dependencies */
409
        bool default_dependencies;
410

411
        /* Configure so that the unit survives a system transition without stopping/starting. */
412
        bool survive_final_kill_signal;
413

414
        /* Refuse manual starting, allow starting only indirectly via dependency. */
415
        bool refuse_manual_start;
416

417
        /* Don't allow the user to stop this unit manually, allow stopping only indirectly via dependency. */
418
        bool refuse_manual_stop;
419

420
        /* Allow isolation requests */
421
        bool allow_isolate;
422

423
        /* Ignore this unit when isolating */
424
        bool ignore_on_isolate;
425

426
        /* Did the last condition check succeed? */
427
        bool condition_result;
428
        bool assert_result;
429

430
        /* Is this a transient unit? */
431
        bool transient;
432

433
        /* Is this a unit that is always running and cannot be stopped? */
434
        bool perpetual;
435

436
        /* When true logs about this unit will be at debug level regardless of other log level settings */
437
        bool debug_invocation;
438

439
        /* Booleans indicating membership of this unit in the various queues */
440
        bool in_load_queue:1;
441
        bool in_dbus_queue:1;
442
        bool in_cleanup_queue:1;
443
        bool in_gc_queue:1;
444
        bool in_cgroup_realize_queue:1;
445
        bool in_cgroup_empty_queue:1;
446
        bool in_cgroup_oom_queue:1;
447
        bool in_target_deps_queue:1;
448
        bool in_stop_when_unneeded_queue:1;
449
        bool in_start_when_upheld_queue:1;
450
        bool in_stop_when_bound_queue:1;
451
        bool in_release_resources_queue:1;
452
        bool in_stop_notify_queue:1;
453

454
        bool sent_dbus_new_signal:1;
455

456
        bool job_running_timeout_set:1;
457

458
        bool in_audit:1;
459
        bool on_console:1;
460

461
        bool start_limit_hit:1;
462

463
        /* Did we already invoke unit_coldplug() for this unit? */
464
        bool coldplugged:1;
465

466
        /* For transient units: whether to add a bus track reference after creating the unit */
467
        bool bus_track_add:1;
468

469
        /* Remember which unit state files we created */
470
        bool exported_invocation_id:1;
471
        bool exported_log_level_max:1;
472
        bool exported_log_extra_fields:1;
473
        bool exported_log_ratelimit_interval:1;
474
        bool exported_log_ratelimit_burst:1;
475

476
        /* When writing transient unit files, stores which section we stored last. If < 0, we didn't write any yet. If
477
         * == 0 we are in the [Unit] section, if > 0 we are in the unit type-specific section. */
478
        signed int last_section_private:2;
479
} Unit;
480

481
typedef struct UnitStatusMessageFormats {
482
        const char *starting_stopping[2];
483
        const char *finished_start_job[_JOB_RESULT_MAX];
484
        const char *finished_stop_job[_JOB_RESULT_MAX];
485
        /* If this entry is present, it'll be called to provide a context-dependent format string,
486
         * or NULL to fall back to finished_{start,stop}_job; if those are NULL too, fall back to generic. */
487
        const char *(*finished_job)(Unit *u, JobType t, JobResult result);
488
} UnitStatusMessageFormats;
489

490
/* Flags used when writing drop-in files or transient unit files */
491
typedef enum UnitWriteFlags {
492
        /* Write a runtime unit file or drop-in (i.e. one below /run) */
493
        UNIT_RUNTIME                = 1 << 0,
494

495
        /* Write a persistent drop-in (i.e. one below /etc) */
496
        UNIT_PERSISTENT             = 1 << 1,
497

498
        /* Place this item in the per-unit-type private section, instead of [Unit] */
499
        UNIT_PRIVATE                = 1 << 2,
500

501
        /* Apply specifier escaping */
502
        UNIT_ESCAPE_SPECIFIERS      = 1 << 3,
503

504
        /* Escape elements of ExecStart= syntax, incl. prevention of variable expansion */
505
        UNIT_ESCAPE_EXEC_SYNTAX_ENV = 1 << 4,
506

507
        /* Escape elements of ExecStart=: syntax (no variable expansion) */
508
        UNIT_ESCAPE_EXEC_SYNTAX     = 1 << 5,
509

510
        /* Apply C escaping before writing */
511
        UNIT_ESCAPE_C               = 1 << 6,
512
} UnitWriteFlags;
513

514
/* Returns true if neither persistent, nor runtime storage is requested, i.e. this is a check invocation only */
515
static inline bool UNIT_WRITE_FLAGS_NOOP(UnitWriteFlags flags) {
3,953✔
516
        return (flags & (UNIT_RUNTIME|UNIT_PERSISTENT)) == 0;
3,953✔
517
}
518

519
#include "kill.h"
520

521
/* The static const, immutable data about a specific unit type */
522
typedef struct UnitVTable {
523
        /* How much memory does an object of this unit type need */
524
        size_t object_size;
525

526
        /* If greater than 0, the offset into the object where
527
         * ExecContext is found, if the unit type has that */
528
        size_t exec_context_offset;
529

530
        /* If greater than 0, the offset into the object where
531
         * CGroupContext is found, if the unit type has that */
532
        size_t cgroup_context_offset;
533

534
        /* If greater than 0, the offset into the object where
535
         * KillContext is found, if the unit type has that */
536
        size_t kill_context_offset;
537

538
        /* If greater than 0, the offset into the object where the pointer to ExecRuntime is found, if
539
         * the unit type has that */
540
        size_t exec_runtime_offset;
541

542
        /* If greater than 0, the offset into the object where the pointer to CGroupRuntime is found, if the
543
         * unit type has that */
544
        size_t cgroup_runtime_offset;
545

546
        /* The name of the configuration file section with the private settings of this unit */
547
        const char *private_section;
548

549
        /* Config file sections this unit type understands, separated
550
         * by NUL chars */
551
        const char *sections;
552

553
        /* This should reset all type-specific variables. This should
554
         * not allocate memory, and is called with zero-initialized
555
         * data. It should hence only initialize variables that need
556
         * to be set != 0. */
557
        void (*init)(Unit *u);
558

559
        /* This should free all type-specific variables. It should be
560
         * idempotent. */
561
        void (*done)(Unit *u);
562

563
        /* Actually load data from disk. This may fail, and should set
564
         * load_state to UNIT_LOADED, UNIT_MERGED or leave it at
565
         * UNIT_STUB if no configuration could be found. */
566
        int (*load)(Unit *u);
567

568
        /* During deserialization we only record the intended state to return to. With coldplug() we actually put the
569
         * deserialized state in effect. This is where unit_notify() should be called to start things up. Note that
570
         * this callback is invoked *before* we leave the reloading state of the manager, i.e. *before* we consider the
571
         * reloading to be complete. Thus, this callback should just restore the exact same state for any unit that was
572
         * in effect before the reload, i.e. units should not catch up with changes happened during the reload. That's
573
         * what catchup() below is for. */
574
        int (*coldplug)(Unit *u);
575

576
        /* This is called shortly after all units' coldplug() call was invoked, and *after* the manager left the
577
         * reloading state. It's supposed to catch up with state changes due to external events we missed so far (for
578
         * example because they took place while we were reloading/reexecing) */
579
        void (*catchup)(Unit *u);
580

581
        void (*dump)(Unit *u, FILE *f, const char *prefix);
582

583
        int (*start)(Unit *u);
584
        int (*stop)(Unit *u);
585
        int (*reload)(Unit *u);
586

587
        /* Clear out the various runtime/state/cache/logs/configuration data */
588
        int (*clean)(Unit *u, ExecCleanMask m);
589

590
        /* Freeze or thaw the unit. Returns > 0 to indicate that the request will be handled asynchronously; unit_frozen
591
         * or unit_thawed should be called once the operation is done. Returns 0 if done successfully, or < 0 on error. */
592
        int (*freezer_action)(Unit *u, FreezerAction a);
593
        bool (*can_freeze)(const Unit *u);
594

595
        /* Return which kind of data can be cleaned */
596
        int (*can_clean)(Unit *u, ExecCleanMask *ret);
597

598
        bool (*can_reload)(Unit *u);
599

600
        /* Add a bind/image mount into the unit namespace while it is running. */
601
        int (*live_mount)(Unit *u, const char *src, const char *dst, sd_bus_message *message, MountInNamespaceFlags flags, const MountOptions *options, sd_bus_error *error);
602
        int (*can_live_mount)(Unit *u, sd_bus_error *error);
603

604
        /* Serialize state and file descriptors that should be carried over into the new
605
         * instance after reexecution. */
606
        int (*serialize)(Unit *u, FILE *f, FDSet *fds);
607

608
        /* Restore one item from the serialization */
609
        int (*deserialize_item)(Unit *u, const char *key, const char *data, FDSet *fds);
610

611
        /* Try to match up fds with what we need for this unit */
612
        void (*distribute_fds)(Unit *u, FDSet *fds);
613

614
        /* Boils down the more complex internal state of this unit to
615
         * a simpler one that the engine can understand */
616
        UnitActiveState (*active_state)(Unit *u);
617

618
        /* Returns the substate specific to this unit type as
619
         * string. This is purely information so that we can give the
620
         * user a more fine grained explanation in which actual state a
621
         * unit is in. */
622
        const char* (*sub_state_to_string)(Unit *u);
623

624
        /* Additionally to UnitActiveState determine whether unit is to be restarted. */
625
        bool (*will_restart)(Unit *u);
626

627
        /* Return false when there is a reason to prevent this unit from being gc'ed
628
         * even though nothing references it and it isn't active in any way. */
629
        bool (*may_gc)(Unit *u);
630

631
        /* Return true when the unit is not controlled by the manager (e.g. extrinsic mounts). */
632
        bool (*is_extrinsic)(Unit *u);
633

634
        /* When the unit is not running and no job for it queued we shall release its runtime resources */
635
        void (*release_resources)(Unit *u);
636

637
        /* Invoked on every child that died */
638
        void (*sigchld_event)(Unit *u, pid_t pid, int code, int status);
639

640
        /* Reset failed state if we are in failed state */
641
        void (*reset_failed)(Unit *u);
642

643
        /* Called whenever any of the cgroups this unit watches for ran empty */
644
        void (*notify_cgroup_empty)(Unit *u);
645

646
        /* Called whenever an OOM kill event on this unit was seen */
647
        void (*notify_cgroup_oom)(Unit *u, bool managed_oom);
648

649
        /* Called whenever a process of this unit sends us a message */
650
        void (*notify_message)(Unit *u, PidRef *pidref, const struct ucred *ucred, char * const *tags, FDSet *fds);
651

652
        /* Called whenever we learn a handoff timestamp */
653
        void (*notify_handoff_timestamp)(Unit *u, const struct ucred *ucred, const dual_timestamp *ts);
654

655
        /* Called whenever we learn about a child process */
656
        void (*notify_pidref)(Unit *u, PidRef *parent_pidref, PidRef *child_pidref);
657

658
        /* Called whenever a name this Unit registered for comes or goes away. */
659
        void (*bus_name_owner_change)(Unit *u, const char *new_owner);
660

661
        /* Called for each property that is being set */
662
        int (*bus_set_property)(Unit *u, const char *name, sd_bus_message *message, UnitWriteFlags flags, sd_bus_error *error);
663

664
        /* Called after at least one property got changed to apply the necessary change */
665
        int (*bus_commit_properties)(Unit *u);
666

667
        /* Return the unit this unit is following */
668
        Unit* (*following)(Unit *u);
669

670
        /* Return the set of units that are following each other */
671
        int (*following_set)(Unit *u, Set **s);
672

673
        /* Invoked each time a unit this unit is triggering changes
674
         * state or gains/loses a job */
675
        void (*trigger_notify)(Unit *u, Unit *trigger);
676

677
        /* Invoked when some other units stop */
678
        bool (*stop_notify)(Unit *u);
679

680
        /* Called whenever CLOCK_REALTIME made a jump */
681
        void (*time_change)(Unit *u);
682

683
        /* Called whenever /etc/localtime was modified */
684
        void (*timezone_change)(Unit *u);
685

686
        /* Returns the next timeout of a unit */
687
        int (*get_timeout)(Unit *u, usec_t *timeout);
688

689
        /* Returns the start timeout of a unit */
690
        usec_t (*get_timeout_start_usec)(Unit *u);
691

692
        /* Returns the main PID if there is any defined, or NULL. */
693
        PidRef* (*main_pid)(Unit *u, bool *ret_is_alien);
694

695
        /* Returns the control PID if there is any defined, or NULL. */
696
        PidRef* (*control_pid)(Unit *u);
697

698
        /* Returns true if the unit currently needs access to the console */
699
        bool (*needs_console)(Unit *u);
700

701
        /* Returns the exit status to propagate in case of FailureAction=exit/SuccessAction=exit; usually returns the
702
         * exit code of the "main" process of the service or similar. */
703
        int (*exit_status)(Unit *u);
704

705
        /* Return a copy of the status string pointer. */
706
        const char* (*status_text)(Unit *u);
707

708
        /* Like the enumerate() callback further down, but only enumerates the perpetual units, i.e. all units that
709
         * unconditionally exist and are always active. The main reason to keep both enumeration functions separate is
710
         * philosophical: the state of perpetual units should be put in place by coldplug(), while the state of those
711
         * discovered through regular enumeration should be put in place by catchup(), see below. */
712
        void (*enumerate_perpetual)(Manager *m);
713

714
        /* This is called for each unit type and should be used to enumerate units already existing in the system
715
         * internally and load them. However, everything that is loaded here should still stay in inactive state. It is
716
         * the job of the catchup() call above to put the units into the discovered state. */
717
        void (*enumerate)(Manager *m);
718

719
        /* Type specific cleanups. */
720
        void (*shutdown)(Manager *m);
721

722
        /* If this function is set and returns false all jobs for units
723
         * of this type will immediately fail. */
724
        bool (*supported)(void);
725

726
        /* If this function is set, it's invoked first as part of starting a unit to allow start rate
727
         * limiting checks to occur before we do anything else. */
728
        int (*can_start)(Unit *u);
729

730
        /* Returns > 0 if the whole subsystem is ratelimited, and new start operations should not be started
731
         * for this unit type right now. */
732
        int (*subsystem_ratelimited)(Manager *m);
733

734
        /* The strings to print in status messages */
735
        UnitStatusMessageFormats status_message_formats;
736

737
        /* True if transient units of this type are OK */
738
        bool can_transient;
739

740
        /* True if cgroup delegation is permissible */
741
        bool can_delegate;
742

743
        /* True if the unit type triggers other units, i.e. can have a UNIT_TRIGGERS dependency */
744
        bool can_trigger;
745

746
        /* True if the unit type knows a failure state, and thus can be source of an OnFailure= dependency */
747
        bool can_fail;
748

749
        /* True if units of this type shall be startable only once and then never again */
750
        bool once_only;
751

752
        /* Do not serialize this unit when preparing for root switch */
753
        bool exclude_from_switch_root_serialization;
754

755
        /* True if queued jobs of this type should be GC'ed if no other job needs them anymore */
756
        bool gc_jobs;
757

758
        /* True if systemd-oomd can monitor and act on this unit's recursive children's cgroups  */
759
        bool can_set_managed_oom;
760

761
        /* If true, we'll notify plymouth about this unit */
762
        bool notify_plymouth;
763

764
        /* If true, we'll notify a surrounding VMM/container manager about this unit becoming available */
765
        bool notify_supervisor;
766

767
        /* The audit events to generate on start + stop (or 0 if none shall be generated) */
768
        int audit_start_message_type;
769
        int audit_stop_message_type;
770
} UnitVTable;
771

772
extern const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX];
773

774
static inline const UnitVTable* UNIT_VTABLE(const Unit *u) {
21,151,755✔
775
        return unit_vtable[u->type];
21,127,822✔
776
}
777

778
/* For casting a unit into the various unit types */
779
#define DEFINE_CAST(UPPERCASE, MixedCase)                               \
780
        static inline MixedCase* UPPERCASE(Unit *u) {                   \
781
                if (_unlikely_(!u || u->type != UNIT_##UPPERCASE))      \
782
                        return NULL;                                    \
783
                                                                        \
784
                return (MixedCase*) u;                                  \
785
        }
786

787
/* For casting the various unit types into a unit */
788
#define UNIT(u)                                         \
789
        ({                                              \
790
                typeof(u) _u_ = (u);                    \
791
                Unit *_w_ = _u_ ? &(_u_)->meta : NULL;  \
792
                _w_;                                    \
793
        })
794

795
#define UNIT_HAS_EXEC_CONTEXT(u) (UNIT_VTABLE(u)->exec_context_offset > 0)
796
#define UNIT_HAS_CGROUP_CONTEXT(u) (UNIT_VTABLE(u)->cgroup_context_offset > 0)
797
#define UNIT_HAS_KILL_CONTEXT(u) (UNIT_VTABLE(u)->kill_context_offset > 0)
798

799
Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other);
800
int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array);
801
int unit_get_transitive_dependency_set(Unit *u, UnitDependencyAtom atom, Set **ret);
802

803
static inline Hashmap* unit_get_dependencies(Unit *u, UnitDependency d) {
65,633✔
804
        return hashmap_get(u->dependencies, UNIT_DEPENDENCY_TO_PTR(d));
65,633✔
805
}
806

807
static inline Unit* UNIT_TRIGGER(Unit *u) {
1,898✔
808
        return unit_has_dependency(u, UNIT_ATOM_TRIGGERS, NULL);
1,898✔
809
}
810

811
static inline Unit* UNIT_GET_SLICE(const Unit *u) {
4,230,923✔
812
        return unit_has_dependency(u, UNIT_ATOM_IN_SLICE, NULL);
4,230,922✔
813
}
814

815
Unit* unit_new(Manager *m, size_t size);
816
Unit* unit_free(Unit *u);
817
DEFINE_TRIVIAL_CLEANUP_FUNC(Unit *, unit_free);
501,889✔
818

819
int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret);
820
int unit_add_name(Unit *u, const char *name);
821

822
int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference, UnitDependencyMask mask);
823
int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask);
824

825
int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask);
826
int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask);
827

828
int unit_add_exec_dependencies(Unit *u, ExecContext *c);
829

830
int unit_choose_id(Unit *u, const char *name);
831
int unit_set_description(Unit *u, const char *description);
832

833
void unit_release_resources(Unit *u);
834

835
bool unit_may_gc(Unit *u);
836

837
static inline bool unit_is_extrinsic(Unit *u) {
21,365✔
838
        return u->perpetual ||
21,365✔
839
                (UNIT_VTABLE(u)->is_extrinsic && UNIT_VTABLE(u)->is_extrinsic(u));
20,798✔
840
}
841

UNCOV
842
static inline const char* unit_status_text(Unit *u) {
×
UNCOV
843
        if (u && UNIT_VTABLE(u)->status_text)
×
UNCOV
844
                return UNIT_VTABLE(u)->status_text(u);
×
845
        return NULL;
846
}
847

848
void unit_add_to_load_queue(Unit *u);
849
void unit_add_to_dbus_queue(Unit *u);
850
void unit_add_to_cleanup_queue(Unit *u);
851
void unit_add_to_gc_queue(Unit *u);
852
void unit_add_to_target_deps_queue(Unit *u);
853
void unit_submit_to_stop_when_unneeded_queue(Unit *u);
854
void unit_submit_to_start_when_upheld_queue(Unit *u);
855
void unit_submit_to_stop_when_bound_queue(Unit *u);
856
void unit_submit_to_release_resources_queue(Unit *u);
857
void unit_add_to_stop_notify_queue(Unit *u);
858
void unit_remove_from_stop_notify_queue(Unit *u);
859

860
int unit_merge(Unit *u, Unit *other);
861
int unit_merge_by_name(Unit *u, const char *other);
862

863
Unit *unit_follow_merge(Unit *u) _pure_;
864

865
int unit_load_fragment_and_dropin(Unit *u, bool fragment_required);
866
int unit_load(Unit *unit);
867

868
int unit_set_slice(Unit *u, Unit *slice);
869
int unit_set_default_slice(Unit *u);
870

871
const char* unit_description(Unit *u) _pure_;
872
const char* unit_status_string(Unit *u, char **combined);
873

874
bool unit_has_name(const Unit *u, const char *name);
875

876
UnitActiveState unit_active_state(Unit *u);
877

878
const char* unit_sub_state_to_string(Unit *u);
879

880
bool unit_can_reload(Unit *u) _pure_;
881
bool unit_can_start(Unit *u) _pure_;
882
bool unit_can_stop(Unit *u) _pure_;
883
bool unit_can_isolate(Unit *u) _pure_;
884

885
int unit_start(Unit *u, ActivationDetails *details);
886
int unit_stop(Unit *u);
887
int unit_reload(Unit *u);
888

889
int unit_kill(Unit *u, KillWhom w, const char *subgroup, int signo, int code, int value, sd_bus_error *ret_error);
890

891
void unit_notify_cgroup_oom(Unit *u, bool managed_oom);
892

893
void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success);
894

895
int unit_watch_pidref(Unit *u, const PidRef *pid, bool exclusive);
896
void unit_unwatch_pidref(Unit *u, const PidRef *pid);
897
void unit_unwatch_all_pids(Unit *u);
898
void unit_unwatch_pidref_done(Unit *u, PidRef *pidref);
899

900
int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name);
901
int unit_watch_bus_name(Unit *u, const char *name);
902
void unit_unwatch_bus_name(Unit *u, const char *name);
903

904
bool unit_job_is_applicable(Unit *u, JobType j);
905

906
int setenv_unit_path(const char *p);
907

908
char* unit_dbus_path(Unit *u);
909
char* unit_dbus_path_invocation_id(Unit *u);
910

911
int unit_load_related_unit(Unit *u, const char *type, Unit **_found);
912

913
int unit_add_node_dependency(Unit *u, const char *what, UnitDependency d, UnitDependencyMask mask);
914
int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask);
915

916
int unit_coldplug(Unit *u);
917
void unit_catchup(Unit *u);
918

919
void unit_status_printf(Unit *u, StatusType status_type, const char *status, const char *format, const char *ident) _printf_(4, 0);
920

921
bool unit_need_daemon_reload(Unit *u);
922

923
void unit_reset_failed(Unit *u);
924

925
Unit *unit_following(Unit *u);
926
int unit_following_set(Unit *u, Set **s);
927

928
const char* unit_slice_name(Unit *u);
929

930
bool unit_stop_pending(Unit *u) _pure_;
931
bool unit_inactive_or_pending(Unit *u) _pure_;
932
bool unit_active_or_pending(Unit *u);
933
bool unit_will_restart_default(Unit *u);
934
bool unit_will_restart(Unit *u);
935

936
int unit_add_default_target_dependency(Unit *u, Unit *target);
937

938
void unit_start_on_termination_deps(Unit *u, UnitDependencyAtom atom);
939
void unit_trigger_notify(Unit *u);
940

941
int unit_get_exec_quota_stats(Unit *u, ExecContext *c, ExecDirectoryType dt, uint64_t *ret_usage, uint64_t *ret_limit);
942

943
UnitFileState unit_get_unit_file_state(Unit *u);
944
PresetAction unit_get_unit_file_preset(Unit *u);
945

946
Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target);
947
void unit_ref_unset(UnitRef *ref);
948

949
#define UNIT_DEREF(ref) ((ref).target)
950
#define UNIT_ISSET(ref) (!!(ref).target)
951

952
int unit_patch_contexts(Unit *u);
953

954
ExecContext* unit_get_exec_context(const Unit *u) _pure_;
955
KillContext* unit_get_kill_context(const Unit *u) _pure_;
956
CGroupContext* unit_get_cgroup_context(const Unit *u) _pure_;
957

958
ExecRuntime* unit_get_exec_runtime(const Unit *u) _pure_;
959
CGroupRuntime* unit_get_cgroup_runtime(const Unit *u) _pure_;
960

961
int unit_setup_exec_runtime(Unit *u);
962
CGroupRuntime* unit_setup_cgroup_runtime(Unit *u);
963

964
const char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf);
965
char* unit_concat_strv(char **l, UnitWriteFlags flags);
966

967
int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data);
968
int unit_write_settingf(Unit *u, UnitWriteFlags mode, const char *name, const char *format, ...) _printf_(4,5);
969

970
int unit_kill_context(Unit *u, KillOperation k);
971

972
int unit_make_transient(Unit *u);
973

974
int unit_add_mounts_for(Unit *u, const char *path, UnitDependencyMask mask, UnitMountDependencyType type);
975

976
bool unit_type_supported(UnitType t);
977

978
bool unit_is_pristine(Unit *u);
979

980
bool unit_is_unneeded(Unit *u);
981
bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit);
982
bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit);
983

984
PidRef* unit_control_pid(Unit *u);
985
PidRef* unit_main_pid_full(Unit *u, bool *ret_is_alien);
986
static inline PidRef* unit_main_pid(Unit *u) {
3,382✔
987
        return unit_main_pid_full(u, NULL);
3,382✔
988
}
989

990
void unit_warn_if_dir_nonempty(Unit *u, const char* where);
991
int unit_log_noncanonical_mount_path(Unit *u, const char *where);
992
int unit_fail_if_noncanonical_mount_path(Unit *u, const char* where);
993

994
int unit_test_start_limit(Unit *u);
995

996
int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid);
997
void unit_unref_uid_gid(Unit *u, bool destroy_now);
998

999
void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid);
1000

1001
int unit_set_invocation_id(Unit *u, sd_id128_t id);
1002
int unit_acquire_invocation_id(Unit *u);
1003

1004
int unit_set_exec_params(Unit *s, ExecParameters *p);
1005

1006
int unit_fork_helper_process(Unit *u, const char *name, bool into_cgroup, PidRef *ret);
1007
int unit_fork_and_watch_rm_rf(Unit *u, char **paths, PidRef *ret);
1008

1009
void unit_remove_dependencies(Unit *u, UnitDependencyMask mask);
1010

1011
void unit_export_state_files(Unit *u);
1012
void unit_unlink_state_files(Unit *u);
1013

1014
int unit_set_debug_invocation(Unit *u, bool enable);
1015

1016
int unit_prepare_exec(Unit *u);
1017

1018
int unit_warn_leftover_processes(Unit *u, bool start);
1019

1020
bool unit_needs_console(Unit *u);
1021

1022
int unit_pid_attachable(Unit *unit, PidRef *pid, sd_bus_error *error);
1023

1024
static inline bool unit_has_job_type(Unit *u, JobType type) {
4,517✔
1025
        return u && u->job && u->job->type == type;
4,515✔
1026
}
1027

1028
int unit_get_log_level_max(const Unit *u);
1029

1030
bool unit_log_level_test(const Unit *u, int level);
1031

1032
/* unit_log_skip is for cases like ExecCondition= where a unit is considered "done"
1033
 * after some execution, rather than succeeded or failed. */
1034
void unit_log_skip(Unit *u, const char *result);
1035
void unit_log_success(Unit *u);
1036
void unit_log_failure(Unit *u, const char *result);
1037
static inline void unit_log_result(Unit *u, bool success, const char *result) {
1,966✔
1038
        if (success)
1,966✔
1039
                unit_log_success(u);
1,966✔
1040
        else
1041
                unit_log_failure(u, result);
×
1042
}
1,966✔
1043

1044
void unit_log_process_exit(Unit *u, const char *kind, const char *command, bool success, int code, int status);
1045

1046
int unit_exit_status(Unit *u);
1047
int unit_success_action_exit_status(Unit *u);
1048
int unit_failure_action_exit_status(Unit *u);
1049

1050
int unit_test_trigger_loaded(Unit *u);
1051

1052
void unit_destroy_runtime_data(Unit *u, const ExecContext *context, bool destroy_runtime_dir);
1053
int unit_clean(Unit *u, ExecCleanMask mask);
1054
int unit_can_clean(Unit *u, ExecCleanMask *ret_mask);
1055

1056
bool unit_can_start_refuse_manual(Unit *u);
1057
bool unit_can_stop_refuse_manual(Unit *u);
1058
bool unit_can_isolate_refuse_manual(Unit *u);
1059

1060
bool unit_can_freeze(const Unit *u);
1061
int unit_freezer_action(Unit *u, FreezerAction action);
1062
void unit_next_freezer_state(Unit *u, FreezerAction action, FreezerState *ret_next, FreezerState *ret_objective);
1063
void unit_set_freezer_state(Unit *u, FreezerState state);
1064
void unit_freezer_complete(Unit *u, FreezerState kernel_state);
1065

1066
int unit_can_live_mount(Unit *u, sd_bus_error *error);
1067
int unit_live_mount(Unit *u, const char *src, const char *dst, sd_bus_message *message, MountInNamespaceFlags flags, const MountOptions *options, sd_bus_error *error);
1068

1069
Condition *unit_find_failed_condition(Unit *u);
1070

1071
int unit_arm_timer(Unit *u, sd_event_source **source, bool relative, usec_t usec, sd_event_time_handler_t handler);
1072

1073
bool unit_passes_filter(Unit *u, char * const *states, char * const *patterns);
1074

1075
int unit_compare_priority(Unit *a, Unit *b);
1076

1077
const char* unit_log_field(const Unit *u);
1078
const char* unit_invocation_log_field(const Unit *u);
1079

1080
UnitMountDependencyType unit_mount_dependency_type_from_string(const char *s) _const_;
1081
const char* unit_mount_dependency_type_to_string(UnitMountDependencyType t) _const_;
1082
UnitDependency unit_mount_dependency_type_to_dependency_type(UnitMountDependencyType t) _pure_;
1083

1084
const char* oom_policy_to_string(OOMPolicy i) _const_;
1085
OOMPolicy oom_policy_from_string(const char *s) _pure_;
1086

1087
/* Macros which append UNIT= or USER_UNIT= to the message */
1088

1089
#define log_unit_full_errno_zerook(unit, level, error, ...)             \
1090
        ({                                                              \
1091
                const Unit *_u = (unit);                                \
1092
                const int _l = (level);                                 \
1093
                LOG_CONTEXT_SET_LOG_LEVEL(unit_get_log_level_max(_u));  \
1094
                const ExecContext *_c = _u ? unit_get_exec_context(_u) : NULL; \
1095
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1096
                                     _c ? _c->n_log_extra_fields : 0);  \
1097
                _u ? log_object_internal(_l, error, PROJECT_FILE, __LINE__, __func__,  unit_log_field(_u), _u->id, unit_invocation_log_field(_u), _u->invocation_id_string, ##__VA_ARGS__) : \
1098
                     log_internal(_l, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
1099
        })
1100

1101
#define log_unit_full_errno(unit, level, error, ...) \
1102
        ({                                                              \
1103
                int _error = (error);                                   \
1104
                ASSERT_NON_ZERO(_error);                                \
1105
                log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
1106
        })
1107

1108
#define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, __VA_ARGS__)
1109

1110
#define log_unit_debug(unit, ...)   log_unit_full(unit, LOG_DEBUG, __VA_ARGS__)
1111
#define log_unit_info(unit, ...)    log_unit_full(unit, LOG_INFO, __VA_ARGS__)
1112
#define log_unit_notice(unit, ...)  log_unit_full(unit, LOG_NOTICE, __VA_ARGS__)
1113
#define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, __VA_ARGS__)
1114
#define log_unit_error(unit, ...)   log_unit_full(unit, LOG_ERR, __VA_ARGS__)
1115

1116
#define log_unit_debug_errno(unit, error, ...)   log_unit_full_errno(unit, LOG_DEBUG, error, __VA_ARGS__)
1117
#define log_unit_info_errno(unit, error, ...)    log_unit_full_errno(unit, LOG_INFO, error, __VA_ARGS__)
1118
#define log_unit_notice_errno(unit, error, ...)  log_unit_full_errno(unit, LOG_NOTICE, error, __VA_ARGS__)
1119
#define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, __VA_ARGS__)
1120
#define log_unit_error_errno(unit, error, ...)   log_unit_full_errno(unit, LOG_ERR, error, __VA_ARGS__)
1121

1122
#if LOG_TRACE
1123
#  define log_unit_trace(...)          log_unit_debug(__VA_ARGS__)
1124
#  define log_unit_trace_errno(...)    log_unit_debug_errno(__VA_ARGS__)
1125
#else
1126
#  define log_unit_trace(...)          do {} while (0)
1127
#  define log_unit_trace_errno(e, ...) (-ERRNO_VALUE(e))
1128
#endif
1129

1130
#define log_unit_struct_errno(unit, level, error, ...)                  \
1131
        ({                                                              \
1132
                const Unit *_u = (unit);                                \
1133
                const int _l = (level);                                 \
1134
                LOG_CONTEXT_SET_LOG_LEVEL(unit_get_log_level_max(_u));  \
1135
                const ExecContext *_c = _u ? unit_get_exec_context(_u) : NULL; \
1136
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1137
                                     _c ? _c->n_log_extra_fields : 0);  \
1138
                log_struct_errno(_l, error, __VA_ARGS__, LOG_UNIT_ID(_u)); \
1139
        })
1140

1141
#define log_unit_struct(unit, level, ...) log_unit_struct_errno(unit, level, 0, __VA_ARGS__)
1142

1143
#define log_unit_struct_iovec_errno(unit, level, error, iovec, n_iovec) \
1144
        ({                                                              \
1145
                const Unit *_u = (unit);                                \
1146
                const int _l = (level);                                 \
1147
                LOG_CONTEXT_SET_LOG_LEVEL(unit_get_log_level_max(_u));  \
1148
                const ExecContext *_c = _u ? unit_get_exec_context(_u) : NULL; \
1149
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1150
                                     _c ? _c->n_log_extra_fields : 0);  \
1151
                log_struct_iovec_errno(_l, error, iovec, n_iovec);      \
1152
        })
1153

1154
#define log_unit_struct_iovec(unit, level, iovec, n_iovec) log_unit_struct_iovec_errno(unit, level, 0, iovec, n_iovec)
1155

1156
/* Like LOG_MESSAGE(), but with the unit name prefixed. */
1157
#define LOG_UNIT_MESSAGE(unit, fmt, ...) LOG_MESSAGE("%s: " fmt, (unit)->id, ##__VA_ARGS__)
1158
#define LOG_UNIT_ID(unit) LOG_ITEM("%s%s", unit_log_field((unit)), (unit)->id)
1159
#define LOG_UNIT_INVOCATION_ID(unit) LOG_ITEM("%s%s", unit_invocation_log_field((unit)), (unit)->invocation_id_string)
1160

1161
const char* collect_mode_to_string(CollectMode m) _const_;
1162
CollectMode collect_mode_from_string(const char *s) _pure_;
1163

1164
typedef struct UnitForEachDependencyData {
1165
        /* Stores state for the FOREACH macro below for iterating through all deps that have any of the
1166
         * specified dependency atom bits set */
1167
        const Unit *unit;
1168
        UnitDependencyAtom match_atom;
1169
        Hashmap *by_type, *by_unit;
1170
        void *current_type;
1171
        Iterator by_type_iterator, by_unit_iterator;
1172
        Unit **current_unit;
1173
        uint64_t generation;
1174
        unsigned n_restart;
1175
        bool restart_on_generation_change;
1176
} UnitForEachDependencyData;
1177

1178
/* Let's not restart the loop infinitely. */
1179
#define MAX_FOREACH_DEPENDENCY_RESTART 100000
1180

1181
/* Iterates through all dependencies that have a specific atom in the dependency type set. This tries to be
1182
 * smart: if the atom is unique, we'll directly go to right entry. Otherwise we'll iterate through the
1183
 * per-dependency type hashmap and match all dep that have the right atom set. */
1184
#define _UNIT_FOREACH_DEPENDENCY(other, u, ma, restart, data)           \
1185
        for (UnitForEachDependencyData data = {                         \
1186
                        .unit = (u),                                    \
1187
                        .match_atom = (ma),                             \
1188
                        .current_unit = &(other),                       \
1189
                        .restart_on_generation_change = (restart),      \
1190
                };                                                      \
1191
             ({                                                         \
1192
                     UnitDependency _dt = _UNIT_DEPENDENCY_INVALID;     \
1193
                     bool _found;                                       \
1194
                                                                        \
1195
                     if (data.generation == 0 ||                        \
1196
                         (data.restart_on_generation_change &&          \
1197
                          data.generation != data.unit->dependency_generation)) { \
1198
                             data.generation = data.unit->dependency_generation; \
1199
                             data.by_type = data.unit->dependencies;    \
1200
                             data.by_type_iterator = ITERATOR_FIRST;    \
1201
                             assert_se(data.n_restart++ < MAX_FOREACH_DEPENDENCY_RESTART); \
1202
                     } else                                             \
1203
                             assert(data.generation == data.unit->dependency_generation); \
1204
                                                                        \
1205
                     if (data.by_type && ITERATOR_IS_FIRST(data.by_type_iterator)) { \
1206
                             _dt = unit_dependency_from_unique_atom(data.match_atom); \
1207
                             if (_dt >= 0) {                            \
1208
                                     data.by_unit = hashmap_get(data.by_type, UNIT_DEPENDENCY_TO_PTR(_dt)); \
1209
                                     data.current_type = UNIT_DEPENDENCY_TO_PTR(_dt); \
1210
                                     data.by_type = NULL;               \
1211
                                     _found = !!data.by_unit;           \
1212
                             }                                          \
1213
                     }                                                  \
1214
                     if (_dt < 0)                                       \
1215
                             _found = hashmap_iterate(data.by_type,     \
1216
                                                      &data.by_type_iterator, \
1217
                                                      (void**) &(data.by_unit), \
1218
                                                      (const void**) &(data.current_type)); \
1219
                     _found;                                            \
1220
             }); )                                                      \
1221
                if ((unit_dependency_to_atom(UNIT_DEPENDENCY_FROM_PTR(data.current_type)) & data.match_atom) != 0) \
1222
                        for (data.by_unit_iterator = ITERATOR_FIRST;    \
1223
                             data.generation == data.unit->dependency_generation && \
1224
                                hashmap_iterate(data.by_unit,           \
1225
                                                &data.by_unit_iterator, \
1226
                                                NULL,                   \
1227
                                                (const void**) data.current_unit); )
1228

1229
/* Note: this matches deps that have *any* of the atoms specified in match_atom set */
1230
#define UNIT_FOREACH_DEPENDENCY(other, u, match_atom) \
1231
        _UNIT_FOREACH_DEPENDENCY(other, u, match_atom, false, UNIQ_T(data, UNIQ))
1232
#define UNIT_FOREACH_DEPENDENCY_SAFE(other, u, match_atom) \
1233
        _UNIT_FOREACH_DEPENDENCY(other, u, match_atom, true, UNIQ_T(data, UNIQ))
1234

1235
#define _LOG_CONTEXT_PUSH_UNIT(unit, u, c)                                                              \
1236
        const Unit *u = (unit);                                                                         \
1237
        const ExecContext *c = unit_get_exec_context(u);                                                \
1238
        LOG_CONTEXT_PUSH_KEY_VALUE(unit_log_field(u), u->id);                                           \
1239
        LOG_CONTEXT_PUSH_KEY_VALUE(unit_invocation_log_field(u), u->invocation_id_string);              \
1240
        LOG_CONTEXT_PUSH_IOV(c ? c->log_extra_fields : NULL, c ? c->n_log_extra_fields : 0);            \
1241
        LOG_CONTEXT_SET_LOG_LEVEL(unit_get_log_level_max(u))
1242

1243
#define LOG_CONTEXT_PUSH_UNIT(unit) \
1244
        _LOG_CONTEXT_PUSH_UNIT(unit, UNIQ_T(u, UNIQ), UNIQ_T(c, UNIQ))
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc