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

systemd / systemd / 14895667988

07 May 2025 08:57PM UTC coverage: 72.225% (-0.007%) from 72.232%
14895667988

push

github

yuwata
network: log_link_message_debug_errno() automatically append %m if necessary

Follow-up for d28746ef5.
Fixes CID#1609753.

0 of 1 new or added line in 1 file covered. (0.0%)

20297 existing lines in 338 files now uncovered.

297407 of 411780 relevant lines covered (72.22%)

695716.85 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 "extract-word.h"
17
#include "fd-util.h"
18
#include "fileio.h"
19
#include "log.h"
20
#include "macro.h"
21
#include "namespace-util.h"
22
#include "parse-util.h"
23
#include "process-util.h"
24
#include "stat-util.h"
25
#include "string-table.h"
26
#include "string-util.h"
27
#include "virt.h"
28

29
enum {
30
      SMBIOS_VM_BIT_SET,
31
      SMBIOS_VM_BIT_UNSET,
32
      SMBIOS_VM_BIT_UNKNOWN,
33
};
34

35
static Virtualization detect_vm_cpuid(void) {
475✔
36

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

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

62
        uint32_t eax, ebx, ecx, edx;
475✔
63
        bool hypervisor;
475✔
64

65
        /* http://lwn.net/Articles/301888/ */
66

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

71
        hypervisor = ecx & 0x80000000U;
475✔
72

73
        if (hypervisor) {
475✔
74
                union {
475✔
75
                        uint32_t sig32[3];
76
                        char text[13];
77
                } sig = {};
475✔
78

79
                /* There is a hypervisor, see what it is */
80
                __cpuid(0x40000000U, eax, ebx, ecx, edx);
475✔
81

82
                sig.sig32[0] = ebx;
475✔
83
                sig.sig32[1] = ecx;
475✔
84
                sig.sig32[2] = edx;
475✔
85

86
                log_debug("Virtualization found, CPUID=%s", sig.text);
475✔
87

88
                FOREACH_ELEMENT(vm, vm_table)
966✔
89
                        if (memcmp_nn(sig.text, sizeof(sig.text),
491✔
90
                                      vm->sig, sizeof(vm->sig)) == 0)
966✔
91
                                return vm->id;
475✔
92

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

99
        return VIRTUALIZATION_NONE;
100
}
101

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

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

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

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

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

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

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

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

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

201
        STRV_FOREACH(vendor, dmi_vendors) {
966✔
202
                _cleanup_free_ char *s = NULL;
962✔
203

204
                r = read_one_line_file(*vendor, &s);
962✔
205
                if (r < 0) {
962✔
206
                        if (r == -ENOENT)
×
UNCOV
207
                                continue;
×
208

209
                        return r;
210
                }
211

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

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

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

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

259
static Virtualization detect_vm_dmi(void) {
475✔
260
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64)
261

262
        int r;
475✔
263
        r = detect_vm_dmi_vendor();
475✔
264

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

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

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

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

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

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

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

345
        for (const char *i = domcap;;) {
×
UNCOV
346
                _cleanup_free_ char *cap = NULL;
×
347

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

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

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

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

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

UNCOV
384
        log_debug("Virtualization %s found in /sys/hypervisor/type", hvtype);
×
385

UNCOV
386
        if (streq(hvtype, "xen"))
×
387
                return VIRTUALIZATION_XEN;
388
        else
UNCOV
389
                return VIRTUALIZATION_VM_OTHER;
×
390
}
391

392
static Virtualization detect_vm_uml(void) {
475✔
393
        _cleanup_fclose_ FILE *f = NULL;
475✔
394
        int r;
475✔
395

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

406
        for (;;) {
1,425✔
407
                _cleanup_free_ char *line = NULL;
475✔
408
                const char *t;
950✔
409

410
                r = read_line(f, LONG_LINE_MAX, &line);
950✔
411
                if (r < 0)
950✔
412
                        return r;
413
                if (r == 0)
950✔
414
                        break;
415

416
                t = startswith(line, "vendor_id\t: ");
950✔
417
                if (t) {
950✔
418
                        if (startswith(t, "User Mode Linux")) {
475✔
419
                                log_debug("UML virtualization found in /proc/cpuinfo");
×
UNCOV
420
                                return VIRTUALIZATION_UML;
×
421
                        }
422

423
                        break;
424
                }
425
        }
426

427
        log_debug("UML virtualization not found in /proc/cpuinfo.");
475✔
428
        return VIRTUALIZATION_NONE;
429
}
430

431
static Virtualization detect_vm_zvm(void) {
4✔
432

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

437
        r = get_proc_field("/proc/sysinfo", "VM00 Control Program", &t);
438
        if (IN_SET(r, -ENOENT, -ENODATA))
439
                return VIRTUALIZATION_NONE;
440
        if (r < 0)
441
                return r;
442

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

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

461
        if (cached_found >= 0)
1,255✔
462
                return cached_found;
463

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

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

487
        /* Detect UML */
488
        v = detect_vm_uml();
475✔
489
        if (v < 0)
475✔
490
                return v;
491
        if (v != VIRTUALIZATION_NONE)
475✔
UNCOV
492
                goto finish;
×
493

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

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

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

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

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

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

555
        v = detect_vm_zvm();
4✔
556
        if (v < 0)
4✔
557
                return v;
558

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

570
        cached_found = v;
475✔
571
        log_debug("Found VM virtualization %s", virtualization_to_string(v));
475✔
572
        return v;
573
}
574

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

587
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
3,781✔
588

589
static int running_in_pidns(void) {
4,695✔
590
        int r;
4,695✔
591

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

596
        return !r;
4,683✔
597
}
598

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

612
        FOREACH_ELEMENT(file, container_file_table) {
14,085✔
613
                if (access(file->file_path, F_OK) >= 0)
9,390✔
UNCOV
614
                        return file->id;
×
615

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

622
        return VIRTUALIZATION_NONE;
623
}
624

625
Virtualization detect_container(void) {
204,088✔
626
        static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
204,088✔
627
        _cleanup_free_ char *m = NULL, *o = NULL, *p = NULL;
204,088✔
628
        const char *e = NULL;
204,088✔
629
        Virtualization v;
204,088✔
630
        int r;
204,088✔
631

632
        if (cached_found >= 0)
204,088✔
633
                return cached_found;
634

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

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

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

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

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

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

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

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

UNCOV
709
                goto translate_name;
×
710
        }
711

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

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

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

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

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

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

767
finish:
3,781✔
768
        log_debug("Found container virtualization %s.", virtualization_to_string(v));
8,476✔
769
        cached_found = v;
8,476✔
770
        return v;
8,476✔
771
}
772

773
Virtualization detect_virtualization(void) {
1,568✔
774
        int v;
1,568✔
775

776
        v = detect_container();
1,568✔
777
        if (v != VIRTUALIZATION_NONE)
1,568✔
778
                return v;
779

780
        return detect_vm();
1,157✔
781
}
782

783
int running_in_userns(void) {
79✔
784
        int r;
79✔
785

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

790
        return !r;
79✔
791
}
792

793
int running_in_chroot(void) {
13,556✔
794
        int r;
13,556✔
795

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

800
        r = getenv_bool("SYSTEMD_IN_CHROOT");
13,556✔
801
        if (r >= 0)
13,556✔
802
                return r > 0;
4✔
803
        if (r != -ENXIO)
13,552✔
UNCOV
804
                log_debug_errno(r, "Failed to parse $SYSTEMD_IN_CHROOT, ignoring: %m");
×
805

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

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

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

823
        return r == 0;
13,435✔
824
}
825

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

938
        return false;
939
}
940
#endif
941

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

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

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

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