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

systemd / systemd / 13168948113

05 Feb 2025 10:37PM UTC coverage: 71.813% (-0.004%) from 71.817%
13168948113

push

github

poettering
update TODO

293032 of 408051 relevant lines covered (71.81%)

710489.93 hits per line

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

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

4
#include <errno.h>
5
#include <stdbool.h>
6
#include <stdlib.h>
7
#include <sys/socket.h>
8
#include <unistd.h>
9

10
#include "sd-id128.h"
11

12
/* Circular dependency with manager.h, needs to be defined before local includes */
13
typedef enum UnitMountDependencyType {
14
        UNIT_MOUNT_WANTS,
15
        UNIT_MOUNT_REQUIRES,
16
        _UNIT_MOUNT_DEPENDENCY_TYPE_MAX,
17
        _UNIT_MOUNT_DEPENDENCY_TYPE_INVALID = -EINVAL,
18
} UnitMountDependencyType;
19

20
#include "cgroup.h"
21
#include "condition.h"
22
#include "emergency-action.h"
23
#include "install.h"
24
#include "list.h"
25
#include "mount-util.h"
26
#include "pidref.h"
27
#include "unit-file.h"
28

29
typedef struct UnitRef UnitRef;
30

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

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

48
static inline bool UNIT_IS_ACTIVE_OR_RELOADING(UnitActiveState t) {
749,647✔
49
        return IN_SET(t, UNIT_ACTIVE, UNIT_RELOADING, UNIT_REFRESHING);
985,270✔
50
}
51

52
static inline bool UNIT_IS_ACTIVE_OR_ACTIVATING(UnitActiveState t) {
751,396✔
53
        return IN_SET(t, UNIT_ACTIVE, UNIT_ACTIVATING, UNIT_RELOADING, UNIT_REFRESHING);
751,396✔
54
}
55

56
static inline bool UNIT_IS_INACTIVE_OR_DEACTIVATING(UnitActiveState t) {
19,684✔
57
        return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED, UNIT_DEACTIVATING);
19,684✔
58
}
59

60
static inline bool UNIT_IS_INACTIVE_OR_FAILED(UnitActiveState t) {
1,562,538✔
61
        return IN_SET(t, UNIT_INACTIVE, UNIT_FAILED);
1,947,373✔
62
}
63

64
static inline bool UNIT_IS_LOAD_COMPLETE(UnitLoadState t) {
133,329✔
65
        return t >= 0 && t < _UNIT_LOAD_STATE_MAX && !IN_SET(t, UNIT_STUB, UNIT_MERGED);
133,329✔
66
}
67

68
static inline bool UNIT_IS_LOAD_ERROR(UnitLoadState t) {
43,643✔
69
        return IN_SET(t, UNIT_NOT_FOUND, UNIT_BAD_SETTING, UNIT_ERROR);
43,643✔
70
}
71

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

80
        /* As unconditional implicit dependency (not affected by unit configuration — except by the unit name and
81
         * type) */
82
        UNIT_DEPENDENCY_IMPLICIT           = 1 << 1,
83

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

89
        /* A dependency created from udev rules */
90
        UNIT_DEPENDENCY_UDEV               = 1 << 3,
91

92
        /* A dependency created because of some unit's RequiresMountsFor= setting */
93
        UNIT_DEPENDENCY_PATH               = 1 << 4,
94

95
        /* A dependency initially configured from the mount unit file however the dependency will be updated
96
         * from /proc/self/mountinfo as soon as the kernel will make the entry for that mount available in
97
         * the /proc file */
98
        UNIT_DEPENDENCY_MOUNT_FILE         = 1 << 5,
99

100
        /* A dependency created or updated because of data read from /proc/self/mountinfo */
101
        UNIT_DEPENDENCY_MOUNTINFO          = 1 << 6,
102

103
        /* A dependency created because of data read from /proc/swaps and no other configuration source */
104
        UNIT_DEPENDENCY_PROC_SWAP          = 1 << 7,
105

106
        /* A dependency for units in slices assigned by directly setting Slice= */
107
        UNIT_DEPENDENCY_SLICE_PROPERTY     = 1 << 8,
108

109
        _UNIT_DEPENDENCY_MASK_FULL         = (1 << 9) - 1,
110
} UnitDependencyMask;
111

112
/* The Unit's dependencies[] hashmaps use this structure as value. It has the same size as a void pointer, and thus can
113
 * be stored directly as hashmap value, without any indirection. Note that this stores two masks, as both the origin
114
 * and the destination of a dependency might have created it. */
115
typedef union UnitDependencyInfo {
116
        void *data;
117
        struct {
118
                UnitDependencyMask origin_mask:16;
119
                UnitDependencyMask destination_mask:16;
120
        } _packed_;
121
} UnitDependencyInfo;
122

123
/* Store information about why a unit was activated.
124
 * We start with trigger units (.path/.timer), eventually it will be expanded to include more metadata. */
125
typedef struct ActivationDetails {
126
        unsigned n_ref;
127
        UnitType trigger_unit_type;
128
        char *trigger_unit_name;
129
} ActivationDetails;
130

131
/* For casting an activation event into the various unit-specific types */
132
#define DEFINE_ACTIVATION_DETAILS_CAST(UPPERCASE, MixedCase, UNIT_TYPE)         \
133
        static inline MixedCase* UPPERCASE(ActivationDetails *a) {              \
134
                if (_unlikely_(!a || a->trigger_unit_type != UNIT_##UNIT_TYPE)) \
135
                        return NULL;                                            \
136
                                                                                \
137
                return (MixedCase*) a;                                          \
138
        }
139

140
/* For casting the various unit types into a unit */
141
#define ACTIVATION_DETAILS(u)                                         \
142
        ({                                                            \
143
                typeof(u) _u_ = (u);                                  \
144
                ActivationDetails *_w_ = _u_ ? &(_u_)->meta : NULL;   \
145
                _w_;                                                  \
146
        })
147

148
ActivationDetails *activation_details_new(Unit *trigger_unit);
149
ActivationDetails *activation_details_ref(ActivationDetails *p);
150
ActivationDetails *activation_details_unref(ActivationDetails *p);
151
void activation_details_serialize(ActivationDetails *p, FILE *f);
152
int activation_details_deserialize(const char *key, const char *value, ActivationDetails **info);
153
int activation_details_append_env(ActivationDetails *info, char ***strv);
154
int activation_details_append_pair(ActivationDetails *info, char ***strv);
155
DEFINE_TRIVIAL_CLEANUP_FUNC(ActivationDetails*, activation_details_unref);
15✔
156

157
typedef struct ActivationDetailsVTable {
158
        /* How much memory does an object of this activation type need */
159
        size_t object_size;
160

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

165
        /* This should free all type-specific variables. It should be idempotent. */
166
        void (*done)(ActivationDetails *info);
167

168
        /* This should serialize all type-specific variables. */
169
        void (*serialize)(ActivationDetails *info, FILE *f);
170

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

174
        /* This should format the type-specific variables for the env block of the spawned service,
175
         * and return the number of added items. */
176
        int (*append_env)(ActivationDetails *info, char ***strv);
177

178
        /* This should append type-specific variables as key/value pairs for the D-Bus property of the job,
179
         * and return the number of added pairs. */
180
        int (*append_pair)(ActivationDetails *info, char ***strv);
181
} ActivationDetailsVTable;
182

183
extern const ActivationDetailsVTable * const activation_details_vtable[_UNIT_TYPE_MAX];
184

185
static inline const ActivationDetailsVTable* ACTIVATION_DETAILS_VTABLE(const ActivationDetails *a) {
81✔
186
        assert(a);
81✔
187
        assert(a->trigger_unit_type < _UNIT_TYPE_MAX);
81✔
188

189
        return activation_details_vtable[a->trigger_unit_type];
81✔
190
}
191

192
/* Newer LLVM versions don't like implicit casts from large pointer types to smaller enums, hence let's add
193
 * explicit type-safe helpers for that. */
194
static inline UnitDependency UNIT_DEPENDENCY_FROM_PTR(const void *p) {
5,302,555✔
195
        return PTR_TO_INT(p);
5,302,555✔
196
}
197

198
static inline void* UNIT_DEPENDENCY_TO_PTR(UnitDependency d) {
8,083,591✔
199
        return INT_TO_PTR(d);
8,083,591✔
200
}
201

202
#include "job.h"
203

204
struct UnitRef {
205
        /* Keeps tracks of references to a unit. This is useful so
206
         * that we can merge two units if necessary and correct all
207
         * references to them */
208

209
        Unit *source, *target;
210
        LIST_FIELDS(UnitRef, refs_by_target);
211
};
212

213
/* The generic, dynamic definition of the unit */
214
typedef struct Unit {
215
        Manager *manager;
216

217
        UnitType type;
218
        UnitLoadState load_state;
219
        Unit *merged_into;
220

221
        char *id;   /* The one special name that we use for identification */
222
        char *instance;
223

224
        Set *aliases; /* All the other names. */
225

226
        /* For each dependency type we can look up another Hashmap with this, whose key is a Unit* object,
227
         * and whose value encodes why the dependency exists, using the UnitDependencyInfo type. i.e. a
228
         * Hashmap(UnitDependency → Hashmap(Unit* → UnitDependencyInfo)) */
229
        Hashmap *dependencies;
230

231
        /* Similar, for RequiresMountsFor= and WantsMountsFor= path dependencies. The key is the path, the
232
         * value the UnitDependencyInfo type */
233
        Hashmap *mounts_for[_UNIT_MOUNT_DEPENDENCY_TYPE_MAX];
234

235
        char *description;
236
        char **documentation;
237

238
        /* The SELinux context used for checking access to this unit read off the unit file at load time (do
239
         * not confuse with the selinux_context field in ExecContext which is the SELinux context we'll set
240
         * for processes) */
241
        char *access_selinux_context;
242

243
        char *fragment_path; /* if loaded from a config file this is the primary path to it */
244
        char *source_path; /* if converted, the source file */
245
        char **dropin_paths;
246

247
        usec_t fragment_not_found_timestamp_hash;
248
        usec_t fragment_mtime;
249
        usec_t source_mtime;
250
        usec_t dropin_mtime;
251

252
        /* If this is a transient unit we are currently writing, this is where we are writing it to */
253
        FILE *transient_file;
254

255
        /* Freezer state */
256
        sd_bus_message *pending_freezer_invocation;
257
        FreezerState freezer_state;
258

259
        /* Job timeout and action to take */
260
        EmergencyAction job_timeout_action;
261
        usec_t job_timeout;
262
        usec_t job_running_timeout;
263
        char *job_timeout_reboot_arg;
264

265
        /* If there is something to do with this unit, then this is the installed job for it */
266
        Job *job;
267

268
        /* JOB_NOP jobs are special and can be installed without disturbing the real job. */
269
        Job *nop_job;
270

271
        /* The slot used for watching NameOwnerChanged signals */
272
        sd_bus_slot *match_bus_slot;
273
        sd_bus_slot *get_name_owner_slot;
274

275
        /* References to this unit from clients */
276
        sd_bus_track *bus_track;
277
        char **deserialized_refs;
278

279
        /* References to this */
280
        LIST_HEAD(UnitRef, refs_by_target);
281

282
        /* Conditions to check */
283
        LIST_HEAD(Condition, conditions);
284
        LIST_HEAD(Condition, asserts);
285

286
        dual_timestamp condition_timestamp;
287
        dual_timestamp assert_timestamp;
288

289
        /* Updated whenever the low-level state changes */
290
        dual_timestamp state_change_timestamp;
291

292
        /* Updated whenever the (high-level) active state enters or leaves the active or inactive states */
293
        dual_timestamp inactive_exit_timestamp;
294
        dual_timestamp active_enter_timestamp;
295
        dual_timestamp active_exit_timestamp;
296
        dual_timestamp inactive_enter_timestamp;
297

298
        /* Per type list */
299
        LIST_FIELDS(Unit, units_by_type);
300

301
        /* Load queue */
302
        LIST_FIELDS(Unit, load_queue);
303

304
        /* D-Bus queue */
305
        LIST_FIELDS(Unit, dbus_queue);
306

307
        /* Cleanup queue */
308
        LIST_FIELDS(Unit, cleanup_queue);
309

310
        /* GC queue */
311
        LIST_FIELDS(Unit, gc_queue);
312

313
        /* CGroup realize members queue */
314
        LIST_FIELDS(Unit, cgroup_realize_queue);
315

316
        /* cgroup empty queue */
317
        LIST_FIELDS(Unit, cgroup_empty_queue);
318

319
        /* cgroup OOM queue */
320
        LIST_FIELDS(Unit, cgroup_oom_queue);
321

322
        /* Target dependencies queue */
323
        LIST_FIELDS(Unit, target_deps_queue);
324

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

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

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

334
        /* Queue of units that should be checked if they can release resources now */
335
        LIST_FIELDS(Unit, release_resources_queue);
336

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

341
        /* Used in SIGCHLD and sd_notify() message event invocation logic to avoid that we dispatch the same event
342
         * multiple times on the same unit. */
343
        unsigned sigchldgen;
344
        unsigned notifygen;
345

346
        /* Used during GC sweeps */
347
        unsigned gc_marker;
348

349
        /* Error code when we didn't manage to load the unit (negative) */
350
        int load_error;
351

352
        /* Put a ratelimit on unit starting */
353
        RateLimit start_ratelimit;
354
        EmergencyAction start_limit_action;
355

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

359
        /* What to do on failure or success */
360
        EmergencyAction success_action, failure_action;
361
        int success_action_exit_status, failure_action_exit_status;
362
        char *reboot_arg;
363

364
        /* Make sure we never enter endless loops with the StopWhenUnneeded=, BindsTo=, Uphold= logic */
365
        RateLimit auto_start_stop_ratelimit;
366
        sd_event_source *auto_start_stop_event_source;
367

368
        /* Reference to a specific UID/GID */
369
        uid_t ref_uid;
370
        gid_t ref_gid;
371

372
        /* Cached unit file state and preset */
373
        UnitFileState unit_file_state;
374
        PresetAction unit_file_preset;
375

376
        /* Low-priority event source which is used to remove watched PIDs that have gone away, and subscribe to any new
377
         * ones which might have appeared. */
378
        sd_event_source *rewatch_pids_event_source;
379

380
        /* How to start OnSuccess=/OnFailure= units */
381
        JobMode on_success_job_mode;
382
        JobMode on_failure_job_mode;
383

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

387
        /* Tweaking the GC logic */
388
        CollectMode collect_mode;
389

390
        /* The current invocation ID */
391
        sd_id128_t invocation_id;
392
        char invocation_id_string[SD_ID128_STRING_MAX]; /* useful when logging */
393

394
        /* Garbage collect us we nobody wants or requires us anymore */
395
        bool stop_when_unneeded;
396

397
        /* Create default dependencies */
398
        bool default_dependencies;
399

400
        /* Configure so that the unit survives a system transition without stopping/starting. */
401
        bool survive_final_kill_signal;
402

403
        /* Refuse manual starting, allow starting only indirectly via dependency. */
404
        bool refuse_manual_start;
405

406
        /* Don't allow the user to stop this unit manually, allow stopping only indirectly via dependency. */
407
        bool refuse_manual_stop;
408

409
        /* Allow isolation requests */
410
        bool allow_isolate;
411

412
        /* Ignore this unit when isolating */
413
        bool ignore_on_isolate;
414

415
        /* Did the last condition check succeed? */
416
        bool condition_result;
417
        bool assert_result;
418

419
        /* Is this a transient unit? */
420
        bool transient;
421

422
        /* Is this a unit that is always running and cannot be stopped? */
423
        bool perpetual;
424

425
        /* When true logs about this unit will be at debug level regardless of other log level settings */
426
        bool debug_invocation;
427

428
        /* Booleans indicating membership of this unit in the various queues */
429
        bool in_load_queue:1;
430
        bool in_dbus_queue:1;
431
        bool in_cleanup_queue:1;
432
        bool in_gc_queue:1;
433
        bool in_cgroup_realize_queue:1;
434
        bool in_cgroup_empty_queue:1;
435
        bool in_cgroup_oom_queue:1;
436
        bool in_target_deps_queue:1;
437
        bool in_stop_when_unneeded_queue:1;
438
        bool in_start_when_upheld_queue:1;
439
        bool in_stop_when_bound_queue:1;
440
        bool in_release_resources_queue:1;
441

442
        bool sent_dbus_new_signal:1;
443

444
        bool job_running_timeout_set:1;
445

446
        bool in_audit:1;
447
        bool on_console:1;
448

449
        bool start_limit_hit:1;
450

451
        /* Did we already invoke unit_coldplug() for this unit? */
452
        bool coldplugged:1;
453

454
        /* For transient units: whether to add a bus track reference after creating the unit */
455
        bool bus_track_add:1;
456

457
        /* Remember which unit state files we created */
458
        bool exported_invocation_id:1;
459
        bool exported_log_level_max:1;
460
        bool exported_log_extra_fields:1;
461
        bool exported_log_ratelimit_interval:1;
462
        bool exported_log_ratelimit_burst:1;
463

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

469
typedef struct UnitStatusMessageFormats {
470
        const char *starting_stopping[2];
471
        const char *finished_start_job[_JOB_RESULT_MAX];
472
        const char *finished_stop_job[_JOB_RESULT_MAX];
473
        /* If this entry is present, it'll be called to provide a context-dependent format string,
474
         * or NULL to fall back to finished_{start,stop}_job; if those are NULL too, fall back to generic. */
475
        const char *(*finished_job)(Unit *u, JobType t, JobResult result);
476
} UnitStatusMessageFormats;
477

478
/* Flags used when writing drop-in files or transient unit files */
479
typedef enum UnitWriteFlags {
480
        /* Write a runtime unit file or drop-in (i.e. one below /run) */
481
        UNIT_RUNTIME                = 1 << 0,
482

483
        /* Write a persistent drop-in (i.e. one below /etc) */
484
        UNIT_PERSISTENT             = 1 << 1,
485

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

489
        /* Apply specifier escaping */
490
        UNIT_ESCAPE_SPECIFIERS      = 1 << 3,
491

492
        /* Escape elements of ExecStart= syntax, incl. prevention of variable expansion */
493
        UNIT_ESCAPE_EXEC_SYNTAX_ENV = 1 << 4,
494

495
        /* Escape elements of ExecStart=: syntax (no variable expansion) */
496
        UNIT_ESCAPE_EXEC_SYNTAX     = 1 << 5,
497

498
        /* Apply C escaping before writing */
499
        UNIT_ESCAPE_C               = 1 << 6,
500
} UnitWriteFlags;
501

502
/* Returns true if neither persistent, nor runtime storage is requested, i.e. this is a check invocation only */
503
static inline bool UNIT_WRITE_FLAGS_NOOP(UnitWriteFlags flags) {
2,509✔
504
        return (flags & (UNIT_RUNTIME|UNIT_PERSISTENT)) == 0;
2,887✔
505
}
506

507
#include "kill.h"
508

509
/* The static const, immutable data about a specific unit type */
510
typedef struct UnitVTable {
511
        /* How much memory does an object of this unit type need */
512
        size_t object_size;
513

514
        /* If greater than 0, the offset into the object where
515
         * ExecContext is found, if the unit type has that */
516
        size_t exec_context_offset;
517

518
        /* If greater than 0, the offset into the object where
519
         * CGroupContext is found, if the unit type has that */
520
        size_t cgroup_context_offset;
521

522
        /* If greater than 0, the offset into the object where
523
         * KillContext is found, if the unit type has that */
524
        size_t kill_context_offset;
525

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

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

534
        /* The name of the configuration file section with the private settings of this unit */
535
        const char *private_section;
536

537
        /* Config file sections this unit type understands, separated
538
         * by NUL chars */
539
        const char *sections;
540

541
        /* This should reset all type-specific variables. This should
542
         * not allocate memory, and is called with zero-initialized
543
         * data. It should hence only initialize variables that need
544
         * to be set != 0. */
545
        void (*init)(Unit *u);
546

547
        /* This should free all type-specific variables. It should be
548
         * idempotent. */
549
        void (*done)(Unit *u);
550

551
        /* Actually load data from disk. This may fail, and should set
552
         * load_state to UNIT_LOADED, UNIT_MERGED or leave it at
553
         * UNIT_STUB if no configuration could be found. */
554
        int (*load)(Unit *u);
555

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

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

569
        void (*dump)(Unit *u, FILE *f, const char *prefix);
570

571
        int (*start)(Unit *u);
572
        int (*stop)(Unit *u);
573
        int (*reload)(Unit *u);
574

575
        /* Clear out the various runtime/state/cache/logs/configuration data */
576
        int (*clean)(Unit *u, ExecCleanMask m);
577

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

583
        /* Return which kind of data can be cleaned */
584
        int (*can_clean)(Unit *u, ExecCleanMask *ret);
585

586
        bool (*can_reload)(Unit *u);
587

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

592
        /* Serialize state and file descriptors that should be carried over into the new
593
         * instance after reexecution. */
594
        int (*serialize)(Unit *u, FILE *f, FDSet *fds);
595

596
        /* Restore one item from the serialization */
597
        int (*deserialize_item)(Unit *u, const char *key, const char *data, FDSet *fds);
598

599
        /* Try to match up fds with what we need for this unit */
600
        void (*distribute_fds)(Unit *u, FDSet *fds);
601

602
        /* Boils down the more complex internal state of this unit to
603
         * a simpler one that the engine can understand */
604
        UnitActiveState (*active_state)(Unit *u);
605

606
        /* Returns the substate specific to this unit type as
607
         * string. This is purely information so that we can give the
608
         * user a more fine grained explanation in which actual state a
609
         * unit is in. */
610
        const char* (*sub_state_to_string)(Unit *u);
611

612
        /* Additionally to UnitActiveState determine whether unit is to be restarted. */
613
        bool (*will_restart)(Unit *u);
614

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

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

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

625
        /* Invoked on every child that died */
626
        void (*sigchld_event)(Unit *u, pid_t pid, int code, int status);
627

628
        /* Reset failed state if we are in failed state */
629
        void (*reset_failed)(Unit *u);
630

631
        /* Called whenever any of the cgroups this unit watches for ran empty */
632
        void (*notify_cgroup_empty)(Unit *u);
633

634
        /* Called whenever an OOM kill event on this unit was seen */
635
        void (*notify_cgroup_oom)(Unit *u, bool managed_oom);
636

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

640
        /* Called whenever we learn a handoff timestamp */
641
        void (*notify_handoff_timestamp)(Unit *u, const struct ucred *ucred, const dual_timestamp *ts);
642

643
        /* Called whenever we learn about a child process */
644
        void (*notify_pidref)(Unit *u, PidRef *parent_pidref, PidRef *child_pidref);
645

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

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

652
        /* Called after at least one property got changed to apply the necessary change */
653
        int (*bus_commit_properties)(Unit *u);
654

655
        /* Return the unit this unit is following */
656
        Unit* (*following)(Unit *u);
657

658
        /* Return the set of units that are following each other */
659
        int (*following_set)(Unit *u, Set **s);
660

661
        /* Invoked each time a unit this unit is triggering changes
662
         * state or gains/loses a job */
663
        void (*trigger_notify)(Unit *u, Unit *trigger);
664

665
        /* Called whenever CLOCK_REALTIME made a jump */
666
        void (*time_change)(Unit *u);
667

668
        /* Called whenever /etc/localtime was modified */
669
        void (*timezone_change)(Unit *u);
670

671
        /* Returns the next timeout of a unit */
672
        int (*get_timeout)(Unit *u, usec_t *timeout);
673

674
        /* Returns the start timeout of a unit */
675
        usec_t (*get_timeout_start_usec)(Unit *u);
676

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

680
        /* Returns the control PID if there is any defined, or NULL. */
681
        PidRef* (*control_pid)(Unit *u);
682

683
        /* Returns true if the unit currently needs access to the console */
684
        bool (*needs_console)(Unit *u);
685

686
        /* Returns the exit status to propagate in case of FailureAction=exit/SuccessAction=exit; usually returns the
687
         * exit code of the "main" process of the service or similar. */
688
        int (*exit_status)(Unit *u);
689

690
        /* Return a copy of the status string pointer. */
691
        const char* (*status_text)(Unit *u);
692

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

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

704
        /* Type specific cleanups. */
705
        void (*shutdown)(Manager *m);
706

707
        /* If this function is set and returns false all jobs for units
708
         * of this type will immediately fail. */
709
        bool (*supported)(void);
710

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

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

719
        /* The strings to print in status messages */
720
        UnitStatusMessageFormats status_message_formats;
721

722
        /* True if transient units of this type are OK */
723
        bool can_transient;
724

725
        /* True if cgroup delegation is permissible */
726
        bool can_delegate;
727

728
        /* True if the unit type triggers other units, i.e. can have a UNIT_TRIGGERS dependency */
729
        bool can_trigger;
730

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

734
        /* True if units of this type shall be startable only once and then never again */
735
        bool once_only;
736

737
        /* Do not serialize this unit when preparing for root switch */
738
        bool exclude_from_switch_root_serialization;
739

740
        /* True if queued jobs of this type should be GC'ed if no other job needs them anymore */
741
        bool gc_jobs;
742

743
        /* True if systemd-oomd can monitor and act on this unit's recursive children's cgroups  */
744
        bool can_set_managed_oom;
745

746
        /* If true, we'll notify plymouth about this unit */
747
        bool notify_plymouth;
748

749
        /* If true, we'll notify a surrounding VMM/container manager about this unit becoming available */
750
        bool notify_supervisor;
751

752
        /* The audit events to generate on start + stop (or 0 if none shall be generated) */
753
        int audit_start_message_type;
754
        int audit_stop_message_type;
755
} UnitVTable;
756

757
extern const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX];
758

759
static inline const UnitVTable* UNIT_VTABLE(const Unit *u) {
29,366,771✔
760
        return unit_vtable[u->type];
29,338,384✔
761
}
762

763
/* For casting a unit into the various unit types */
764
#define DEFINE_CAST(UPPERCASE, MixedCase)                               \
765
        static inline MixedCase* UPPERCASE(Unit *u) {                   \
766
                if (_unlikely_(!u || u->type != UNIT_##UPPERCASE))      \
767
                        return NULL;                                    \
768
                                                                        \
769
                return (MixedCase*) u;                                  \
770
        }
771

772
/* For casting the various unit types into a unit */
773
#define UNIT(u)                                         \
774
        ({                                              \
775
                typeof(u) _u_ = (u);                    \
776
                Unit *_w_ = _u_ ? &(_u_)->meta : NULL;  \
777
                _w_;                                    \
778
        })
779

780
#define UNIT_HAS_EXEC_CONTEXT(u) (UNIT_VTABLE(u)->exec_context_offset > 0)
781
#define UNIT_HAS_CGROUP_CONTEXT(u) (UNIT_VTABLE(u)->cgroup_context_offset > 0)
782
#define UNIT_HAS_KILL_CONTEXT(u) (UNIT_VTABLE(u)->kill_context_offset > 0)
783

784
Unit* unit_has_dependency(const Unit *u, UnitDependencyAtom atom, Unit *other);
785
int unit_get_dependency_array(const Unit *u, UnitDependencyAtom atom, Unit ***ret_array);
786
int unit_get_transitive_dependency_set(Unit *u, UnitDependencyAtom atom, Set **ret);
787

788
static inline Hashmap* unit_get_dependencies(Unit *u, UnitDependency d) {
62,526✔
789
        return hashmap_get(u->dependencies, UNIT_DEPENDENCY_TO_PTR(d));
62,526✔
790
}
791

792
static inline Unit* UNIT_TRIGGER(Unit *u) {
2,378✔
793
        return unit_has_dependency(u, UNIT_ATOM_TRIGGERS, NULL);
2,378✔
794
}
795

796
static inline Unit* UNIT_GET_SLICE(const Unit *u) {
5,892,042✔
797
        return unit_has_dependency(u, UNIT_ATOM_IN_SLICE, NULL);
5,892,041✔
798
}
799

800
Unit* unit_new(Manager *m, size_t size);
801
Unit* unit_free(Unit *u);
802
DEFINE_TRIVIAL_CLEANUP_FUNC(Unit *, unit_free);
627,059✔
803

804
int unit_new_for_name(Manager *m, size_t size, const char *name, Unit **ret);
805
int unit_add_name(Unit *u, const char *name);
806

807
int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference, UnitDependencyMask mask);
808
int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference, UnitDependencyMask mask);
809

810
int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, bool add_reference, UnitDependencyMask mask);
811
int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, bool add_reference, UnitDependencyMask mask);
812

