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

systemd / systemd / 14766779411

30 Apr 2025 04:55PM UTC coverage: 72.225% (-0.06%) from 72.282%
14766779411

push

github

web-flow
wait-online: handle varlink connection errors while waiting for DNS (#37283)

Currently, if systemd-networkd-wait-online is started with --dns, and
systemd-resolved is not running, it will exit with an error right away.
Similarly, if systemd-resolved is restarted while waiting for DNS
configuration, systemd-networkd-wait-online will not attempt to
re-connect, and will potentially never see subsequent DNS
configurations.

Improve this by adding socket units for the systemd-resolved varlink
servers, and re-establish the connection in systemd-networkd-wait-online
when we receive `SD_VARLINK_ERROR_DISCONNECTED`.

8 of 16 new or added lines in 2 files covered. (50.0%)

5825 existing lines in 217 files now uncovered.

297168 of 411450 relevant lines covered (72.22%)

695892.62 hits per line

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

63.32
/src/basic/virt.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#if defined(__i386__) || defined(__x86_64__)
4
#include <cpuid.h>
5
#endif
6
#include <errno.h>
7
#include <stdint.h>
8
#include <stdlib.h>
9
#include <threads.h>
10
#include <unistd.h>
11

12
#include "alloc-util.h"
13
#include "dirent-util.h"
14
#include "env-util.h"
15
#include "errno-util.h"
16
#include "fd-util.h"
17
#include "fileio.h"
18
#include "log.h"
19
#include "macro.h"
20
#include "namespace-util.h"
21
#include "process-util.h"
22
#include "stat-util.h"
23
#include "string-table.h"
24
#include "string-util.h"
25
#include "virt.h"
26

27
enum {
28
      SMBIOS_VM_BIT_SET,
29
      SMBIOS_VM_BIT_UNSET,
30
      SMBIOS_VM_BIT_UNKNOWN,
31
};
32

33
static Virtualization detect_vm_cpuid(void) {
477✔
34

35
        /* CPUID is an x86 specific interface. */
36
#if defined(__i386__) || defined(__x86_64__)
37

38
        static const struct {
477✔
39
                const char sig[13];
40
                Virtualization id;
41
        } vm_table[] = {
42
                { "XenVMMXenVMM", VIRTUALIZATION_XEN       },
43
                { "KVMKVMKVM",    VIRTUALIZATION_KVM       }, /* qemu with KVM */
44
                { "Linux KVM Hv", VIRTUALIZATION_KVM       }, /* qemu with KVM + HyperV Enlightenments */
45
                { "TCGTCGTCGTCG", VIRTUALIZATION_QEMU      }, /* qemu without KVM */
46
                /* http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=1009458 */
47
                { "VMwareVMware", VIRTUALIZATION_VMWARE    },
48
                /* https://docs.microsoft.com/en-us/virtualization/hyper-v-on-windows/reference/tlfs */
49
                { "Microsoft Hv", VIRTUALIZATION_MICROSOFT },
50
                /* https://wiki.freebsd.org/bhyve */
51
                { "bhyve bhyve ", VIRTUALIZATION_BHYVE     },
52
                { "QNXQVMBSQG",   VIRTUALIZATION_QNX       },
53
                /* https://projectacrn.org */
54
                { "ACRNACRNACRN", VIRTUALIZATION_ACRN      },
55
                /* https://www.lockheedmartin.com/en-us/products/Hardened-Security-for-Intel-Processors.html */
56
                { "SRESRESRESRE", VIRTUALIZATION_SRE       },
57
                { "Apple VZ",     VIRTUALIZATION_APPLE     },
58
        };
59

60
        uint32_t eax, ebx, ecx, edx;
477✔
61
        bool hypervisor;
477✔
62

63
        /* http://lwn.net/Articles/301888/ */
64

65
        /* First detect whether there is a hypervisor */
66
        if (__get_cpuid(1, &eax, &ebx, &ecx, &edx) == 0)
477✔
67
                return VIRTUALIZATION_NONE;
477✔
68

69
        hypervisor = ecx & 0x80000000U;
477✔
70

71
        if (hypervisor) {
477✔
72
                union {
477✔
73
                        uint32_t sig32[3];
74
                        char text[13];
75
                } sig = {};
477✔
76

77
                /* There is a hypervisor, see what it is */
78
                __cpuid(0x40000000U, eax, ebx, ecx, edx);
477✔
79

80
                sig.sig32[0] = ebx;
477✔
81
                sig.sig32[1] = ecx;
477✔
82
                sig.sig32[2] = edx;
477✔
83

84
                log_debug("Virtualization found, CPUID=%s", sig.text);
477✔
85

86
                FOREACH_ELEMENT(vm, vm_table)
970✔
87
                        if (memcmp_nn(sig.text, sizeof(sig.text),
493✔
88
                                      vm->sig, sizeof(vm->sig)) == 0)
970✔
89
                                return vm->id;
477✔
90

91
                log_debug("Unknown virtualization with CPUID=%s. Add to vm_table[]?", sig.text);
×
92
                return VIRTUALIZATION_VM_OTHER;
×
93
        }
94
#endif
95
        log_debug("No virtualization found in CPUID");
×
96

97
        return VIRTUALIZATION_NONE;
98
}
99

100
static Virtualization detect_vm_device_tree(void) {
4✔
101
#if defined(__arm__) || defined(__aarch64__) || defined(__powerpc__) || defined(__powerpc64__) || defined(__riscv)
102
        _cleanup_free_ char *hvtype = NULL;
103
        int r;
104

105
        r = read_one_line_file("/proc/device-tree/hypervisor/compatible", &hvtype);
106
        if (r == -ENOENT) {
107
                if (access("/proc/device-tree/ibm,partition-name", F_OK) == 0 &&
108
                    access("/proc/device-tree/hmc-managed?", F_OK) == 0 &&
109
                    access("/proc/device-tree/chosen/qemu,graphic-width", F_OK) != 0)
110
                        return VIRTUALIZATION_POWERVM;
111

112
                _cleanup_closedir_ DIR *dir = opendir("/proc/device-tree");
113
                if (!dir) {
114
                        if (errno == ENOENT) {
115
                                log_debug_errno(errno, "/proc/device-tree/ does not exist");
116
                                return VIRTUALIZATION_NONE;
117
                        }
118
                        return log_debug_errno(errno, "Opening /proc/device-tree/ failed: %m");
119
                }
120

121
                FOREACH_DIRENT(de, dir, return log_debug_errno(errno, "Failed to enumerate /proc/device-tree/ contents: %m"))
122
                        if (strstr(de->d_name, "fw-cfg")) {
123
                                log_debug("Virtualization QEMU: \"fw-cfg\" present in /proc/device-tree/%s", de->d_name);
124
                                return VIRTUALIZATION_QEMU;
125
                        }
126

127
                _cleanup_free_ char *compat = NULL;
128
                r = read_one_line_file("/proc/device-tree/compatible", &compat);
129
                if (r < 0 && r != -ENOENT)
130
                        return log_debug_errno(r, "Failed to read /proc/device-tree/compatible: %m");
131
                if (r >= 0) {
132
                        if (streq(compat, "qemu,pseries")) {
133
                                log_debug("Virtualization %s found in /proc/device-tree/compatible", compat);
134
                                return VIRTUALIZATION_QEMU;
135
                        }
136
                        if (streq(compat, "linux,dummy-virt")) {
137
                                /* https://www.kernel.org/doc/Documentation/devicetree/bindings/arm/linux%2Cdummy-virt.yaml */
138
                                log_debug("Generic virtualization %s found in /proc/device-tree/compatible", compat);
139
                                return VIRTUALIZATION_VM_OTHER;
140
                        }
141
                }
142

143
                log_debug("No virtualization found in /proc/device-tree/*");
144
                return VIRTUALIZATION_NONE;
145
        } else if (r < 0)
146
                return r;
147

148
        log_debug("Virtualization %s found in /proc/device-tree/hypervisor/compatible", hvtype);
149
        if (streq(hvtype, "linux,kvm"))
150
                return VIRTUALIZATION_KVM;
151
        else if (strstr(hvtype, "xen"))
152
                return VIRTUALIZATION_XEN;
153
        else if (strstr(hvtype, "vmware"))
154
                return VIRTUALIZATION_VMWARE;
155
        else
156
                return VIRTUALIZATION_VM_OTHER;
157
#else
158
        log_debug("This platform does not support /proc/device-tree");
4✔
159
        return VIRTUALIZATION_NONE;
4✔
160
#endif
161
}
162

163
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64) || defined(__riscv)
164
static Virtualization detect_vm_dmi_vendor(void) {
477✔
165
        static const char* const dmi_vendors[] = {
477✔
166
                "/sys/class/dmi/id/product_name", /* Test this before sys_vendor to detect KVM over QEMU */
167
                "/sys/class/dmi/id/sys_vendor",
168
                "/sys/class/dmi/id/board_vendor",
169
                "/sys/class/dmi/id/bios_vendor",
170
                "/sys/class/dmi/id/product_version", /* For Hyper-V VMs test */
171
                NULL
172
        };
173

174
        static const struct {
477✔
175
                const char *vendor;
176
                Virtualization id;
177
        } dmi_vendor_table[] = {
178
                { "KVM",                   VIRTUALIZATION_KVM       },
179
                { "OpenStack",             VIRTUALIZATION_KVM       }, /* Detect OpenStack instance as KVM in non x86 architecture */
180
                { "KubeVirt",              VIRTUALIZATION_KVM       }, /* Detect KubeVirt instance as KVM in non x86 architecture */
181
                { "Amazon EC2",            VIRTUALIZATION_AMAZON    },
182
                { "QEMU",                  VIRTUALIZATION_QEMU      },
183
                { "VMware",                VIRTUALIZATION_VMWARE    }, /* https://kb.vmware.com/s/article/1009458 */
184
                { "VMW",                   VIRTUALIZATION_VMWARE    },
185
                { "innotek GmbH",          VIRTUALIZATION_ORACLE    },
186
                { "VirtualBox",            VIRTUALIZATION_ORACLE    },
187
                { "Oracle Corporation",    VIRTUALIZATION_ORACLE    }, /* Detect VirtualBox on some proprietary systems via the board_vendor */
188
                { "Xen",                   VIRTUALIZATION_XEN       },
189
                { "Bochs",                 VIRTUALIZATION_BOCHS     },
190
                { "Parallels",             VIRTUALIZATION_PARALLELS },
191
                /* https://wiki.freebsd.org/bhyve */
192
                { "BHYVE",                 VIRTUALIZATION_BHYVE     },
193
                { "Hyper-V",               VIRTUALIZATION_MICROSOFT },
194
                { "Apple Virtualization",  VIRTUALIZATION_APPLE     },
195
                { "Google Compute Engine", VIRTUALIZATION_GOOGLE    }, /* https://cloud.google.com/run/docs/container-contract#sandbox */
196
        };
197
        int r;
477✔
198

199
        STRV_FOREACH(vendor, dmi_vendors) {
970✔
200
                _cleanup_free_ char *s = NULL;
966✔
201

202
                r = read_one_line_file(*vendor, &s);
966✔
203
                if (r < 0) {
966✔
204
                        if (r == -ENOENT)
×
205
                                continue;
×
206

207
                        return r;
208
                }
209

210
                FOREACH_ELEMENT(dmi_vendor, dmi_vendor_table)
11,239✔
211
                        if (startswith(s, dmi_vendor->vendor)) {
10,746✔
212
                                log_debug("Virtualization %s found in DMI (%s)", s, *vendor);
473✔
213
                                return dmi_vendor->id;
473✔
214
                        }
215
        }
216
        log_debug("No virtualization found in DMI vendor table.");
4✔
217
        return VIRTUALIZATION_NONE;
218
}
219

220
static int detect_vm_smbios(void) {
4✔
221
        /* The SMBIOS BIOS Characteristics Extension Byte 2 (Section 2.1.2.2 of
222
         * https://www.dmtf.org/sites/default/files/standards/documents/DSP0134_3.4.0.pdf), specifies that
223
         * the 4th bit being set indicates a VM. The BIOS Characteristics table is exposed via the kernel in
224
         * /sys/firmware/dmi/entries/0-0. Note that in the general case, this bit being unset should not
225
         * imply that the system is running on bare-metal.  For example, QEMU 3.1.0 (with or without KVM)
226
         * with SeaBIOS does not set this bit. */
227
        _cleanup_free_ char *s = NULL;
4✔
228
        size_t readsize;
4✔
229
        int r;
4✔
230

231
        r = read_full_virtual_file("/sys/firmware/dmi/entries/0-0/raw", &s, &readsize);
4✔
232
        if (r < 0) {
4✔
233
                log_debug_errno(r, "Unable to read /sys/firmware/dmi/entries/0-0/raw, "
4✔
234
                                "using the virtualization information found in DMI vendor table, ignoring: %m");
235
                return SMBIOS_VM_BIT_UNKNOWN;
4✔
236
        }
237
        if (readsize < 20 || s[1] < 20) {
×
238
                /* The spec indicates that byte 1 contains the size of the table, 0x12 + the number of
239
                 * extension bytes. The data we're interested in is in extension byte 2, which would be at
240
                 * 0x13. If we didn't read that much data, or if the BIOS indicates that we don't have that
241
                 * much data, we don't infer anything from the SMBIOS. */
242
                log_debug("Only read %zu bytes from /sys/firmware/dmi/entries/0-0/raw (expected 20). "
×
243
                          "Using the virtualization information found in DMI vendor table.", readsize);
244
                return SMBIOS_VM_BIT_UNKNOWN;
×
245
        }
246

247
        uint8_t byte = (uint8_t) s[19];
×
248
        if (byte & (1U<<4)) {
×
249
                log_debug("DMI BIOS Extension table indicates virtualization.");
×
250
                return SMBIOS_VM_BIT_SET;
×
251
        }
UNCOV
252
        log_debug("DMI BIOS Extension table does not indicate virtualization.");
×
253
        return SMBIOS_VM_BIT_UNSET;
254
}
255
#endif /* defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64) */
256

