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

systemd / systemd / 16979578868

14 Aug 2025 05:18PM UTC coverage: 72.036% (-0.2%) from 72.212%
16979578868

push

github

bluca
mkosi: install util-linux-script on F44

Once F41 is EOL we can just move this to the main list and
stop doing this dance every 6 months

301650 of 418750 relevant lines covered (72.04%)

661496.21 hits per line

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

63.43
/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 <stdlib.h>
7
#include <threads.h>
8
#include <unistd.h>
9

10
#include "alloc-util.h"
11
#include "dirent-util.h"
12
#include "env-util.h"
13
#include "extract-word.h"
14
#include "fd-util.h"
15
#include "fileio.h"
16
#include "log.h"
17
#include "namespace-util.h"
18
#include "parse-util.h"
19
#include "pidref.h"
20
#include "process-util.h"
21
#include "string-table.h"
22
#include "string-util.h"
23
#include "strv.h"
24
#include "virt.h"
25

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

32
static Virtualization detect_vm_cpuid(void) {
573✔
33

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

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

59
        uint32_t eax, ebx, ecx, edx;
573✔
60
        bool hypervisor;
573✔
61

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

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

68
        hypervisor = ecx & 0x80000000U;
573✔
69

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

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

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

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

85
                FOREACH_ELEMENT(vm, vm_table)
1,162✔
86
                        if (memcmp_nn(sig.text, sizeof(sig.text),
589✔
87
                                      vm->sig, sizeof(vm->sig)) == 0)
1,162✔
88
                                return vm->id;
573✔
89

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

96
        return VIRTUALIZATION_NONE;
97
}
98

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

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

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

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

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

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

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

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

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

198
        STRV_FOREACH(vendor, dmi_vendors) {
1,162✔
199
                _cleanup_free_ char *s = NULL;
1,158✔
200

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

206
                        return r;
207
                }
208

209
                FOREACH_ELEMENT(dmi_vendor, dmi_vendor_table)
13,447✔
210
                        if (startswith(s, dmi_vendor->vendor)) {
12,858✔
211
                                log_debug("Virtualization %s found in DMI (%s)", s, *vendor);
569✔
212
                                return dmi_vendor->id;
569✔
213
                        }
214
        }
215
        log_debug("No virtualization found in DMI vendor table.");
4✔
216
        return VIRTUALIZATION_NONE;
217
}
218

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

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

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

256
static Virtualization detect_vm_dmi(void) {
573✔
257
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__) || defined(__loongarch_lp64) || defined(__riscv)
258

259
        int r;
573✔
260
        r = detect_vm_dmi_vendor();
573✔
261

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

403
        for (;;) {
1,719✔
404
                _cleanup_free_ char *line = NULL;
573✔
405
                const char *t;
1,146✔
406

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

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

420
                        break;
421
                }
422
        }
423

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