813
int unit_add_exec_dependencies(Unit *u, ExecContext *c);
814

815
int unit_choose_id(Unit *u, const char *name);
816
int unit_set_description(Unit *u, const char *description);
817

818
void unit_release_resources(Unit *u);
819

820
bool unit_may_gc(Unit *u);
821

822
static inline bool unit_is_extrinsic(Unit *u) {
25,185✔
823
        return u->perpetual ||
25,185✔
824
                (UNIT_VTABLE(u)->is_extrinsic && UNIT_VTABLE(u)->is_extrinsic(u));
24,594✔
825
}
826

827
static inline const char* unit_status_text(Unit *u) {
×
828
        if (u && UNIT_VTABLE(u)->status_text)
×
829
                return UNIT_VTABLE(u)->status_text(u);
×
830
        return NULL;
831
}
832

833
void unit_add_to_load_queue(Unit *u);
834
void unit_add_to_dbus_queue(Unit *u);
835
void unit_add_to_cleanup_queue(Unit *u);
836
void unit_add_to_gc_queue(Unit *u);
837
void unit_add_to_target_deps_queue(Unit *u);
838
void unit_submit_to_stop_when_unneeded_queue(Unit *u);
839
void unit_submit_to_start_when_upheld_queue(Unit *u);
840
void unit_submit_to_stop_when_bound_queue(Unit *u);
841
void unit_submit_to_release_resources_queue(Unit *u);
842

843
int unit_merge(Unit *u, Unit *other);
844
int unit_merge_by_name(Unit *u, const char *other);
845

846
Unit *unit_follow_merge(Unit *u) _pure_;
847

848
int unit_load_fragment_and_dropin(Unit *u, bool fragment_required);
849
int unit_load(Unit *unit);
850

851
int unit_set_slice(Unit *u, Unit *slice);
852
int unit_set_default_slice(Unit *u);
853

854
const char* unit_description(Unit *u) _pure_;
855
const char* unit_status_string(Unit *u, char **combined);
856

857
bool unit_has_name(const Unit *u, const char *name);
858

859
UnitActiveState unit_active_state(Unit *u);
860

861
const char* unit_sub_state_to_string(Unit *u);
862

863
bool unit_can_reload(Unit *u) _pure_;
864
bool unit_can_start(Unit *u) _pure_;
865
bool unit_can_stop(Unit *u) _pure_;
866
bool unit_can_isolate(Unit *u) _pure_;
867

868
int unit_start(Unit *u, ActivationDetails *details);
869
int unit_stop(Unit *u);
870
int unit_reload(Unit *u);
871

872
int unit_kill(Unit *u, KillWhom w, int signo, int code, int value, sd_bus_error *ret_error);
873

874
void unit_notify_cgroup_oom(Unit *u, bool managed_oom);
875

876
void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success);
877

878
int unit_watch_pidref(Unit *u, const PidRef *pid, bool exclusive);
879
int unit_watch_pid(Unit *u, pid_t pid, bool exclusive);
880
void unit_unwatch_pidref(Unit *u, const PidRef *pid);
881
void unit_unwatch_pid(Unit *u, pid_t pid);
882
void unit_unwatch_all_pids(Unit *u);
883
void unit_unwatch_pidref_done(Unit *u, PidRef *pidref);
884

885
int unit_enqueue_rewatch_pids(Unit *u);
886
void unit_dequeue_rewatch_pids(Unit *u);
887

888
int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name);
889
int unit_watch_bus_name(Unit *u, const char *name);
890
void unit_unwatch_bus_name(Unit *u, const char *name);
891

892
bool unit_job_is_applicable(Unit *u, JobType j);
893

894
int setenv_unit_path(const char *p);
895

896
char* unit_dbus_path(Unit *u);
897
char* unit_dbus_path_invocation_id(Unit *u);
898

899
int unit_load_related_unit(Unit *u, const char *type, Unit **_found);
900

901
int unit_add_node_dependency(Unit *u, const char *what, UnitDependency d, UnitDependencyMask mask);
902
int unit_add_blockdev_dependency(Unit *u, const char *what, UnitDependencyMask mask);
903

904
int unit_coldplug(Unit *u);
905
void unit_catchup(Unit *u);
906

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

909
bool unit_need_daemon_reload(Unit *u);
910

911
void unit_reset_failed(Unit *u);
912

913
Unit *unit_following(Unit *u);
914
int unit_following_set(Unit *u, Set **s);
915

916
const char* unit_slice_name(Unit *u);
917

918
bool unit_stop_pending(Unit *u) _pure_;
919
bool unit_inactive_or_pending(Unit *u) _pure_;
920
bool unit_active_or_pending(Unit *u);
921
bool unit_will_restart_default(Unit *u);
922
bool unit_will_restart(Unit *u);
923

924
int unit_add_default_target_dependency(Unit *u, Unit *target);
925

926
void unit_start_on_termination_deps(Unit *u, UnitDependencyAtom atom);
927
void unit_trigger_notify(Unit *u);
928

929
UnitFileState unit_get_unit_file_state(Unit *u);
930
PresetAction unit_get_unit_file_preset(Unit *u);
931

932
Unit* unit_ref_set(UnitRef *ref, Unit *source, Unit *target);
933
void unit_ref_unset(UnitRef *ref);
934

935
#define UNIT_DEREF(ref) ((ref).target)
936
#define UNIT_ISSET(ref) (!!(ref).target)
937

938
int unit_patch_contexts(Unit *u);
939

940
ExecContext* unit_get_exec_context(const Unit *u) _pure_;
941
KillContext* unit_get_kill_context(const Unit *u) _pure_;
942
CGroupContext* unit_get_cgroup_context(const Unit *u) _pure_;
943

944
ExecRuntime* unit_get_exec_runtime(const Unit *u) _pure_;
945
CGroupRuntime* unit_get_cgroup_runtime(const Unit *u) _pure_;
946

947
int unit_setup_exec_runtime(Unit *u);
948
CGroupRuntime* unit_setup_cgroup_runtime(Unit *u);
949

950
const char* unit_escape_setting(const char *s, UnitWriteFlags flags, char **buf);
951
char* unit_concat_strv(char **l, UnitWriteFlags flags);
952

953
int unit_write_setting(Unit *u, UnitWriteFlags flags, const char *name, const char *data);
954
int unit_write_settingf(Unit *u, UnitWriteFlags mode, const char *name, const char *format, ...) _printf_(4,5);
955

956
int unit_kill_context(Unit *u, KillOperation k);
957

958
int unit_make_transient(Unit *u);
959

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

962
bool unit_type_supported(UnitType t);
963

964
bool unit_is_pristine(Unit *u);
965

966
bool unit_is_unneeded(Unit *u);
967
bool unit_is_upheld_by_active(Unit *u, Unit **ret_culprit);
968
bool unit_is_bound_by_inactive(Unit *u, Unit **ret_culprit);
969

970
PidRef* unit_control_pid(Unit *u);
971
PidRef* unit_main_pid_full(Unit *u, bool *ret_is_alien);
972
static inline PidRef* unit_main_pid(Unit *u) {
10,381✔
973
        return unit_main_pid_full(u, NULL);
10,381✔
974
}
975

976
void unit_warn_if_dir_nonempty(Unit *u, const char* where);
977
int unit_fail_if_noncanonical(Unit *u, const char* where);
978

979
int unit_test_start_limit(Unit *u);
980

981
int unit_ref_uid_gid(Unit *u, uid_t uid, gid_t gid);
982
void unit_unref_uid_gid(Unit *u, bool destroy_now);
983

984
void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid);
985

986
int unit_set_invocation_id(Unit *u, sd_id128_t id);
987
int unit_acquire_invocation_id(Unit *u);
988

989
int unit_set_exec_params(Unit *s, ExecParameters *p);
990

991
int unit_fork_helper_process(Unit *u, const char *name, bool into_cgroup, PidRef *ret);
992
int unit_fork_and_watch_rm_rf(Unit *u, char **paths, PidRef *ret);
993

994
void unit_remove_dependencies(Unit *u, UnitDependencyMask mask);
995

996
void unit_export_state_files(Unit *u);
997
void unit_unlink_state_files(Unit *u);
998

999
int unit_set_debug_invocation(Unit *u, bool enable);
1000

1001
int unit_prepare_exec(Unit *u);
1002

1003
int unit_warn_leftover_processes(Unit *u, bool start);
1004

1005
bool unit_needs_console(Unit *u);
1006

1007
int unit_pid_attachable(Unit *unit, PidRef *pid, sd_bus_error *error);
1008

1009
static inline bool unit_has_job_type(Unit *u, JobType type) {
7,772✔
1010
        return u && u->job && u->job->type == type;
7,770✔
1011
}
1012

1013
static inline bool unit_log_level_test(const Unit *u, int level) {
350,260✔
1014
        assert(u);
350,260✔
1015
        ExecContext *ec = unit_get_exec_context(u);
350,260✔
1016
        return !ec || ec->log_level_max < 0 || ec->log_level_max >= LOG_PRI(level) || u->debug_invocation;
350,260✔
1017
}
1018

1019
/* unit_log_skip is for cases like ExecCondition= where a unit is considered "done"
1020
 * after some execution, rather than succeeded or failed. */
1021
void unit_log_skip(Unit *u, const char *result);
1022
void unit_log_success(Unit *u);
1023
void unit_log_failure(Unit *u, const char *result);
1024
static inline void unit_log_result(Unit *u, bool success, const char *result) {
1,210✔
1025
        if (success)
1,210✔
1026
                unit_log_success(u);
1,210✔
1027
        else
1028
                unit_log_failure(u, result);
×
1029
}
1,210✔
1030

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

1033
int unit_exit_status(Unit *u);
1034
int unit_success_action_exit_status(Unit *u);
1035
int unit_failure_action_exit_status(Unit *u);
1036

1037
int unit_test_trigger_loaded(Unit *u);
1038

1039
void unit_destroy_runtime_data(Unit *u, const ExecContext *context, bool destroy_runtime_dir);
1040
int unit_clean(Unit *u, ExecCleanMask mask);
1041
int unit_can_clean(Unit *u, ExecCleanMask *ret_mask);
1042

1043
bool unit_can_start_refuse_manual(Unit *u);
1044
bool unit_can_stop_refuse_manual(Unit *u);
1045
bool unit_can_isolate_refuse_manual(Unit *u);
1046

1047
bool unit_can_freeze(const Unit *u);
1048
int unit_freezer_action(Unit *u, FreezerAction action);
1049
void unit_next_freezer_state(Unit *u, FreezerAction action, FreezerState *ret_next, FreezerState *ret_objective);
1050
void unit_set_freezer_state(Unit *u, FreezerState state);
1051
void unit_freezer_complete(Unit *u, FreezerState kernel_state);
1052

1053
int unit_can_live_mount(Unit *u, sd_bus_error *error);
1054
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);
1055

1056
Condition *unit_find_failed_condition(Unit *u);
1057

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

1060
bool unit_passes_filter(Unit *u, char * const *states, char * const *patterns);
1061

1062
int unit_compare_priority(Unit *a, Unit *b);
1063

1064
UnitMountDependencyType unit_mount_dependency_type_from_string(const char *s) _const_;
1065
const char* unit_mount_dependency_type_to_string(UnitMountDependencyType t) _const_;
1066
UnitDependency unit_mount_dependency_type_to_dependency_type(UnitMountDependencyType t) _pure_;
1067

1068
/* Macros which append UNIT= or USER_UNIT= to the message */
1069

1070
#define log_unit_full_errno_zerook(unit, level, error, ...)             \
1071
        ({                                                              \
1072
                const Unit *_u = (unit);                                \
1073
                const int _l = (level);                                 \
1074
                bool _do_log = !(log_get_max_level() < LOG_PRI(_l) ||   \
1075
                        (_u && !unit_log_level_test(_u, _l)));          \
1076
                const ExecContext *_c = _do_log && _u ?                 \
1077
                        unit_get_exec_context(_u) : NULL;               \
1078
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1079
                                     _c ? _c->n_log_extra_fields : 0);  \
1080
                !_do_log ? -ERRNO_VALUE(error) :                        \
1081
                        _u ? log_object_internal(_l, error, PROJECT_FILE, __LINE__, __func__, _u->manager->unit_log_field, _u->id, _u->manager->invocation_log_field, _u->invocation_id_string, ##__VA_ARGS__) : \
1082
                                log_internal(_l, error, PROJECT_FILE, __LINE__, __func__, ##__VA_ARGS__); \
1083
        })
1084

1085
#define log_unit_full_errno(unit, level, error, ...) \
1086
        ({                                                              \
1087
                int _error = (error);                                   \
1088
                ASSERT_NON_ZERO(_error);                                \
1089
                log_unit_full_errno_zerook(unit, level, _error, ##__VA_ARGS__); \
1090
        })
1091

1092
#define log_unit_full(unit, level, ...) (void) log_unit_full_errno_zerook(unit, level, 0, __VA_ARGS__)
1093

1094
#define log_unit_debug(unit, ...)   log_unit_full(unit, LOG_DEBUG, __VA_ARGS__)
1095
#define log_unit_info(unit, ...)    log_unit_full(unit, LOG_INFO, __VA_ARGS__)
1096
#define log_unit_notice(unit, ...)  log_unit_full(unit, LOG_NOTICE, __VA_ARGS__)
1097
#define log_unit_warning(unit, ...) log_unit_full(unit, LOG_WARNING, __VA_ARGS__)
1098
#define log_unit_error(unit, ...)   log_unit_full(unit, LOG_ERR, __VA_ARGS__)
1099

1100
#define log_unit_debug_errno(unit, error, ...)   log_unit_full_errno(unit, LOG_DEBUG, error, __VA_ARGS__)
1101
#define log_unit_info_errno(unit, error, ...)    log_unit_full_errno(unit, LOG_INFO, error, __VA_ARGS__)
1102
#define log_unit_notice_errno(unit, error, ...)  log_unit_full_errno(unit, LOG_NOTICE, error, __VA_ARGS__)
1103
#define log_unit_warning_errno(unit, error, ...) log_unit_full_errno(unit, LOG_WARNING, error, __VA_ARGS__)
1104
#define log_unit_error_errno(unit, error, ...)   log_unit_full_errno(unit, LOG_ERR, error, __VA_ARGS__)
1105

1106
#if LOG_TRACE
1107
#  define log_unit_trace(...)          log_unit_debug(__VA_ARGS__)
1108
#  define log_unit_trace_errno(...)    log_unit_debug_errno(__VA_ARGS__)
1109
#else
1110
#  define log_unit_trace(...)          do {} while (0)
1111
#  define log_unit_trace_errno(e, ...) (-ERRNO_VALUE(e))
1112
#endif
1113

1114
#define log_unit_struct_errno(unit, level, error, ...)                  \
1115
        ({                                                              \
1116
                const Unit *_u = (unit);                                \
1117
                const int _l = (level);                                 \
1118
                bool _do_log = unit_log_level_test(_u, _l);             \
1119
                const ExecContext *_c = _do_log && _u ?                 \
1120
                        unit_get_exec_context(_u) : NULL;               \
1121
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1122
                                     _c ? _c->n_log_extra_fields : 0);  \
1123
                _do_log ?                                               \
1124
                        log_struct_errno(_l, error, __VA_ARGS__, LOG_UNIT_ID(_u)) : \
1125
                        -ERRNO_VALUE(error);                            \
1126
        })
1127

1128
#define log_unit_struct(unit, level, ...) log_unit_struct_errno(unit, level, 0, __VA_ARGS__)
1129

1130
#define log_unit_struct_iovec_errno(unit, level, error, iovec, n_iovec) \
1131
        ({                                                              \
1132
                const Unit *_u = (unit);                                \
1133
                const int _l = (level);                                 \
1134
                bool _do_log = unit_log_level_test(_u, _l);             \
1135
                const ExecContext *_c = _do_log && _u ?                 \
1136
                        unit_get_exec_context(_u) : NULL;               \
1137
                LOG_CONTEXT_PUSH_IOV(_c ? _c->log_extra_fields : NULL,  \
1138
                                     _c ? _c->n_log_extra_fields : 0);  \
1139
                _do_log ?                                               \
1140
                        log_struct_iovec_errno(_l, error, iovec, n_iovec) : \
1141
                        -ERRNO_VALUE(error);                            \
1142
        })
1143

1144
#define log_unit_struct_iovec(unit, level, iovec, n_iovec) log_unit_struct_iovec_errno(unit, level, 0, iovec, n_iovec)
1145

1146
/* Like LOG_MESSAGE(), but with the unit name prefixed. */
1147
#define LOG_UNIT_MESSAGE(unit, fmt, ...) LOG_MESSAGE("%s: " fmt, (unit)->id, ##__VA_ARGS__)
1148
#define LOG_UNIT_ID(unit) (unit)->manager->unit_log_format_string, (unit)->id
1149
#define LOG_UNIT_INVOCATION_ID(unit) (unit)->manager->invocation_log_format_string, (unit)->invocation_id_string
1150

1151
const char* collect_mode_to_string(CollectMode m) _const_;
1152
CollectMode collect_mode_from_string(const char *s) _pure_;
1153

1154
typedef struct UnitForEachDependencyData {
1155
        /* Stores state for the FOREACH macro below for iterating through all deps that have any of the
1156
         * specified dependency atom bits set */
1157
        UnitDependencyAtom match_atom;
1158
        Hashmap *by_type, *by_unit;
1159
        void *current_type;
1160
        Iterator by_type_iterator, by_unit_iterator;
1161
        Unit **current_unit;
1162
} UnitForEachDependencyData;
1163

1164
/* Iterates through all dependencies that have a specific atom in the dependency type set. This tries to be
1165
 * smart: if the atom is unique, we'll directly go to right entry. Otherwise we'll iterate through the
1166
 * per-dependency type hashmap and match all dep that have the right atom set. */
1167
#define _UNIT_FOREACH_DEPENDENCY(other, u, ma, data)                    \
1168
        for (UnitForEachDependencyData data = {                         \
1169
                        .match_atom = (ma),                             \
1170
                        .by_type = (u)->dependencies,                   \
1171
                        .by_type_iterator = ITERATOR_FIRST,             \
1172
                        .current_unit = &(other),                       \
1173
                };                                                      \
1174
             ({                                                         \
1175
                     UnitDependency _dt = _UNIT_DEPENDENCY_INVALID;     \
1176
                     bool _found;                                       \
1177
                                                                        \
1178
                     if (data.by_type && ITERATOR_IS_FIRST(data.by_type_iterator)) { \
1179
                             _dt = unit_dependency_from_unique_atom(data.match_atom); \
1180
                             if (_dt >= 0) {                            \
1181
                                     data.by_unit = hashmap_get(data.by_type, UNIT_DEPENDENCY_TO_PTR(_dt)); \
1182
                                     data.current_type = UNIT_DEPENDENCY_TO_PTR(_dt); \
1183
                                     data.by_type = NULL;               \
1184
                                     _found = !!data.by_unit;           \
1185
                             }                                          \
1186
                     }                                                  \
1187
                     if (_dt < 0)                                       \
1188
                             _found = hashmap_iterate(data.by_type,     \
1189
                                                      &data.by_type_iterator, \
1190
                                                      (void**)&(data.by_unit), \
1191
                                                      (const void**) &(data.current_type)); \
1192
                     _found;                                            \
1193
             }); )                                                      \
1194
                if ((unit_dependency_to_atom(UNIT_DEPENDENCY_FROM_PTR(data.current_type)) & data.match_atom) != 0) \
1195
                        for (data.by_unit_iterator = ITERATOR_FIRST;    \
1196
                                hashmap_iterate(data.by_unit,           \
1197
                                                &data.by_unit_iterator, \
1198
                                                NULL,                   \
1199
                                                (const void**) data.current_unit); )
1200

1201
/* Note: this matches deps that have *any* of the atoms specified in match_atom set */
1202
#define UNIT_FOREACH_DEPENDENCY(other, u, match_atom) \
1203
        _UNIT_FOREACH_DEPENDENCY(other, u, match_atom, UNIQ_T(data, UNIQ))
1204

1205
#define _LOG_CONTEXT_PUSH_UNIT(unit, u, c)                                                              \
1206
        const Unit *u = (unit);                                                                         \
1207
        const ExecContext *c = unit_get_exec_context(u);                                                \
1208
        LOG_CONTEXT_PUSH_KEY_VALUE(u->manager->unit_log_field, u->id);                                  \
1209
        LOG_CONTEXT_PUSH_KEY_VALUE(u->manager->invocation_log_field, u->invocation_id_string);          \
1210
        LOG_CONTEXT_PUSH_IOV(c ? c->log_extra_fields : NULL, c ? c->n_log_extra_fields : 0);            \
1211
        LOG_CONTEXT_SET_LOG_LEVEL(c->log_level_max >= 0 ? c->log_level_max : log_get_max_level())
1212

1213
#define LOG_CONTEXT_PUSH_UNIT(unit) \
1214
        _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