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

systemd / systemd / 14872145375

06 May 2025 09:07PM UTC coverage: 72.232% (+0.02%) from 72.214%
14872145375

push

github

DaanDeMeyer
string-table: annotate _to_string and _from_string with _const_ and _pure_, respectively

Follow-up for c94f6ab1b

297286 of 411572 relevant lines covered (72.23%)

695615.99 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 "parse-util.h"
22
#include "process-util.h"
23
#include "stat-util.h"
24
#include "string-table.h"
25
#include "string-util.h"
26
#include "virt.h"
27

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

34
static Virtualization detect_vm_cpuid(void) {
475✔
35

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

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

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

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

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

70
        hypervisor = ecx & 0x80000000U;
475✔
71

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

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

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

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

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

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

98
        return VIRTUALIZATION_NONE;
99
}
100

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

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

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

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

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

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

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

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

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

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

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

208
                        return r;
209
                }
210

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

422
                        break;
423
                }
424
        }
425

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

430
static Virtualization detect_vm_zvm(void) {
4✔
431

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

586
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
3,786✔
587

588
static int running_in_pidns(void) {
4,698✔
589
        int r;
4,698✔
590

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

595
        return !r;
4,686✔
596
}
597

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

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

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

621
        return VIRTUALIZATION_NONE;
622
}
623

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

631
        if (cached_found >= 0)
204,067✔
632
                return cached_found;
633

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

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

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

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

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

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

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

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

708
                goto translate_name;
×
709
        }
710

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

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

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

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

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

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

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

772
Virtualization detect_virtualization(void) {
1,569✔
773
        int v;
1,569✔
774

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

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

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

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

789
        return !r;
79✔
790
}
791

792
int running_in_chroot(void) {
13,533✔
793
        int r;
13,533✔
794

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

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

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

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

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

822
        return r == 0;
13,412✔
823
}
824

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

937
        return false;
938
}
939
#endif
940

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

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

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

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