257
static Virtualization detect_vm_dmi(void) {
477✔
258
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64)
259

260
        int r;
477✔
261
        r = detect_vm_dmi_vendor();
477✔
262

263
        /* The DMI vendor tables in /sys/class/dmi/id don't help us distinguish between Amazon EC2
264
         * virtual machines and bare-metal instances, so we need to look at SMBIOS. */
265
        if (r == VIRTUALIZATION_AMAZON) {
477✔
266
                switch (detect_vm_smbios()) {
×
267
                case SMBIOS_VM_BIT_SET:
268
                        return VIRTUALIZATION_AMAZON;
269
                case SMBIOS_VM_BIT_UNSET:
×
270
                        return VIRTUALIZATION_NONE;
×
271
                case SMBIOS_VM_BIT_UNKNOWN: {
×
272
                        /* The DMI information we are after is only accessible to the root user,
273
                         * so we fallback to using the product name which is less restricted
274
                         * to distinguish metal systems from virtualized instances */
275
                        _cleanup_free_ char *s = NULL;
×
276
                        const char *e;
×
277

278
                        r = read_full_virtual_file("/sys/class/dmi/id/product_name", &s, NULL);
×
279
                        /* In EC2, virtualized is much more common than metal, so if for some reason
280
                         * we fail to read the DMI data, assume we are virtualized. */
281
                        if (r < 0) {
×
282
                                log_debug_errno(r, "Can't read /sys/class/dmi/id/product_name,"
×
283
                                                " assuming virtualized: %m");
284
                                return VIRTUALIZATION_AMAZON;
×
285
                        }
286
                        e = strstrafter(truncate_nl(s), ".metal");
×
287
                        if (e && IN_SET(*e, 0, '-')) {
×
288
                                log_debug("DMI product name has '.metal', assuming no virtualization");
×
289
                                return VIRTUALIZATION_NONE;
×
290
                        } else
291
                                return VIRTUALIZATION_AMAZON;
292
                }
293
                default:
×
294
                        assert_not_reached();
×
295
              }
296
        }
297

298
        /* If we haven't identified a VM, but the firmware indicates that there is one, indicate as much. We
299
         * have no further information about what it is. */
300
        if (r == VIRTUALIZATION_NONE && detect_vm_smbios() == SMBIOS_VM_BIT_SET)
477✔
301
                return VIRTUALIZATION_VM_OTHER;
×
302
        return r;
303
#else
304
        return VIRTUALIZATION_NONE;
305
#endif
306
}
307