428
static Virtualization detect_vm_zvm(void) {
4✔
429

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

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

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

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

458
        if (cached_found >= 0)
1,439✔
459
                return cached_found;
460

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

473
        dmi = detect_vm_dmi();
573✔
474
        if (IN_SET(dmi,
573✔
475
                   VIRTUALIZATION_ORACLE,
476
                   VIRTUALIZATION_XEN,
477
                   VIRTUALIZATION_AMAZON,
478
                   /* Unable to distinguish a GCE machine from a VM to bare-metal
479
                    * for non-x86 architectures due to its necessity for cpuid
480
                    * detection, which functions solely on x86 platforms. Report
481
                    * as a VM for other architectures. */
482
#if !defined(__i386__) && !defined(__x86_64__)
483
                   VIRTUALIZATION_GOOGLE,
484
#endif
485
                   VIRTUALIZATION_PARALLELS)) {
486
                v = dmi;
×
487
                goto finish;
×
488
        }
489

490
        /* Detect UML */
491
        v = detect_vm_uml();
573✔
492
        if (v < 0)
573✔
493
                return v;
494
        if (v != VIRTUALIZATION_NONE)
573✔
495
                goto finish;
×
496

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

513
        /* Detect from CPUID */
514
        v = detect_vm_cpuid();
573✔
515
        if (v < 0)
573✔
516
                return v;
517
        if (v == VIRTUALIZATION_MICROSOFT)
573✔
518
                /* QEMU sets the CPUID string to hyperv's, in case it provides hyperv enlightenments. Let's
519
                 * hence not return Microsoft here but just use the other mechanisms first to make a better
520
                 * decision. */
521
                hyperv = true;
522
        else if (v == VIRTUALIZATION_VM_OTHER)
569✔
523
                other = true;
524
        else if (v == VIRTUALIZATION_KVM && dmi == VIRTUALIZATION_GOOGLE)
569✔
525
                /* The DMI vendor tables in /sys/class/dmi/id don't help us distinguish between GCE
526
                 * virtual machines and bare-metal instances, so we need to look at hypervisor. */
527
                return VIRTUALIZATION_GOOGLE;
528
        else if (v != VIRTUALIZATION_NONE)
569✔
529
                goto finish;
569✔
530

531
        /* If we are in Dom0 and have not yet finished, finish with the result of detect_vm_cpuid */
532
        if (xen_dom0 > 0)
4✔
533
                goto finish;
×
534

535
        /* Now, let's get back to DMI */
536
        if (dmi < 0)
4✔
537
                return dmi;
538
        if (dmi == VIRTUALIZATION_VM_OTHER)
4✔
539
                other = true;
540
        else if (!IN_SET(dmi, VIRTUALIZATION_NONE, VIRTUALIZATION_GOOGLE)) {
4✔
541
                /* At this point if GCE has been detected in dmi, do not report as a VM. It should
542
                 * be a bare-metal machine */
543
                v = dmi;
×
544
                goto finish;
×
545
        }
546

547
        /* Check high-level hypervisor sysfs file */
548
        v = detect_vm_hypervisor();
4✔
549
        if (v < 0)
4✔
550
                return v;
551
        if (v == VIRTUALIZATION_VM_OTHER)
4✔
552
                other = true;
553
        else if (v != VIRTUALIZATION_NONE)
4✔
554
                goto finish;
×
555

556
        v = detect_vm_device_tree();
4✔
557
        if (v < 0)
4✔
558
                return v;
559
        if (v == VIRTUALIZATION_VM_OTHER)
4✔
560
                other = true;
561
        else if (v != VIRTUALIZATION_NONE)
4✔
562
                goto finish;
×
563

564
        v = detect_vm_zvm();
4✔
565
        if (v < 0)
4✔
566
                return v;
567

568
finish:
4✔
569
        /* None of the checks above gave us a clear answer, hence let's now use fallback logic: if hyperv
570
         * enlightenments are available but the VMM wasn't recognized as anything yet, it's probably
571
         * Microsoft. */
572
        if (v == VIRTUALIZATION_NONE) {
573✔
573
                if (hyperv)
4✔
574
                        v = VIRTUALIZATION_MICROSOFT;
575
                else if (other)
×
576
                        v = VIRTUALIZATION_VM_OTHER;
×
577
        }
578

579
        cached_found = v;
573✔
580
        log_debug("Found VM virtualization %s", virtualization_to_string(v));
573✔
581
        return v;
582
}
583

584
static const char *const container_table[_VIRTUALIZATION_MAX] = {
585
        [VIRTUALIZATION_LXC]            = "lxc",
586
        [VIRTUALIZATION_LXC_LIBVIRT]    = "lxc-libvirt",
587
        [VIRTUALIZATION_SYSTEMD_NSPAWN] = "systemd-nspawn",
588
        [VIRTUALIZATION_DOCKER]         = "docker",
589
        [VIRTUALIZATION_PODMAN]         = "podman",
590
        [VIRTUALIZATION_RKT]            = "rkt",
591
        [VIRTUALIZATION_WSL]            = "wsl",
592
        [VIRTUALIZATION_PROOT]          = "proot",
593
        [VIRTUALIZATION_POUCH]          = "pouch",
594
};
595

596
DEFINE_PRIVATE_STRING_TABLE_LOOKUP_FROM_STRING(container, int);
3,817✔
597

598
static int running_in_pidns(void) {
4,801✔
599
        int r;
4,801✔
600

601
        r = namespace_is_init(NAMESPACE_PID);
4,801✔
602
        if (r < 0)
4,801✔
603
                return log_debug_errno(r, "Failed to test if in root PID namespace, ignoring: %m");
17✔
604

605
        return !r;
4,784✔
606
}
607

608
static Virtualization detect_container_files(void) {
4,801✔
609
        static const struct {
4,801✔
610
                const char *file_path;
611
                Virtualization id;
612
        } container_file_table[] = {
613
                /* https://github.com/containers/podman/issues/6192 */
614
                /* https://github.com/containers/podman/issues/3586#issuecomment-661918679 */
615
                { "/run/.containerenv", VIRTUALIZATION_PODMAN },
616
                /* https://github.com/moby/moby/issues/18355 */
617
                /* Docker must be the last in this table, see below. */
618
                { "/.dockerenv",        VIRTUALIZATION_DOCKER },
619
        };
620

621
        FOREACH_ELEMENT(file, container_file_table) {
14,403✔
622
                if (access(file->file_path, F_OK) >= 0)
9,602✔
623
                        return file->id;
×
624

625
                if (errno != ENOENT)
9,602✔
626
                        log_debug_errno(errno,
9,602✔
627
                                        "Checking if %s exists failed, ignoring: %m",
628
                                        file->file_path);
629
        }
630

631
        return VIRTUALIZATION_NONE;
632
}
633

634
Virtualization detect_container(void) {
193,904✔
635
        static thread_local Virtualization cached_found = _VIRTUALIZATION_INVALID;
193,904✔
636
        _cleanup_free_ char *m = NULL, *o = NULL, *p = NULL;
193,904✔
637
        const char *e = NULL;
193,904✔
638
        Virtualization v;
193,904✔
639
        int r;
193,904✔
640

641
        if (cached_found >= 0)
193,904✔
642
                return cached_found;
643

644
        /* /proc/vz exists in container and outside of the container, /proc/bc only outside of the container. */
645
        if (access("/proc/vz", F_OK) < 0) {
8,618✔
646
                if (errno != ENOENT)
8,618✔
647
                        log_debug_errno(errno, "Failed to check if /proc/vz exists, ignoring: %m");
×
648
        } else if (access("/proc/bc", F_OK) < 0) {
×
649
                if (errno == ENOENT) {
×
650
                        v = VIRTUALIZATION_OPENVZ;
×
651
                        goto finish;
×
652
                }
653

654
                log_debug_errno(errno, "Failed to check if /proc/bc exists, ignoring: %m");
×
655
        }
656

657
        /* "Official" way of detecting WSL https://github.com/Microsoft/WSL/issues/423#issuecomment-221627364 */
658
        r = read_one_line_file("/proc/sys/kernel/osrelease", &o);
8,618✔
659
        if (r < 0)
8,618✔
660
                log_debug_errno(r, "Failed to read /proc/sys/kernel/osrelease, ignoring: %m");
17✔
661
        else if (strstr(o, "Microsoft") || strstr(o, "WSL")) {
8,601✔
662
                v = VIRTUALIZATION_WSL;
×
663
                goto finish;
×
664
        }
665

666
        /* proot doesn't use PID namespacing, so we can just check if we have a matching tracer for this
667
         * invocation without worrying about it being elsewhere.
668
         */
669
        r = get_proc_field("/proc/self/status", "TracerPid", &p);
8,618✔
670
        if (r < 0)
8,618✔
671
                log_debug_errno(r, "Failed to read our own trace PID, ignoring: %m");
17✔
672
        else if (!streq(p, "0")) {
8,601✔
673
                pid_t ptrace_pid;
×
674

675
                r = parse_pid(p, &ptrace_pid);
×
676
                if (r < 0)
×
677
                        log_debug_errno(r, "Failed to parse our own tracer PID, ignoring: %m");
×
678
                else {
679
                        _cleanup_free_ char *ptrace_comm = NULL;
×
680
                        const char *pf;
×
681

682
                        pf = procfs_file_alloca(ptrace_pid, "comm");
×
683
                        r = read_one_line_file(pf, &ptrace_comm);
×
684
                        if (r < 0)
×
685
                                log_debug_errno(r, "Failed to read %s, ignoring: %m", pf);
×
686
                        else if (startswith(ptrace_comm, "proot")) {
×
687
                                v = VIRTUALIZATION_PROOT;
×
688
                                goto finish;
×
689
                        }
690
                }
691
        }
692

693
        /* The container manager might have placed this in the /run/host/ hierarchy for us, which is best
694
         * because we can be consumed just like that, without special privileges. */
695
        r = read_one_line_file("/run/host/container-manager", &m);
8,618✔
696
        if (r > 0) {
8,618✔
697
                e = m;
3,817✔
698
                goto translate_name;
3,817✔
699
        }
700
        if (!IN_SET(r, -ENOENT, 0))
4,801✔
701
                return log_debug_errno(r, "Failed to read /run/host/container-manager: %m");
×
702

703
        if (getpid_cached() == 1) {
4,801✔
704
                /* If we are PID 1 we can just check our own environment variable, and that's authoritative.
705
                 * We distinguish three cases:
706
                 * - the variable is not defined → we jump to other checks
707
                 * - the variable is defined to an empty value → we are not in a container
708
                 * - anything else → some container, either one of the known ones or "container-other"
709
                 */
710
                e = getenv("container");
26✔
711
                if (!e)
26✔
712
                        goto check_files;
26✔
713
                if (isempty(e)) {
×
714
                        v = VIRTUALIZATION_NONE;
×
715
                        goto finish;
×
716
                }
717

718
                goto translate_name;
×
719
        }
720

721
        /* Otherwise, PID 1 might have dropped this information into a file in /run. This is better than accessing
722
         * /proc/1/environ, since we don't need CAP_SYS_PTRACE for that. */
723
        r = read_one_line_file("/run/systemd/container", &m);
4,775✔
724
        if (r > 0) {
4,775✔
725
                e = m;
×
726
                goto translate_name;
×
727
        }
728
        if (!IN_SET(r, -ENOENT, 0))
4,775✔
729
                return log_debug_errno(r, "Failed to read /run/systemd/container: %m");
×
730

731
        /* Fallback for cases where PID 1 was not systemd (for example, cases where init=/bin/sh is used. */
732
        r = getenv_for_pid(1, "container", &m);
4,775✔
733
        if (r > 0) {
4,775✔
734
                e = m;
×
735
                goto translate_name;
×
736
        }
737
        if (r < 0) /* This only works if we have CAP_SYS_PTRACE, hence let's better ignore failures here */
4,775✔
738
                log_debug_errno(r, "Failed to read $container of PID 1, ignoring: %m");
1,627✔
739

740
check_files:
3,148✔
741
        /* Check for existence of some well-known files. We only do this after checking
742
         * for other specific container managers, otherwise we risk mistaking another
743
         * container manager for Docker: the /.dockerenv file could inadvertently end up
744
         * in a file system image. */
745
        v = detect_container_files();
4,801✔
746
        if (v < 0)
4,801✔
747
                return v;
748
        if (v != VIRTUALIZATION_NONE)
4,801✔
749
                goto finish;
×
750

751
        /* Finally, the root pid namespace has an hardcoded inode number of 0xEFFFFFFC since kernel 3.8, so
752
         * if all else fails we can check the inode number of our pid namespace and compare it. */
753
        if (running_in_pidns() > 0) {
4,801✔
754
                log_debug("Running in a pid namespace, assuming unknown container manager.");
1✔
755
                v = VIRTUALIZATION_CONTAINER_OTHER;
1✔
756
                goto finish;
1✔
757
        }
758

759
        /* If none of that worked, give up, assume no container manager. */
760
        v = VIRTUALIZATION_NONE;
4,800✔
761
        goto finish;
4,800✔
762

763
translate_name:
3,817✔
764
        if (streq(e, "oci")) {
3,817✔
765
                /* Some images hardcode container=oci, but OCI is not a specific container manager.
766
                 * Try to detect one based on well-known files. */
767
                v = detect_container_files();
×
768
                if (v == VIRTUALIZATION_NONE)
×
769
                        v = VIRTUALIZATION_CONTAINER_OTHER;
×
770
                goto finish;
×
771
        }
772
        v = container_from_string(e);
3,817✔
773
        if (v < 0)
3,817✔
774
                v = VIRTUALIZATION_CONTAINER_OTHER;
×
775

776
finish:
3,817✔
777
        log_debug("Found container virtualization %s.", virtualization_to_string(v));
8,618✔
778
        cached_found = v;
8,618✔
779
        return v;
8,618✔
780
}
781

782
Virtualization detect_virtualization(void) {
1,706✔
783
        int v;
1,706✔
784

785
        v = detect_container();
1,706✔
786
        if (v != VIRTUALIZATION_NONE)
1,706✔
787
                return v;
788

789
        return detect_vm();
1,311✔
790
}
791

792
int running_in_userns(void) {
89✔
793
        int r;
89✔
794

795
        r = namespace_is_init(NAMESPACE_USER);
89✔
796
        if (r < 0)
89✔
797
                return log_debug_errno(r, "Failed to test if in root user namespace, ignoring: %m");
×
798

799
        return !r;
89✔
800
}
801

802
int running_in_chroot(void) {
11,058✔
803
        int r;
11,058✔
804

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

809
        r = getenv_bool("SYSTEMD_IN_CHROOT");
11,058✔
810
        if (r >= 0)
11,058✔
811
                return r > 0;
4✔
812
        if (r != -ENXIO)
11,054✔
813
                log_debug_errno(r, "Failed to parse $SYSTEMD_IN_CHROOT, ignoring: %m");
×
814

815
        /* Deprecated but kept for backwards compatibility. */
816
        if (getenv_bool("SYSTEMD_IGNORE_CHROOT") > 0)
11,054✔
817
                return 0;
818

819
        r = pidref_from_same_root_fs(&PIDREF_MAKE_FROM_PID(1), NULL);
11,054✔
820
        if (r == -ENOSYS) {
11,054✔
821
                if (getpid_cached() == 1)
×
822
                        return false; /* We will mount /proc, assuming we're not in a chroot. */
823

824
                log_debug("/proc/ is not mounted, assuming we're in a chroot.");
×
825
                return true;
×
826
        }
827
        if (r == -ESRCH) /* We must have a fake /proc/, we can't do the check properly. */
11,054✔
828
                return -ENOSYS;
829
        if (r < 0)
11,054✔
830
                return r;
831

832
        return r == 0;
10,923✔
833
}
834

835
#if defined(__i386__) || defined(__x86_64__)
836
struct cpuid_table_entry {
837
        uint32_t flag_bit;
838
        const char *name;
839
};
840

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

867
static const struct cpuid_table_entry leaf1_ecx[] = {
868
        {  0, "pni"     },
869
        {  1, "pclmul"  },
870
        {  3, "monitor" },
871
        {  9, "ssse3"   },
872
        { 12, "fma3"    },
873
        { 13, "cx16"    },
874
        { 19, "sse4_1"  },
875
        { 20, "sse4_2"  },
876
        { 22, "movbe"   },
877
        { 23, "popcnt"  },
878
        { 25, "aes"     },
879
        { 26, "xsave"   },
880
        { 27, "osxsave" },
881
        { 28, "avx"     },
882
        { 29, "f16c"    },
883
        { 30, "rdrand"  },
884
};
885

886
static const struct cpuid_table_entry leaf7_ebx[] = {
887
        {  3, "bmi1"   },
888
        {  5, "avx2"   },
889
        {  8, "bmi2"   },
890
        { 18, "rdseed" },
891
        { 19, "adx"    },
892
        { 29, "sha_ni" },
893
};
894

895
static const struct cpuid_table_entry leaf81_edx[] = {
896
        { 11, "syscall" },
897
        { 27, "rdtscp"  },
898
        { 29, "lm"      },
899
};
900

901
static const struct cpuid_table_entry leaf81_ecx[] = {
902
        {  0, "lahf_lm" },
903
        {  5, "abm"     },
904
};
905

906
static const struct cpuid_table_entry leaf87_edx[] = {
907
        {  8, "constant_tsc" },
908
};
909

910
static bool given_flag_in_set(const char *flag, const struct cpuid_table_entry *set, size_t set_size, uint32_t val) {
14✔
911
        for (size_t i = 0; i < set_size; i++) {
132✔
912
                if ((UINT32_C(1) << set[i].flag_bit) & val &&
119✔
913
                                streq(flag, set[i].name))
116✔
914
                        return true;
915
        }
916
        return false;
917
}
918

919
static bool real_has_cpu_with_flag(const char *flag) {
3✔
920
        uint32_t eax, ebx, ecx, edx;
3✔
921

922
        if (__get_cpuid(1, &eax, &ebx, &ecx, &edx)) {
3✔
923
                if (given_flag_in_set(flag, leaf1_ecx, ELEMENTSOF(leaf1_ecx), ecx))
3✔
924
                        return true;
3✔
925

926
                if (given_flag_in_set(flag, leaf1_edx, ELEMENTSOF(leaf1_edx), edx))
3✔
927
                        return true;
928
        }
929

930
        if (__get_cpuid_count(7, 0, &eax, &ebx, &ecx, &edx)) {
2✔
931
                if (given_flag_in_set(flag, leaf7_ebx, ELEMENTSOF(leaf7_ebx), ebx))
2✔
932
                        return true;
933
        }
934

935
        if (__get_cpuid(0x80000001U, &eax, &ebx, &ecx, &edx)) {
2✔
936
                if (given_flag_in_set(flag, leaf81_ecx, ELEMENTSOF(leaf81_ecx), ecx))
2✔
937
                        return true;
938

939
                if (given_flag_in_set(flag, leaf81_edx, ELEMENTSOF(leaf81_edx), edx))
2✔
940
                        return true;
941
        }
942

943
        if (__get_cpuid(0x80000007U, &eax, &ebx, &ecx, &edx))
2✔
944
                if (given_flag_in_set(flag, leaf87_edx, ELEMENTSOF(leaf87_edx), edx))
2✔
945
                        return true;
×
946

947
        return false;
948
}
949
#endif
950

951
bool has_cpu_with_flag(const char *flag) {
3✔
952
        /* CPUID is an x86 specific interface. Assume on all others that no CPUs have those flags. */
953
#if defined(__i386__) || defined(__x86_64__)
954
        return real_has_cpu_with_flag(flag);
3✔
955
#else
956
        return false;
957
#endif
958
}
959

960
static const char *const virtualization_table[_VIRTUALIZATION_MAX] = {
961
        [VIRTUALIZATION_NONE]            = "none",
962
        [VIRTUALIZATION_KVM]             = "kvm",
963
        [VIRTUALIZATION_AMAZON]          = "amazon",
964
        [VIRTUALIZATION_QEMU]            = "qemu",
965
        [VIRTUALIZATION_BOCHS]           = "bochs",
966
        [VIRTUALIZATION_XEN]             = "xen",
967
        [VIRTUALIZATION_UML]             = "uml",
968
        [VIRTUALIZATION_VMWARE]          = "vmware",
969
        [VIRTUALIZATION_ORACLE]          = "oracle",
970
        [VIRTUALIZATION_MICROSOFT]       = "microsoft",
971
        [VIRTUALIZATION_ZVM]             = "zvm",
972
        [VIRTUALIZATION_PARALLELS]       = "parallels",
973
        [VIRTUALIZATION_BHYVE]           = "bhyve",
974
        [VIRTUALIZATION_QNX]             = "qnx",
975
        [VIRTUALIZATION_ACRN]            = "acrn",
976
        [VIRTUALIZATION_POWERVM]         = "powervm",
977
        [VIRTUALIZATION_APPLE]           = "apple",
978
        [VIRTUALIZATION_SRE]             = "sre",
979
        [VIRTUALIZATION_GOOGLE]          = "google",
980
        [VIRTUALIZATION_VM_OTHER]        = "vm-other",
981

982
        [VIRTUALIZATION_SYSTEMD_NSPAWN]  = "systemd-nspawn",
983
        [VIRTUALIZATION_LXC_LIBVIRT]     = "lxc-libvirt",
984
        [VIRTUALIZATION_LXC]             = "lxc",
985
        [VIRTUALIZATION_OPENVZ]          = "openvz",
986
        [VIRTUALIZATION_DOCKER]          = "docker",
987
        [VIRTUALIZATION_PODMAN]          = "podman",
988
        [VIRTUALIZATION_RKT]             = "rkt",
989
        [VIRTUALIZATION_WSL]             = "wsl",
990
        [VIRTUALIZATION_PROOT]           = "proot",
991
        [VIRTUALIZATION_POUCH]           = "pouch",
992
        [VIRTUALIZATION_CONTAINER_OTHER] = "container-other",
993
};
994

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