1 // Copyright 2017 syzkaller project authors. All rights reserved.
2 // Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
3
4 // This file is shared between executor and csource package.
5
6 // Implementation of syz_kvm_setup_cpu pseudo-syscall.
7
8 struct kvm_text {
9 uintptr_t typ;
10 const void* text;
11 uintptr_t size;
12 };
13
14 struct kvm_opt {
15 uint64 typ;
16 uint64 val;
17 };
18
19 // syz_kvm_setup_cpu(fd fd_kvmvm, cpufd fd_kvmcpu, usermem vma[24], text ptr[in, array[kvm_text, 1]], ntext len[text], flags flags[kvm_setup_flags], opts ptr[in, array[kvm_setup_opt, 0:2]], nopt len[opts])
syz_kvm_setup_cpu(uintptr_t a0,uintptr_t a1,uintptr_t a2,uintptr_t a3,uintptr_t a4,uintptr_t a5,uintptr_t a6,uintptr_t a7)20 static uintptr_t syz_kvm_setup_cpu(uintptr_t a0, uintptr_t a1, uintptr_t a2, uintptr_t a3, uintptr_t a4, uintptr_t a5, uintptr_t a6, uintptr_t a7)
21 {
22 const int vmfd = a0;
23 const int cpufd = a1;
24 char* const host_mem = (char*)a2;
25 const struct kvm_text* const text_array_ptr = (struct kvm_text*)a3;
26 const uintptr_t text_count = a4;
27 const uintptr_t flags = a5;
28 const struct kvm_opt* const opt_array_ptr = (struct kvm_opt*)a6;
29 uintptr_t opt_count = a7;
30
31 (void)flags;
32 (void)opt_count;
33
34 const uintptr_t page_size = 4 << 10;
35 const uintptr_t guest_mem = 0;
36 const uintptr_t guest_mem_size = 24 * page_size;
37
38 (void)text_count; // fuzzer can spoof count and we need just 1 text, so ignore text_count
39 int text_type = 0;
40 const void* text = 0;
41 int text_size = 0;
42 NONFAILING(text_type = text_array_ptr[0].typ);
43 NONFAILING(text = text_array_ptr[0].text);
44 NONFAILING(text_size = text_array_ptr[0].size);
45 (void)text_type;
46 (void)opt_array_ptr;
47
48 uint32 features = 0;
49 if (opt_count > 1)
50 opt_count = 1;
51 uintptr_t i;
52 for (i = 0; i < opt_count; i++) {
53 uint64 typ = 0;
54 uint64 val = 0;
55 NONFAILING(typ = opt_array_ptr[i].typ);
56 NONFAILING(val = opt_array_ptr[i].val);
57 switch (typ) {
58 case 1:
59 features = val;
60 break;
61 }
62 }
63
64 for (i = 0; i < guest_mem_size / page_size; i++) {
65 struct kvm_userspace_memory_region memreg;
66 memreg.slot = i;
67 memreg.flags = 0; // can be KVM_MEM_LOG_DIRTY_PAGES | KVM_MEM_READONLY
68 memreg.guest_phys_addr = guest_mem + i * page_size;
69 memreg.memory_size = page_size;
70 memreg.userspace_addr = (uintptr_t)host_mem + i * page_size;
71 ioctl(vmfd, KVM_SET_USER_MEMORY_REGION, &memreg);
72 }
73
74 struct kvm_vcpu_init init;
75 ioctl(cpufd, KVM_ARM_PREFERRED_TARGET, &init);
76 init.features[0] = features;
77 ioctl(cpufd, KVM_ARM_VCPU_INIT, &init);
78
79 if (text_size > 1000)
80 text_size = 1000;
81 NONFAILING(memcpy(host_mem, text, text_size));
82
83 return 0;
84 }
85