308
#define XENFEAT_dom0 11 /* xen/include/public/features.h */
309
#define PATH_FEATURES "/sys/hypervisor/properties/features"
310
/* Returns -errno, or 0 for domU, or 1 for dom0 */
311
static int detect_vm_xen_dom0(void) {
×
312
        _cleanup_free_ char *domcap = NULL;
×
313
        int r;
×
314

315
        r = read_one_line_file(PATH_FEATURES, &domcap);
×
316
        if (r < 0 && r != -ENOENT)
×
317
                return r;
318
        if (r >= 0) {
×
319
                unsigned long features;
×
320

321
                /* Here, we need to use sscanf() instead of safe_atoul()
322
                 * as the string lacks the leading "0x". */
323
                r = sscanf(domcap, "%lx", &features);
×
324
                if (r == 1) {
×
325
                        r = !!(features & (1U << XENFEAT_dom0));
×
326
                        log_debug("Virtualization XEN, found %s with value %08lx, "
×
327
                                  "XENFEAT_dom0 (indicating the 'hardware domain') is%s set.",
328
                                  PATH_FEATURES, features, r ? "" : " not");
329
                        return r;
×
330
                }
331
                log_debug("Virtualization XEN, found %s, unhandled content '%s'",
×
332
                          PATH_FEATURES, domcap);
333
        }
334

335
        r = read_one_line_file("/proc/xen/capabilities", &domcap);
×
336
        if (r == -ENOENT) {
×
337
                log_debug("Virtualization XEN because /proc/xen/capabilities does not exist");
×
338
                return 0;
×
339
        }
340
        if (r < 0)
×
341
                return r;
342

343
        for (const char *i = domcap;;) {
×
344
                _cleanup_free_ char *cap = NULL;
×
345

346
                r = extract_first_word(&i, &cap, ",", 0);
×
347
                if (r < 0)
×
348
                        return r;
349
                if (r == 0) {
×
350
                        log_debug("Virtualization XEN DomU found (/proc/xen/capabilities)");
×
351
                        return 0;
×
352
                }
353

354
                if (streq(cap, "control_d")) {
×
355
                        log_debug("Virtualization XEN Dom0 ignored (/proc/xen/capabilities)");
×
356
                        return 1;
×
357
                }
358
        }
359
}
360

361
static Virtualization detect_vm_xen(void) {
477✔
362
        /* The presence of /proc/xen indicates some form of a Xen domain
363
           The check for Dom0 is handled outside this function */
364
        if (access("/proc/xen", F_OK) < 0) {
477✔
365
                log_debug("Virtualization XEN not found, /proc/xen does not exist");
477✔
366
                return VIRTUALIZATION_NONE;
477✔
367
        }
368
        log_debug("Virtualization XEN found (/proc/xen exists)");
×
369
        return VIRTUALIZATION_XEN;
370
}
371

372
static Virtualization detect_vm_hypervisor(void) {
4✔
373
        _cleanup_free_ char *hvtype = NULL;
4✔
374
        int r;
4✔
375

376
        r = read_one_line_file("/sys/hypervisor/type", &hvtype);
4✔
377
        if (r == -ENOENT)
4✔
378
                return VIRTUALIZATION_NONE;
379
        if (r < 0)
×
380
                return r;
381

382
        log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
×
383

384
        if (streq(hvtype, "xen"))
×
385
                return VIRTUALIZATION_XEN;
386
        else
387
                return VIRTUALIZATION_VM_OTHER;
×
388
}
389

390
static Virtualization detect_vm_uml(void) {
477✔
391
        _cleanup_fclose_ FILE *f = NULL;
477✔
392
        int r;
477✔
393

394
        /* Detect User-Mode Linux by reading /proc/cpuinfo */
395
        f = fopen("/proc/cpuinfo", "re");
477✔
396
        if (!f) {
477✔
397
                if (errno == ENOENT) {
×
398
                        log_debug("/proc/cpuinfo not found, assuming no UML virtualization.");
×
399
                        return VIRTUALIZATION_NONE;
×
400
                }
401
                return -errno;
×
402
        }
403

404
        for (;;) {
1,431✔
405
                _cleanup_free_ char *line = NULL;
477✔
406
                const char *t;
954✔
407

408
                r = read_line(f, LONG_LINE_MAX, &line);
954✔
409
                if (r < 0)
954✔
410
                        return r;
411
                if (r == 0)
954✔
412
                        break;
413

414
                t = startswith(line, "vendor_id\t: ");
954✔
415
                if (t) {
954✔
416
                        if (startswith(t, "User Mode Linux")) {
477✔
417
                                log_debug("UML virtualization found in /proc/cpuinfo");
×
418
                                return VIRTUALIZATION_UML;
×
419
                        }
420

421
                        break;
422
                }
423
        }
424

425
        log_debug("UML virtualization not found in /proc/cpuinfo.");
477✔
426
        return VIRTUALIZATION_NONE;
427
}
428

429
static Virtualization detect_vm_zvm(void) {
4✔
430

431
#if defined(__s390__)
432
        _cleanup_free_ char *t = NULL;
433
        int r;
434

435
        r = get_proc_field("/proc/sysinfo", "VM00 Control Program", WHITESPACE, &t);
436
        if (r == -ENOENT)
437
                return VIRTUALIZATION_NONE;
438
        if (r < 0)
439
                return r;
440

441
        log_debug("Virtualization %s found in /proc/sysinfo", t);
442
        if (streq(t, "z/VM"))
443
                return VIRTUALIZATION_ZVM;
444
        else
445
                return VIRTUALIZATION_KVM;
446
#else
447
        log_debug("This platform does not support /proc/sysinfo");
4✔
448
        return VIRTUALIZATION_NONE;
4✔
449
#endif
450
}
451

452
/* Returns a short identifier for the various VM implementations */
453
Virtualization detect_vm(void) {
1,257✔
454
        static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
1,257✔
455
        bool other = false, hyperv = false;
1,257✔
456
        int xen_dom0 = 0;
1,257✔
457
        Virtualization v, dmi;
1,257✔
458

459
        if (cached_found >= 0)
1,257✔
460
                return cached_found;
461

462
        /* We have to use the correct order here:
463
         *
464
         * → First, try to detect Oracle Virtualbox, Amazon EC2 Nitro, Parallels, and Google Compute Engine,
465
         *   even if they use KVM, as well as Xen, even if it cloaks as Microsoft Hyper-V. Attempt to detect
466
         *   UML at this stage too, since it runs as a user-process nested inside other VMs. Also check for
467
         *   Xen now, because Xen PV mode does not override CPUID when nested inside another hypervisor.
468
         *
469
         * → Second, try to detect from CPUID. This will report KVM for whatever software is used even if
470
         *   info in DMI is overwritten.
471
         *
472
         * → Third, try to detect from DMI. */
473

474
        dmi = detect_vm_dmi();
477✔
475
        if (IN_SET(dmi,
477✔
476
                   VIRTUALIZATION_ORACLE,
477
                   VIRTUALIZATION_XEN,
478
                   VIRTUALIZATION_AMAZON,
479
                   VIRTUALIZATION_PARALLELS,
480
                   VIRTUALIZATION_GOOGLE)) {
481
                v = dmi;
×
482
                goto finish;
×
483
        }
484

485
        /* Detect UML */
486
        v = detect_vm_uml();
477✔
487
        if (v < 0)
477✔
488
                return v;
489
        if (v != VIRTUALIZATION_NONE)
477✔
490
                goto finish;
×
491

492
        /* Detect Xen */
493
        v = detect_vm_xen();
477✔
494
        if (v < 0)
477✔
495
                return v;
496
        if (v == VIRTUALIZATION_XEN) {
477✔
497
                 /* If we are Dom0, then we expect to not report as a VM. However, as we might be nested
498
                  * inside another hypervisor which can be detected via the CPUID check, wait to report this
499
                  * until after the CPUID check. */
500
                xen_dom0 = detect_vm_xen_dom0();
×
501
                if (xen_dom0 < 0)
×
502
                        return xen_dom0;
503
                if (xen_dom0 == 0)
×
504
                        goto finish;
×
505
        } else if (v != VIRTUALIZATION_NONE)
477✔
506
                assert_not_reached();
×
507

508
        /* Detect from CPUID */
509
        v = detect_vm_cpuid();
477✔
510
        if (v < 0)
477✔
511
                return v;
512
        if (v == VIRTUALIZATION_MICROSOFT)
477✔
513
                /* QEMU sets the CPUID string to hyperv's, in case it provides hyperv enlightenments. Let's
514
                 * hence not return Microsoft here but just use the other mechanisms first to make a better
515
                 * decision. */
516
                hyperv = true;
517
        else if (v == VIRTUALIZATION_VM_OTHER)
473✔
518
                other = true;
519
        else if (v != VIRTUALIZATION_NONE)
473✔
520
                goto finish;
473✔
521

522
        /* If we are in Dom0 and have not yet finished, finish with the result of detect_vm_cpuid */
523
        if (xen_dom0 > 0)
4✔
524
                goto finish;
×
525

526
        /* Now, let's get back to DMI */
527
        if (dmi < 0)
4✔
528
                return dmi;
529
        if (dmi == VIRTUALIZATION_VM_OTHER)
4✔
530
                other = true;
531
        else if (dmi != VIRTUALIZATION_NONE) {
4✔
532
                v = dmi;
×
533
                goto finish;
×
534
        }
535

536
        /* Check high-level hypervisor sysfs file */
537
        v = detect_vm_hypervisor();
4✔
538
        if (v < 0)
4✔
539
                return v;
540
        if (v == VIRTUALIZATION_VM_OTHER)
4✔
541
                other = true;
542
        else if (v != VIRTUALIZATION_NONE)
4✔
543
                goto finish;
×
544

545
        v = detect_vm_device_tree();
4✔
546
        if (v < 0)
4✔
547
                return v;
548
        if (v == VIRTUALIZATION_VM_OTHER)
4✔
549
                other = true;
550
        else if (v != VIRTUALIZATION_NONE)
4✔
551
                goto finish;
×
552

553
        v = detect_vm_zvm();
4✔
554
        if (v < 0)
4✔
555
                return v;
556

557
finish:
4✔
558
        /* None of the checks above gave us a clear answer, hence let's now use fallback logic: if hyperv
559
         * enlightenments are available but the VMM wasn't recognized as anything yet, it's probably
560
         * Microsoft. */
561
        if (v == VIRTUALIZATION_NONE) {
477✔
562
                if (hyperv)
4✔
563
                        v = VIRTUALIZATION_MICROSOFT;
564
                else if (other)
×
565
                        v = VIRTUALIZATION_VM_OTHER;
×
566
        }
567

568
        cached_found = v;
477✔
569
        log_debug("Found VM virtualization %s", virtualization_to_string(v));
477✔
570
        return v;
571
}
572

573
static const char *const container_table[_VIRTUALIZATION_MAX] = {
574
        [VIRTUALIZATION_LXC]            = "lxc",
575
        [VIRTUALIZATION_LXC_LIBVIRT]    = "lxc-libvirt",
576
        [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
577
        [VIRTUALIZATION_DOCKER]         = "docker",
578
        [VIRTUALIZATION_PODMAN]         = "podman",
579
        [VIRTUALIZATION_RKT]            = "rkt",
580
        [VIRTUALIZATION_WSL]            = "wsl",
581
        [VIRTUALIZATION_PROOT]          = "proot",
582
        [VIRTUALIZATION_POUCH]          = "pouch",
583
};
584

585
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
3,779✔
586

587
static int running_in_pidns(void) {
4,712✔
588
        int r;
4,712✔
589

590
        r = namespace_is_init(NAMESPACE_PID);
4,712✔
591
        if (r < 0)
4,712✔
592
                return log_debug_errno(r, "Failed to test if in root PID namespace, ignoring: %m");
12✔
593

594
        return !r;
4,700✔
595
}
596

597
static Virtualization detect_container_files(void) {
4,712✔
598
        static const struct {
4,712✔
599
                const char *file_path;
600
                Virtualization id;
601
        } container_file_table[] = {
602
                /* https://github.com/containers/podman/issues/6192 */
603
                /* https://github.com/containers/podman/issues/3586#issuecomment-661918679 */
604
                { "/run/.containerenv", VIRTUALIZATION_PODMAN },
605
                /* https://github.com/moby/moby/issues/18355 */
606
                /* Docker must be the last in this table, see below. */
607
                { "/.dockerenv",        VIRTUALIZATION_DOCKER },
608
        };
609

610
        FOREACH_ELEMENT(file, container_file_table) {
14,136✔
611
                if (access(file->file_path, F_OK) >= 0)
9,424✔
612
                        return file->id;
×
613

614
                if (errno != ENOENT)
9,424✔
615
                        log_debug_errno(errno,
9,424✔
616
                                        "Checking if %s exists failed, ignoring: %m",
617
                                        file->file_path);
618
        }
619

620
        return VIRTUALIZATION_NONE;
621
}
622

623
Virtualization detect_container(void) {
203,699✔
624
        static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
203,699✔
625
        _cleanup_free_ char *m = NULL, *o = NULL, *p = NULL;
203,699✔
626
        const char *e = NULL;
203,699✔
627
        Virtualization v;
203,699✔
628
        int r;
203,699✔
629

630
        if (cached_found >= 0)
203,699✔
631
                return cached_found;
632

633
        /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
634
        if (access("/proc/vz", F_OK) < 0) {
8,491✔
635
                if (errno != ENOENT)
8,491✔
636
                        log_debug_errno(errno, "Failed to check if /proc/vz exists, ignoring: %m");
×
637
        } else if (access("/proc/bc", F_OK) < 0) {
×
638
                if (errno == ENOENT) {
×
639
                        v = VIRTUALIZATION_OPENVZ;
×
640
                        goto finish;
×
641
                }
642

643
                log_debug_errno(errno, "Failed to check if /proc/bc exists, ignoring: %m");
×
644
        }
645

646
        /* "Official" way of detecting WSL https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364 */
647
        r = read_one_line_file("/proc/sys/kernel/osrelease", &o);
8,491✔
648
        if (r < 0)
8,491✔
649
                log_debug_errno(r, "Failed to read /proc/sys/kernel/osrelease, ignoring: %m");
12✔
650
        else if (strstr(o, "Microsoft") || strstr(o, "WSL")) {
8,479✔
651
                v = VIRTUALIZATION_WSL;
×
652
                goto finish;
×
653
        }
654

655
        /* proot doesn't use PID namespacing, so we can just check if we have a matching tracer for this
656
         * invocation without worrying about it being elsewhere.
657
         */
658
        r = get_proc_field("/proc/self/status", "TracerPid", WHITESPACE, &p);
8,491✔
659
        if (r < 0)
8,491✔
660
                log_debug_errno(r, "Failed to read our own trace PID, ignoring: %m");
12✔
661
        else if (!streq(p, "0")) {
8,479✔
662
                pid_t ptrace_pid;
×
663

664
                r = parse_pid(p, &ptrace_pid);
×
665
                if (r < 0)
×
666
                        log_debug_errno(r, "Failed to parse our own tracer PID, ignoring: %m");
×
667
                else {
668
                        _cleanup_free_ char *ptrace_comm = NULL;
×
669
                        const char *pf;
×
670

671
                        pf = procfs_file_alloca(ptrace_pid, "comm");
×
672
                        r = read_one_line_file(pf, &ptrace_comm);
×
673
                        if (r < 0)
×
674
                                log_debug_errno(r, "Failed to read %s, ignoring: %m", pf);
×
675
                        else if (startswith(ptrace_comm, "proot")) {
×
676
                                v = VIRTUALIZATION_PROOT;
×
677
                                goto finish;
×
678
                        }
679
                }
680
        }
681

682
        /* The container manager might have placed this in the /run/host/ hierarchy for us, which is best
683
         * because we can be consumed just like that, without special privileges. */
684
        r = read_one_line_file("/run/host/container-manager", &m);
8,491✔
685
        if (r > 0) {
8,491✔
686
                e = m;
3,779✔
687
                goto translate_name;
3,779✔
688
        }
689
        if (!IN_SET(r, -ENOENT, 0))
4,712✔
690
                return log_debug_errno(r, "Failed to read /run/host/container-manager: %m");
×
691

692
        if (getpid_cached() == 1) {
4,712✔
693
                /* If we are PID 1 we can just check our own environment variable, and that's authoritative.
694
                 * We distinguish three cases:
695
                 * - the variable is not defined → we jump to other checks
696
                 * - the variable is defined to an empty value → we are not in a container
697
                 * - anything else → some container, either one of the known ones or "container-other"
698
                 */
699
                e = getenv("container");
21✔
700
                if (!e)
21✔
701
                        goto check_files;
21✔
702
                if (isempty(e)) {
×
703
                        v = VIRTUALIZATION_NONE;
×
704
                        goto finish;
×
705
                }
706

707
                goto translate_name;
×
708
        }
709

710
        /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
711
         * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
712
        r = read_one_line_file("/run/systemd/container", &m);
4,691✔
713
        if (r > 0) {
4,691✔
714
                e = m;
×
715
                goto translate_name;
×
716
        }
717
        if (!IN_SET(r, -ENOENT, 0))
4,691✔
718
                return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
×
719

720
        /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
721
        r = getenv_for_pid(1, "container", &m);
4,691✔
722
        if (r > 0) {
4,691✔
723
                e = m;
×
724
                goto translate_name;
×
725
        }
726
        if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
4,691✔
727
                log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
1,847✔
728

729
check_files:
2,844✔
730
        /* Check for existence of some well-known files. We only do this after checking
731
         * for other specific container managers, otherwise we risk mistaking another
732
         * container manager for Docker: the /.dockerenv file could inadvertently end up
733
         * in a file system image. */
734
        v = detect_container_files();
4,712✔
735
        if (v < 0)
4,712✔
736
                return v;
737
        if (v != VIRTUALIZATION_NONE)
4,712✔
738
                goto finish;
×
739

740
        /* Finally, the root pid namespace has an hardcoded inode number of 0xEFFFFFFC since kernel 3.8, so
741
         * if all else fails we can check the inode number of our pid namespace and compare it. */
742
        if (running_in_pidns() > 0) {
4,712✔
743
                log_debug("Running in a pid namespace, assuming unknown container manager.");
1✔
744
                v = VIRTUALIZATION_CONTAINER_OTHER;
1✔
745
                goto finish;
1✔
746
        }
747

748
        /* If none of that worked, give up, assume no container manager. */
749
        v = VIRTUALIZATION_NONE;
4,711✔
750
        goto finish;
4,711✔
751

752
translate_name:
3,779✔
753
        if (streq(e, "oci")) {
3,779✔
754
                /* Some images hardcode container=oci, but OCI is not a specific container manager.
755
                 * Try to detect one based on well-known files. */
756
                v = detect_container_files();
×
757
                if (v == VIRTUALIZATION_NONE)
×
758
                        v = VIRTUALIZATION_CONTAINER_OTHER;
×
759
                goto finish;
×
760
        }
761
        v = container_from_string(e);
3,779✔
762
        if (v < 0)
3,779✔
763
                v = VIRTUALIZATION_CONTAINER_OTHER;
×
764

765
finish:
3,779✔
766
        log_debug("Found container virtualization %s.", virtualization_to_string(v));
8,491✔
767
        cached_found = v;
8,491✔
768
        return v;
8,491✔
769
}
770

771
Virtualization detect_virtualization(void) {
1,570✔
772
        int v;
1,570✔
773

774
        v = detect_container();
1,570✔
775
        if (v != VIRTUALIZATION_NONE)
1,570✔
776
                return v;
777

778
        return detect_vm();
1,159✔
779
}
780

781
int running_in_userns(void) {
79✔
782
        int r;
79✔
783

784
        r = namespace_is_init(NAMESPACE_USER);
79✔
785
        if (r < 0)
79✔
786
                return log_debug_errno(r, "Failed to test if in root user namespace, ignoring: %m");
×
787

788
        return !r;
79✔
789
}
790

791
int running_in_chroot(void) {
13,553✔
792
        int r;
13,553✔
793

794
        /* If we're PID1, /proc may not be mounted (and most likely we're not in a chroot). But PID1 will
795
         * mount /proc, so all other programs can assume that if /proc is *not* available, we're in some
796
         * chroot. */
797

798
        r = getenv_bool("SYSTEMD_IN_CHROOT");
13,553✔
799
        if (r >= 0)
13,553✔
800
                return r > 0;
4✔
801
        if (r != -ENXIO)
13,549✔
802
                log_debug_errno(r, "Failed to parse $SYSTEMD_IN_CHROOT, ignoring: %m");
×
803

804
        /* Deprecated but kept for backwards compatibility. */
805
        if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
13,549✔
806
                return 0;
807

808
        r = pidref_from_same_root_fs(&PIDREF_MAKE_FROM_PID(1), NULL);
13,549✔
809
        if (r == -ENOSYS) {
13,549✔
810
                if (getpid_cached() == 1)
×
811
                        return false; /* We will mount /proc, assuming we're not in a chroot. */
812

813
                log_debug("/proc/ is not mounted, assuming we're in a chroot.");
×
814
                return true;
×
815
        }
816
        if (r == -ESRCH) /* We must have a fake /proc/, we can't do the check properly. */
13,549✔
817
                return -ENOSYS;
818
        if (r < 0)
13,549✔
819
                return r;
820

821
        return r == 0;
13,432✔
822
}
823

824
#if defined(__i386__) || defined(__x86_64__)
825
struct cpuid_table_entry {
826
        uint32_t flag_bit;
827
        const char *name;
828
};
829

830
static const struct cpuid_table_entry leaf1_edx[] = {
831
        {  0, "fpu"     },
832
        {  1, "vme"     },
833
        {  2, "de"      },
834
        {  3, "pse"     },
835
        {  4, "tsc"     },
836
        {  5, "msr"     },
837
        {  6, "pae"     },
838
        {  7, "mce"     },
839
        {  8, "cx8"     },
840
        {  9, "apic"    },
841
        { 11, "sep"     },
842
        { 12, "mtrr"    },
843
        { 13, "pge"     },
844
        { 14, "mca"     },
845
        { 15, "cmov"    },
846
        { 16, "pat"     },
847
        { 17, "pse36"   },
848
        { 19, "clflush" },
849
        { 23, "mmx"     },
850
        { 24, "fxsr"    },
851
        { 25, "sse"     },
852
        { 26, "sse2"    },
853
        { 28, "ht"      },
854
};
855

856
static const struct cpuid_table_entry leaf1_ecx[] = {
857
        {  0, "pni"     },
858
        {  1, "pclmul"  },
859
        {  3, "monitor" },
860
        {  9, "ssse3"   },
861
        { 12, "fma3"    },
862
        { 13, "cx16"    },
863
        { 19, "sse4_1"  },
864
        { 20, "sse4_2"  },
865
        { 22, "movbe"   },
866
        { 23, "popcnt"  },
867
        { 25, "aes"     },
868
        { 26, "xsave"   },
869
        { 27, "osxsave" },
870
        { 28, "avx"     },
871
        { 29, "f16c"    },
872
        { 30, "rdrand"  },
873
};
874

875
static const struct cpuid_table_entry leaf7_ebx[] = {
876
        {  3, "bmi1"   },
877
        {  5, "avx2"   },
878
        {  8, "bmi2"   },
879
        { 18, "rdseed" },
880
        { 19, "adx"    },
881
        { 29, "sha_ni" },
882
};
883

884
static const struct cpuid_table_entry leaf81_edx[] = {
885
        { 11, "syscall" },
886
        { 27, "rdtscp"  },
887
        { 29, "lm"      },
888
};
889

890
static const struct cpuid_table_entry leaf81_ecx[] = {
891
        {  0, "lahf_lm" },
892
        {  5, "abm"     },
893
};
894

895
static const struct cpuid_table_entry leaf87_edx[] = {
896
        {  8, "constant_tsc" },
897
};
898

899
static bool given_flag_in_set(const char *flag, const struct cpuid_table_entry *set, size_t set_size, uint32_t val) {
14✔
900
        for (size_t i = 0; i < set_size; i++) {
132✔
901
                if ((UINT32_C(1) << set[i].flag_bit) & val &&
119✔
902
                                streq(flag, set[i].name))
116✔
903
                        return true;
904
        }
905
        return false;
906
}
907

908
static bool real_has_cpu_with_flag(const char *flag) {
3✔
909
        uint32_t eax, ebx, ecx, edx;
3✔
910

911
        if (__get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
3✔
912
                if (given_flag_in_set(flag, leaf1_ecx, ELEMENTSOF(leaf1_ecx), ecx))
3✔
913
                        return true;
3✔
914

915
                if (given_flag_in_set(flag, leaf1_edx, ELEMENTSOF(leaf1_edx), edx))
3✔
916
                        return true;
917
        }
918

919
        if (__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
2✔
920
                if (given_flag_in_set(flag, leaf7_ebx, ELEMENTSOF(leaf7_ebx), ebx))
2✔
921
                        return true;
922
        }
923

924
        if (__get_cpuid(0x80000001U, &eax, &ebx, &ecx, &edx)) {
2✔
925
                if (given_flag_in_set(flag, leaf81_ecx, ELEMENTSOF(leaf81_ecx), ecx))
2✔
926
                        return true;
927

928
                if (given_flag_in_set(flag, leaf81_edx, ELEMENTSOF(leaf81_edx), edx))
2✔
929
                        return true;
930
        }
931

932
        if (__get_cpuid(0x80000007U, &eax, &ebx, &ecx, &edx))
2✔
933
                if (given_flag_in_set(flag, leaf87_edx, ELEMENTSOF(leaf87_edx), edx))
2✔
934
                        return true;
×
935

936
        return false;
937
}
938
#endif
939

940
bool has_cpu_with_flag(const char *flag) {
3✔
941
        /* CPUID is an x86 specific interface. Assume on all others that no CPUs have those flags. */
942
#if defined(__i386__) || defined(__x86_64__)
943
        return real_has_cpu_with_flag(flag);
3✔
944
#else
945
        return false;
946
#endif
947
}
948

949
static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
950
        [VIRTUALIZATION_NONE]            = "none",
951
        [VIRTUALIZATION_KVM]             = "kvm",
952
        [VIRTUALIZATION_AMAZON]          = "amazon",
953
        [VIRTUALIZATION_QEMU]            = "qemu",
954
        [VIRTUALIZATION_BOCHS]           = "bochs",
955
        [VIRTUALIZATION_XEN]             = "xen",
956
        [VIRTUALIZATION_UML]             = "uml",
957
        [VIRTUALIZATION_VMWARE]          = "vmware",
958
        [VIRTUALIZATION_ORACLE]          = "oracle",
959
        [VIRTUALIZATION_MICROSOFT]       = "microsoft",
960
        [VIRTUALIZATION_ZVM]             = "zvm",
961
        [VIRTUALIZATION_PARALLELS]       = "parallels",
962
        [VIRTUALIZATION_BHYVE]           = "bhyve",
963
        [VIRTUALIZATION_QNX]             = "qnx",
964
        [VIRTUALIZATION_ACRN]            = "acrn",
965
        [VIRTUALIZATION_POWERVM]         = "powervm",
966
        [VIRTUALIZATION_APPLE]           = "apple",
967
        [VIRTUALIZATION_SRE]             = "sre",
968
        [VIRTUALIZATION_GOOGLE]          = "google",
969
        [VIRTUALIZATION_VM_OTHER]        = "vm-other",
970

971
        [VIRTUALIZATION_SYSTEMD_NSPAWN]  = "systemd-nspawn",
972
        [VIRTUALIZATION_LXC_LIBVIRT]     = "lxc-libvirt",
973
        [VIRTUALIZATION_LXC]             = "lxc",
974
        [VIRTUALIZATION_OPENVZ]          = "openvz",
975
        [VIRTUALIZATION_DOCKER]          = "docker",
976
        [VIRTUALIZATION_PODMAN]          = "podman",
977
        [VIRTUALIZATION_RKT]             = "rkt",
978
        [VIRTUALIZATION_WSL]             = "wsl",
979
        [VIRTUALIZATION_PROOT]           = "proot",
980
        [VIRTUALIZATION_POUCH]           = "pouch",
981
        [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
982
};
983

984
DEFINE_STRING_TABLE_LOOKUP(virtualization, Virtualization);
1,942✔
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