VirtualBox

Ticket #17961: vmdetect.c

File vmdetect.c, 1.7 KB (added by georgschoelly_joe, 4 years ago)

demo sample source code

Line 
1/*
2 * Linux test app for https://www.virtualbox.org/ticket/17961
3 *
4 * gcc vmdetect.c -std=gnu11 -masm=intel -o vmdetect
5 *
6 */
7
8#define _POSIX_C_SOURCE 200809L
9
10#include <signal.h>
11#include <stdio.h>
12
13#if __x86_64__
14#define ENABLE_TF() asm( \
15 "pushf;" \
16 "or WORD ptr[rsp], 0x100;" \
17 "popf;" \
18 );
19
20#define DISABLE_TF() asm( \
21 "pushf;" \
22 "and WORD ptr[rsp], 0xFFEF;" \
23 "popf;" \
24 );
25#else
26#define ENABLE_TF() asm( \
27 "pushf;" \
28 "or WORD ptr[esp], 0x100;" \
29 "popf;" \
30 );
31
32#define DISABLE_TF() asm( \
33 "pushf;" \
34 "and WORD ptr[esp], 0xFFEF;" \
35 "popf;" \
36 );
37#endif
38
39static int codepoint = -1;
40
41static void handler(int signo, siginfo_t *info, void *context) {
42 // store codepoint of first exception
43 if (codepoint < 0) {
44 codepoint = *(unsigned char*)info->si_addr;
45 }
46}
47
48
49struct sigaction handler_act = {
50 .sa_sigaction = &handler,
51 .sa_flags = SA_SIGINFO,
52};
53
54void cpuid_test()
55{
56 ENABLE_TF();
57
58 asm(
59 "cpuid;"
60 "nop;" // normal TF
61 "int 3;" // in VM
62 : /* no output */
63 : /* no input */
64 : "eax", "ebx", "ecx", "edx" /* clobber list */
65 );
66
67 DISABLE_TF();
68}
69
70int main(int argc, char *argv[]) {
71 if (sigaction(SIGTRAP, &handler_act, NULL) < 0) {
72 printf("Error installing signal handler");
73 return 1;
74 }
75
76 cpuid_test();
77
78 printf("Found opcode 0x%02hhX\n", codepoint);
79 if (codepoint == 0x90) {
80 printf("Trapped on nop, we are running on a real machine\n");
81 } else if (codepoint == 0xCC) {
82 printf("Trapped on int3, we are running in a VM\n");
83 } else {
84 printf("Unexpected trap location.\n");
85 }
86
87 return 0;
88}
89

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy