auto-apply clang-format

- including vl.c & kvm-all.c
This commit is contained in:
Sergej Schumilo 2022-10-16 23:34:23 +02:00
parent 976d8e8329
commit 8a88edc2a1
74 changed files with 9616 additions and 7849 deletions

View File

@ -48,15 +48,15 @@
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
#include "nyx/pt.h"
#include "nyx/hypercall/hypercall.h"
#include "nyx/synchronization.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/state/state.h"
#include "nyx/interface.h"
#include "nyx/fast_vm_reload_sync.h" #include "nyx/fast_vm_reload_sync.h"
#include "nyx/snapshot/memory/backend/nyx_dirty_ring.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "nyx/hypercall/hypercall.h"
#include "nyx/interface.h"
#include "nyx/pt.h"
#include "nyx/snapshot/memory/backend/nyx_dirty_ring.h"
#include "nyx/state/state.h"
#include "nyx/synchronization.h"
// clang-format off // clang-format off
#endif #endif
@ -93,7 +93,7 @@ struct KVMState
AccelState parent_obj; AccelState parent_obj;
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
bool nyx_no_pt_mode; bool nyx_no_pt_mode;
// clang-format off // clang-format off
#endif #endif
@ -387,11 +387,13 @@ static int kvm_get_vcpu(KVMState *s, unsigned long vcpu_id)
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
int kvm_get_vm_fd(KVMState *s){ int kvm_get_vm_fd(KVMState *s)
{
return s->vmfd; return s->vmfd;
} }
KVMMemoryListener* kvm_get_kml(int as_id){ KVMMemoryListener *kvm_get_kml(int as_id)
{
return kvm_state->as[as_id].ml; return kvm_state->as[as_id].ml;
} }
// clang-format off // clang-format off
@ -416,9 +418,9 @@ int kvm_init_vcpu(CPUState *cpu)
cpu->vcpu_dirty = true; cpu->vcpu_dirty = true;
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(s->nyx_no_pt_mode){ if (s->nyx_no_pt_mode) {
if(!getenv("NYX_DISABLE_DIRTY_RING")){ if (!getenv("NYX_DISABLE_DIRTY_RING")) {
nyx_dirty_ring_pre_init(cpu->kvm_fd, s->vmfd); nyx_dirty_ring_pre_init(cpu->kvm_fd, s->vmfd);
} }
} }
@ -450,7 +452,7 @@ int kvm_init_vcpu(CPUState *cpu)
ret = kvm_arch_init_vcpu(cpu); ret = kvm_arch_init_vcpu(cpu);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
unblock_signals(); unblock_signals();
// clang-format off // clang-format off
#endif #endif
@ -1928,28 +1930,34 @@ static int kvm_init(MachineState *ms)
goto err; goto err;
} }
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if (ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_PT) != 1 && ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_FDL) != 1) { if (ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_PT) != 1 &&
ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_FDL) != 1)
{
/* fallback -> use vanilla KVM module instead (no Intel-PT tracing or nested hypercalls at this point) */ /* fallback -> use vanilla KVM module instead (no Intel-PT tracing or nested hypercalls at this point) */
fprintf(stderr, "[QEMU-Nyx] Could not access KVM-PT kernel module!\n[QEMU-Nyx] Trying vanilla KVM...\n"); fprintf(stderr, "[QEMU-Nyx] Could not access KVM-PT kernel "
"module!\n[QEMU-Nyx] Trying vanilla KVM...\n");
if (s->fd == -1) { if (s->fd == -1) {
fprintf(stderr, "[QEMU-Nyx] Error: NYX fallback failed: Could not access vanilla KVM module!\n"); fprintf(stderr, "[QEMU-Nyx] Error: NYX fallback failed: Could not "
"access vanilla KVM module!\n");
ret = -errno; ret = -errno;
goto err; goto err;
} }
int ret_val = ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING); int ret_val = ioctl(s->fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING);
if(ret_val == -1 || ret_val == 0){ if (ret_val == -1 || ret_val == 0) {
fprintf(stderr, "[QEMU-Nyx] Error: NYX requires support for KVM_CAP_DIRTY_LOG_RING in fallback mode!\n"); fprintf(stderr, "[QEMU-Nyx] Error: NYX requires support for "
"KVM_CAP_DIRTY_LOG_RING in fallback mode!\n");
ret = -errno; ret = -errno;
goto err; goto err;
} }
/* check for vmware_backdoor support */ /* check for vmware_backdoor support */
int fd = open("/sys/module/kvm/parameters/enable_vmware_backdoor", O_RDONLY); int fd = open("/sys/module/kvm/parameters/enable_vmware_backdoor", O_RDONLY);
if(fd == -1){ if (fd == -1) {
fprintf(stderr, "ERROR: /sys/module/kvm/parameters/enable_vmware_backdoor file not found...\n"); fprintf(stderr,
"ERROR: /sys/module/kvm/parameters/enable_vmware_backdoor file "
"not found...\n");
ret = -errno; ret = -errno;
goto err; goto err;
} }
@ -1958,27 +1966,31 @@ static int kvm_init(MachineState *ms)
assert(read(fd, &vmware_backdoor_option, 1) == 1); assert(read(fd, &vmware_backdoor_option, 1) == 1);
close(fd); close(fd);
if(vmware_backdoor_option == 'N'){ if (vmware_backdoor_option == 'N') {
fprintf(stderr, "\n[QEMU-Nyx] ERROR: vmware backdoor is not enabled...\n"); fprintf(stderr,
"\n[QEMU-Nyx] ERROR: vmware backdoor is not enabled...\n");
fprintf(stderr, "\n\tRun the following commands to fix the issue:\n"); fprintf(stderr, "\n\tRun the following commands to fix the issue:\n");
fprintf(stderr, "\t-----------------------------------------\n"); fprintf(stderr, "\t-----------------------------------------\n");
fprintf(stderr, "\tsudo modprobe -r kvm-intel\n"); fprintf(stderr, "\tsudo modprobe -r kvm-intel\n");
fprintf(stderr, "\tsudo modprobe -r kvm\n"); fprintf(stderr, "\tsudo modprobe -r kvm\n");
fprintf(stderr, "\tsudo modprobe kvm enable_vmware_backdoor=y\n"); fprintf(stderr, "\tsudo modprobe kvm enable_vmware_backdoor=y\n");
fprintf(stderr, "\tsudo modprobe kvm-intel\n"); fprintf(stderr, "\tsudo modprobe kvm-intel\n");
fprintf(stderr, "\tcat /sys/module/kvm/parameters/enable_vmware_backdoor\n"); fprintf(stderr,
"\tcat /sys/module/kvm/parameters/enable_vmware_backdoor\n");
fprintf(stderr, "\t-----------------------------------------\n\n"); fprintf(stderr, "\t-----------------------------------------\n\n");
ret = -errno; ret = -errno;
goto err; goto err;
} }
fprintf(stderr, "[QEMU-Nyx] NYX runs in fallback mode (no Intel-PT tracing or nested hypercall support)!\n"); fprintf(stderr, "[QEMU-Nyx] NYX runs in fallback mode (no Intel-PT tracing "
"or nested hypercall support)!\n");
s->nyx_no_pt_mode = true; s->nyx_no_pt_mode = true;
GET_GLOBAL_STATE()->nyx_fdl = false; GET_GLOBAL_STATE()->nyx_fdl = false;
GET_GLOBAL_STATE()->pt_trace_mode = false; // Intel PT is not available in this mode GET_GLOBAL_STATE()->pt_trace_mode =
fast_reload_set_mode(get_fast_reload_snapshot(), RELOAD_MEMORY_MODE_DIRTY_RING); false; // Intel PT is not available in this mode
} fast_reload_set_mode(get_fast_reload_snapshot(),
else{ RELOAD_MEMORY_MODE_DIRTY_RING);
} else {
s->nyx_no_pt_mode = false; s->nyx_no_pt_mode = false;
GET_GLOBAL_STATE()->nyx_fdl = true; GET_GLOBAL_STATE()->nyx_fdl = true;
fast_reload_set_mode(get_fast_reload_snapshot(), RELOAD_MEMORY_MODE_FDL); fast_reload_set_mode(get_fast_reload_snapshot(), RELOAD_MEMORY_MODE_FDL);
@ -2050,13 +2062,16 @@ static int kvm_init(MachineState *ms)
s->vmfd = ret; s->vmfd = ret;
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(s->nyx_no_pt_mode){ if (s->nyx_no_pt_mode) {
if(getenv("NYX_DISABLE_DIRTY_RING")){ if (getenv("NYX_DISABLE_DIRTY_RING")) {
fprintf(stderr, "WARNING: Nyx has disabled KVM's dirty-ring (required to enable full VGA support during pre-snapshot creation procedure)\n"); fprintf(stderr,
fast_reload_set_mode(get_fast_reload_snapshot(), RELOAD_MEMORY_MODE_DEBUG_QUIET); /* required to create snapshot */ "WARNING: Nyx has disabled KVM's dirty-ring (required to enable "
} "full VGA support during pre-snapshot creation procedure)\n");
else{ fast_reload_set_mode(
get_fast_reload_snapshot(),
RELOAD_MEMORY_MODE_DEBUG_QUIET); /* required to create snapshot */
} else {
nyx_dirty_ring_early_init(s->fd, s->vmfd); nyx_dirty_ring_early_init(s->fd, s->vmfd);
} }
} }
@ -2105,11 +2120,10 @@ static int kvm_init(MachineState *ms)
#ifndef QEMU_NYX #ifndef QEMU_NYX
ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0, 1); ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0, 1);
#else #else
// clang-format on // clang-format on
if(s->nyx_no_pt_mode){ if (s->nyx_no_pt_mode) {
ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0, 1); ret = kvm_vm_enable_cap(s, KVM_CAP_MANUAL_DIRTY_LOG_PROTECT2, 0, 1);
} } else {
else{
ret = 0; ret = 0;
} }
// clang-format off // clang-format off
@ -2405,13 +2419,14 @@ static void kvm_eat_signals(CPUState *cpu)
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
static int handle_vmware_hypercall(struct kvm_run *run, CPUState *cpu){ static int handle_vmware_hypercall(struct kvm_run *run, CPUState *cpu)
{
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
X86CPU *x86_cpu = X86_CPU(cpu); X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env; CPUX86State *env = &x86_cpu->env;
return handle_kafl_hypercall(run, cpu, env->regs[R_EBX]+100, env->regs[R_ECX]); return handle_kafl_hypercall(run, cpu, env->regs[R_EBX] + 100, env->regs[R_ECX]);
} }
// clang-format off // clang-format off
#endif #endif
@ -2432,9 +2447,9 @@ int kvm_cpu_exec(CPUState *cpu)
cpu_exec_start(cpu); cpu_exec_start(cpu);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
static bool timeout_reload_pending = false; static bool timeout_reload_pending = false;
if(timeout_reload_pending){ if (timeout_reload_pending) {
synchronization_lock_timeout_found(); synchronization_lock_timeout_found();
} }
timeout_reload_pending = false; timeout_reload_pending = false;
@ -2462,8 +2477,8 @@ int kvm_cpu_exec(CPUState *cpu)
} }
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(!kvm_state->nyx_no_pt_mode){ if (!kvm_state->nyx_no_pt_mode) {
pt_pre_kvm_run(cpu); pt_pre_kvm_run(cpu);
} }
// clang-format off // clang-format off
@ -2475,7 +2490,7 @@ int kvm_cpu_exec(CPUState *cpu)
smp_rmb(); smp_rmb();
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
arm_sigprof_timer(&GET_GLOBAL_STATE()->timeout_detector); arm_sigprof_timer(&GET_GLOBAL_STATE()->timeout_detector);
// clang-format off // clang-format off
#endif #endif
@ -2483,8 +2498,8 @@ int kvm_cpu_exec(CPUState *cpu)
run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0); run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if (disarm_sigprof_timer(&GET_GLOBAL_STATE()->timeout_detector)){ if (disarm_sigprof_timer(&GET_GLOBAL_STATE()->timeout_detector)) {
timeout_reload_pending = true; timeout_reload_pending = true;
} }
// clang-format off // clang-format off
@ -2493,8 +2508,8 @@ int kvm_cpu_exec(CPUState *cpu)
attrs = kvm_arch_post_run(cpu, run); attrs = kvm_arch_post_run(cpu, run);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(!kvm_state->nyx_no_pt_mode){ if (!kvm_state->nyx_no_pt_mode) {
pt_post_kvm_run(cpu); pt_post_kvm_run(cpu);
} }
// clang-format off // clang-format off
@ -2522,24 +2537,25 @@ int kvm_cpu_exec(CPUState *cpu)
fprintf(stderr, "error: kvm run failed %s\n", fprintf(stderr, "error: kvm run failed %s\n",
strerror(-run_ret)); strerror(-run_ret));
#else #else
// clang-format on // clang-format on
if(run_ret == -EFAULT){ if (run_ret == -EFAULT) {
if(GET_GLOBAL_STATE()->protect_payload_buffer){ if (GET_GLOBAL_STATE()->protect_payload_buffer) {
if (GET_GLOBAL_STATE()->in_fuzzing_mode){ if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
synchronization_payload_buffer_write_detected(); synchronization_payload_buffer_write_detected();
ret = 0; ret = 0;
break; break;
} } else {
else{ fprintf(
fprintf(stderr, "ERROR: invalid write to input buffer detected before harness was ready (write protection is enabled)!\n"); stderr,
"ERROR: invalid write to input buffer detected before "
"harness was ready (write protection is enabled)!\n");
exit(1); exit(1);
} }
} }
} }
fprintf(stderr, "QEMU-PT: error: kvm run failed %s\n", fprintf(stderr, "QEMU-PT: error: kvm run failed %s\n", strerror(-run_ret));
strerror(-run_ret));
qemu_backtrace(); qemu_backtrace();
// clang-format off // clang-format off
#endif #endif
@ -2562,8 +2578,10 @@ int kvm_cpu_exec(CPUState *cpu)
DPRINTF("handle_io\n"); DPRINTF("handle_io\n");
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(run->io.port == 0x5658 && run->io.size == 4 && *((uint32_t*)((uint8_t *)run + run->io.data_offset)) == 0x8080801f) { if (run->io.port == 0x5658 && run->io.size == 4 &&
*((uint32_t *)((uint8_t *)run + run->io.data_offset)) == 0x8080801f)
{
assert(kvm_state->nyx_no_pt_mode); assert(kvm_state->nyx_no_pt_mode);
ret = handle_vmware_hypercall(run, cpu); ret = handle_vmware_hypercall(run, cpu);
break; break;
@ -2598,20 +2616,23 @@ int kvm_cpu_exec(CPUState *cpu)
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET); qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
#else #else
// clang-format on // clang-format on
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
#define CONFIG_KVM_EXIT_SHUTODWN_IS_PANIC // consider triple-fault etc as crash? #define CONFIG_KVM_EXIT_SHUTODWN_IS_PANIC // consider triple-fault etc as crash?
#ifndef CONFIG_KVM_EXIT_SHUTODWN_IS_PANIC #ifndef CONFIG_KVM_EXIT_SHUTODWN_IS_PANIC
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
fprintf(stderr, "Got KVM_EXIT_SHUTDOWN while in fuzzing mode => reload\n",); fprintf(stderr,
handle_hypercall_kafl_release(run, cpu, (uint64_t)run->hypercall.args[0]); "Got KVM_EXIT_SHUTDOWN while in fuzzing mode => reload\n", );
handle_hypercall_kafl_release(run, cpu,
(uint64_t)run->hypercall.args[0]);
ret = 0; ret = 0;
#else #else
nyx_debug("Got KVM_EXIT_SHUTDOWN while in fuzzing mode => panic\n"); nyx_debug("Got KVM_EXIT_SHUTDOWN while in fuzzing mode => panic\n");
handle_hypercall_kafl_panic(run, cpu, (uint64_t)run->hypercall.args[0]); handle_hypercall_kafl_panic(run, cpu,
(uint64_t)run->hypercall.args[0]);
ret = 0; ret = 0;
#endif #endif
} else{ } else {
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET); qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
} }
@ -2623,7 +2644,7 @@ int kvm_cpu_exec(CPUState *cpu)
(uint64_t)run->hw.hardware_exit_reason); (uint64_t)run->hw.hardware_exit_reason);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
assert(false); assert(false);
// clang-format off // clang-format off
#endif #endif
@ -2635,23 +2656,24 @@ int kvm_cpu_exec(CPUState *cpu)
break; break;
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
case KVM_EXIT_DIRTY_RING_FULL: case KVM_EXIT_DIRTY_RING_FULL:
//printf("[*] WARNING: KVM_EXIT_DIRTY_RING_FULL\n"); // printf("[*] WARNING: KVM_EXIT_DIRTY_RING_FULL\n");
fast_reload_handle_dirty_ring_full(get_fast_reload_snapshot()); fast_reload_handle_dirty_ring_full(get_fast_reload_snapshot());
ret = 0; ret = 0;
break; break;
case KVM_EXIT_KAFL_ACQUIRE ... (KVM_EXIT_KAFL_ACQUIRE+100): case KVM_EXIT_KAFL_ACQUIRE ...(KVM_EXIT_KAFL_ACQUIRE + 100):
ret = handle_kafl_hypercall(run, cpu, (uint64_t)run->exit_reason, (uint64_t)run->hypercall.args[0]); ret = handle_kafl_hypercall(run, cpu, (uint64_t)run->exit_reason,
(uint64_t)run->hypercall.args[0]);
break; break;
case KVM_EXIT_DEBUG: case KVM_EXIT_DEBUG:
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
if(!handle_hypercall_kafl_hook(run, cpu, (uint64_t)run->hypercall.args[0])){ if (!handle_hypercall_kafl_hook(run, cpu, (uint64_t)run->hypercall.args[0]))
{
ret = kvm_arch_handle_exit(cpu, run); ret = kvm_arch_handle_exit(cpu, run);
} } else {
else {
ret = 0; ret = 0;
} }
break; break;
@ -2665,14 +2687,16 @@ int kvm_cpu_exec(CPUState *cpu)
qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN); qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
#else #else
// clang-format on // clang-format on
fprintf(stderr, "ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_SHUTDOWN)!\n"); fprintf(
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ stderr,
"ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_SHUTDOWN)!\n");
if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
handle_hypercall_kafl_release(run, cpu, (uint64_t)run->hypercall.args[0]); handle_hypercall_kafl_release(run, cpu,
(uint64_t)run->hypercall.args[0]);
ret = 0; ret = 0;
} } else {
else{
qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN); qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
} }
@ -2684,14 +2708,15 @@ int kvm_cpu_exec(CPUState *cpu)
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET); qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
#else #else
// clang-format on // clang-format on
fprintf(stderr, "ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_RESET)!\n"); fprintf(stderr,
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ "ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_RESET)!\n");
if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
handle_hypercall_kafl_release(run, cpu, (uint64_t)run->hypercall.args[0]); handle_hypercall_kafl_release(run, cpu,
(uint64_t)run->hypercall.args[0]);
ret = 0; ret = 0;
} } else {
else{
qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET); qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);
ret = EXCP_INTERRUPT; ret = EXCP_INTERRUPT;
} }
@ -2706,14 +2731,15 @@ int kvm_cpu_exec(CPUState *cpu)
qemu_mutex_unlock_iothread(); qemu_mutex_unlock_iothread();
ret = 0; ret = 0;
#else #else
// clang-format on // clang-format on
fprintf(stderr, "ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_CRASH)!\n"); fprintf(stderr,
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ "ATTEMPT TO SHUTDOWN MACHINE (KVM_SYSTEM_EVENT_CRASH)!\n");
if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
handle_hypercall_kafl_release(run, cpu, (uint64_t)run->hypercall.args[0]); handle_hypercall_kafl_release(run, cpu,
(uint64_t)run->hypercall.args[0]);
ret = 0; ret = 0;
} } else {
else{
kvm_cpu_synchronize_state(cpu); kvm_cpu_synchronize_state(cpu);
qemu_mutex_lock_iothread(); qemu_mutex_lock_iothread();
qemu_system_guest_panicked(cpu_get_crash_info(cpu)); qemu_system_guest_panicked(cpu_get_crash_info(cpu));
@ -2743,7 +2769,8 @@ int kvm_cpu_exec(CPUState *cpu)
nyx_debug("kvm_arch_handle_exit(%d) => panic\n", run->exit_reason); nyx_debug("kvm_arch_handle_exit(%d) => panic\n", run->exit_reason);
ret = kvm_arch_handle_exit(cpu, run); ret = kvm_arch_handle_exit(cpu, run);
if (ret != 0) if (ret != 0)
handle_hypercall_kafl_panic(run, cpu, (uint64_t)run->hypercall.args[0]); handle_hypercall_kafl_panic(run, cpu,
(uint64_t)run->hypercall.args[0]);
#endif #endif
// clang-format off // clang-format off
#endif #endif
@ -2752,30 +2779,34 @@ int kvm_cpu_exec(CPUState *cpu)
} }
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(GET_GLOBAL_STATE()->in_fuzzing_mode && GET_GLOBAL_STATE()->cow_cache_full){ if (GET_GLOBAL_STATE()->in_fuzzing_mode && GET_GLOBAL_STATE()->cow_cache_full)
{
synchronization_cow_full_detected(); synchronization_cow_full_detected();
GET_GLOBAL_STATE()->cow_cache_full = false; GET_GLOBAL_STATE()->cow_cache_full = false;
ret = 0; ret = 0;
} } else {
else{ if (GET_GLOBAL_STATE()->in_fuzzing_mode && cpu->halted) {
if(GET_GLOBAL_STATE()->in_fuzzing_mode && cpu->halted){
fprintf(stderr, "%s: Attempt to halt CPU -> FUCK OFF!\n", __func__); fprintf(stderr, "%s: Attempt to halt CPU -> FUCK OFF!\n", __func__);
cpu->halted = 0; cpu->halted = 0;
GET_GLOBAL_STATE()->shutdown_requested = true; GET_GLOBAL_STATE()->shutdown_requested = true;
} }
if(GET_GLOBAL_STATE()->in_fuzzing_mode && GET_GLOBAL_STATE()->shutdown_requested){ if (GET_GLOBAL_STATE()->in_fuzzing_mode &&
GET_GLOBAL_STATE()->shutdown_requested)
{
/* Fuzzing is enabled at this point -> don't exit */ /* Fuzzing is enabled at this point -> don't exit */
fprintf(stderr, "shutdown_requested -> calling handle_hypercall_kafl_release\n"); fprintf(
stderr,
"shutdown_requested -> calling handle_hypercall_kafl_release\n");
//synchronization_lock_shutdown_detected(); // synchronization_lock_shutdown_detected();
synchronization_lock_crash_found(); synchronization_lock_crash_found();
GET_GLOBAL_STATE()->shutdown_requested = false; GET_GLOBAL_STATE()->shutdown_requested = false;
ret = 0; ret = 0;
} }
} }
if(reload_request_exists(GET_GLOBAL_STATE()->reload_state)){ if (reload_request_exists(GET_GLOBAL_STATE()->reload_state)) {
break; break;
} }
// clang-format off // clang-format off
@ -2788,7 +2819,7 @@ int kvm_cpu_exec(CPUState *cpu)
if (ret < 0) { if (ret < 0) {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
fprintf(stderr, "ATTEMPT TO SHUTDOWN MACHINE (ret < 0)!\n"); fprintf(stderr, "ATTEMPT TO SHUTDOWN MACHINE (ret < 0)!\n");
// clang-format off // clang-format off
#endif #endif
@ -2799,8 +2830,8 @@ int kvm_cpu_exec(CPUState *cpu)
atomic_set(&cpu->exit_request, 0); atomic_set(&cpu->exit_request, 0);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(check_if_relood_request_exists_pre(GET_GLOBAL_STATE()->reload_state)){ if (check_if_relood_request_exists_pre(GET_GLOBAL_STATE()->reload_state)) {
pause_all_vcpus(); /* performance boost ??? */ pause_all_vcpus(); /* performance boost ??? */
} }
// clang-format off // clang-format off
@ -3203,7 +3234,7 @@ void kvm_init_cpu_signals(CPUState *cpu)
#endif #endif
sigdelset(&set, SIG_IPI); sigdelset(&set, SIG_IPI);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
sigdelset(&set, SIGALRM); sigdelset(&set, SIGALRM);
// clang-format off // clang-format off
#endif #endif

View File

@ -19,89 +19,95 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "nyx/auxiliary_buffer.h" #include "nyx/auxiliary_buffer.h"
#include "nyx/state/state.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/state/state.h"
#include "nyx/trace_dump.h" #include "nyx/trace_dump.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
/* experimental feature (currently broken) /* experimental feature (currently broken)
* enabled via trace mode * enabled via trace mode
*/ */
//#define SUPPORT_COMPILE_TIME_REDQUEEN // #define SUPPORT_COMPILE_TIME_REDQUEEN
#define VOLATILE_WRITE_64(dst, src) *((volatile uint64_t*)&dst) = (uint64_t)src #define VOLATILE_WRITE_64(dst, src) *((volatile uint64_t *)&dst) = (uint64_t)src
#define VOLATILE_WRITE_32(dst, src) *((volatile uint32_t*)&dst) = (uint32_t)src #define VOLATILE_WRITE_32(dst, src) *((volatile uint32_t *)&dst) = (uint32_t)src
#define VOLATILE_WRITE_16(dst, src) *((volatile uint16_t*)&dst) = (uint16_t)src #define VOLATILE_WRITE_16(dst, src) *((volatile uint16_t *)&dst) = (uint16_t)src
#define VOLATILE_WRITE_8(dst, src) *((volatile uint8_t*)&dst) = (uint8_t)src #define VOLATILE_WRITE_8(dst, src) *((volatile uint8_t *)&dst) = (uint8_t)src
#define VOLATILE_READ_64(dst, src) dst = *((volatile uint64_t*)(&src)) #define VOLATILE_READ_64(dst, src) dst = *((volatile uint64_t *)(&src))
#define VOLATILE_READ_32(dst, src) dst = *((volatile uint32_t*)(&src)) #define VOLATILE_READ_32(dst, src) dst = *((volatile uint32_t *)(&src))
#define VOLATILE_READ_16(dst, src) dst = *((volatile uint16_t*)(&src)) #define VOLATILE_READ_16(dst, src) dst = *((volatile uint16_t *)(&src))
#define VOLATILE_READ_8(dst, src) dst = *((volatile uint8_t*)(&src)) #define VOLATILE_READ_8(dst, src) dst = *((volatile uint8_t *)(&src))
static void volatile_memset(void* dst, uint8_t ch, size_t count){ static void volatile_memset(void *dst, uint8_t ch, size_t count)
for (size_t i = 0; i < count; i++){ {
VOLATILE_WRITE_8(((uint8_t*)dst)[i], ch); for (size_t i = 0; i < count; i++) {
VOLATILE_WRITE_8(((uint8_t *)dst)[i], ch);
} }
} }
static void volatile_memcpy(void* dst, void* src, size_t size){ static void volatile_memcpy(void *dst, void *src, size_t size)
for (size_t i = 0; i < size; i++){ {
VOLATILE_WRITE_8(((uint8_t*)dst)[i], ((uint8_t*)src)[i]); for (size_t i = 0; i < size; i++) {
VOLATILE_WRITE_8(((uint8_t *)dst)[i], ((uint8_t *)src)[i]);
} }
} }
void init_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer){ void init_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer)
{
nyx_trace(); nyx_trace();
volatile_memset((void*) auxilary_buffer, 0, sizeof(auxilary_buffer_t)); volatile_memset((void *)auxilary_buffer, 0, sizeof(auxilary_buffer_t));
VOLATILE_WRITE_16(auxilary_buffer->header.version, QEMU_PT_VERSION); VOLATILE_WRITE_16(auxilary_buffer->header.version, QEMU_PT_VERSION);
uint16_t hash = (sizeof(auxilary_buffer_header_t) + uint16_t hash =
sizeof(auxilary_buffer_cap_t) + (sizeof(auxilary_buffer_header_t) + sizeof(auxilary_buffer_cap_t) +
sizeof(auxilary_buffer_config_t) + sizeof(auxilary_buffer_config_t) + sizeof(auxilary_buffer_result_t) +
sizeof(auxilary_buffer_result_t) + sizeof(auxilary_buffer_misc_t)) %
sizeof(auxilary_buffer_misc_t)) % 0xFFFF; 0xFFFF;
VOLATILE_WRITE_16(auxilary_buffer->header.hash, hash); VOLATILE_WRITE_16(auxilary_buffer->header.hash, hash);
VOLATILE_WRITE_64(auxilary_buffer->header.magic, AUX_MAGIC); VOLATILE_WRITE_64(auxilary_buffer->header.magic, AUX_MAGIC);
} }
void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_buffer_config_t* shadow_config){ void check_auxiliary_config_buffer(auxilary_buffer_t *auxilary_buffer,
auxilary_buffer_config_t *shadow_config)
{
uint8_t changed = 0; uint8_t changed = 0;
VOLATILE_READ_8(changed, auxilary_buffer->configuration.changed); VOLATILE_READ_8(changed, auxilary_buffer->configuration.changed);
if (changed){ if (changed) {
uint8_t aux_byte; uint8_t aux_byte;
VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.redqueen_mode); VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.redqueen_mode);
if(aux_byte){ if (aux_byte) {
/* enable redqueen mode */ /* enable redqueen mode */
if(aux_byte != shadow_config->redqueen_mode){ if (aux_byte != shadow_config->redqueen_mode) {
GET_GLOBAL_STATE()->in_redqueen_reload_mode = true; GET_GLOBAL_STATE()->in_redqueen_reload_mode = true;
GET_GLOBAL_STATE()->redqueen_enable_pending = true; GET_GLOBAL_STATE()->redqueen_enable_pending = true;
GET_GLOBAL_STATE()->redqueen_instrumentation_mode = REDQUEEN_LIGHT_INSTRUMENTATION; GET_GLOBAL_STATE()->redqueen_instrumentation_mode =
REDQUEEN_LIGHT_INSTRUMENTATION;
} }
} } else {
else{
/* disable redqueen mode */ /* disable redqueen mode */
if(aux_byte != shadow_config->redqueen_mode){ if (aux_byte != shadow_config->redqueen_mode) {
GET_GLOBAL_STATE()->in_redqueen_reload_mode = false; GET_GLOBAL_STATE()->in_redqueen_reload_mode = false;
GET_GLOBAL_STATE()->redqueen_disable_pending = true; GET_GLOBAL_STATE()->redqueen_disable_pending = true;
GET_GLOBAL_STATE()->redqueen_instrumentation_mode = REDQUEEN_NO_INSTRUMENTATION; GET_GLOBAL_STATE()->redqueen_instrumentation_mode =
REDQUEEN_NO_INSTRUMENTATION;
} }
} }
VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.trace_mode); VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.trace_mode);
if(aux_byte){ if (aux_byte) {
/* enable trace mode */ /* enable trace mode */
if(aux_byte != shadow_config->trace_mode && GET_GLOBAL_STATE()->redqueen_state){ if (aux_byte != shadow_config->trace_mode &&
GET_GLOBAL_STATE()->redqueen_state)
{
#ifdef SUPPORT_COMPILE_TIME_REDQUEEN #ifdef SUPPORT_COMPILE_TIME_REDQUEEN
GET_GLOBAL_STATE()->pt_trace_mode_force = true; GET_GLOBAL_STATE()->pt_trace_mode_force = true;
#endif #endif
@ -109,10 +115,11 @@ void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_
redqueen_set_trace_mode(); redqueen_set_trace_mode();
pt_trace_dump_enable(true); pt_trace_dump_enable(true);
} }
} } else {
else {
/* disable trace mode */ /* disable trace mode */
if(aux_byte != shadow_config->trace_mode && GET_GLOBAL_STATE()->redqueen_state){ if (aux_byte != shadow_config->trace_mode &&
GET_GLOBAL_STATE()->redqueen_state)
{
#ifdef SUPPORT_COMPILE_TIME_REDQUEEN #ifdef SUPPORT_COMPILE_TIME_REDQUEEN
GET_GLOBAL_STATE()->pt_trace_mode_force = false; GET_GLOBAL_STATE()->pt_trace_mode_force = false;
#endif #endif
@ -123,12 +130,12 @@ void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_
} }
VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.page_dump_mode); VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.page_dump_mode);
if(aux_byte){ if (aux_byte) {
GET_GLOBAL_STATE()->dump_page = true; GET_GLOBAL_STATE()->dump_page = true;
uint64_t data; uint64_t data;
VOLATILE_READ_64(data, auxilary_buffer->configuration.page_addr); VOLATILE_READ_64(data, auxilary_buffer->configuration.page_addr);
GET_GLOBAL_STATE()->dump_page_addr = data; GET_GLOBAL_STATE()->dump_page_addr = data;
//fprintf(stderr, "%s dump_page_addr => 0x%lx\n", __func__, GET_GLOBAL_STATE()->dump_page_addr); // fprintf(stderr, "%s dump_page_addr => 0x%lx\n", __func__, GET_GLOBAL_STATE()->dump_page_addr);
VOLATILE_WRITE_8(auxilary_buffer->configuration.page_dump_mode, 0); VOLATILE_WRITE_8(auxilary_buffer->configuration.page_dump_mode, 0);
VOLATILE_WRITE_64(auxilary_buffer->configuration.page_addr, 0); VOLATILE_WRITE_64(auxilary_buffer->configuration.page_addr, 0);
} }
@ -138,8 +145,9 @@ void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_
GET_GLOBAL_STATE()->in_reload_mode = aux_byte; GET_GLOBAL_STATE()->in_reload_mode = aux_byte;
/* modify protect_payload_buffer */ /* modify protect_payload_buffer */
VOLATILE_READ_8(aux_byte, auxilary_buffer->configuration.protect_payload_buffer); VOLATILE_READ_8(aux_byte,
if (GET_GLOBAL_STATE()->protect_payload_buffer == 0 && aux_byte == 1){ auxilary_buffer->configuration.protect_payload_buffer);
if (GET_GLOBAL_STATE()->protect_payload_buffer == 0 && aux_byte == 1) {
GET_GLOBAL_STATE()->protect_payload_buffer = aux_byte; GET_GLOBAL_STATE()->protect_payload_buffer = aux_byte;
} }
@ -149,46 +157,62 @@ void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_
VOLATILE_WRITE_8(auxilary_buffer->configuration.discard_tmp_snapshot, 0); VOLATILE_WRITE_8(auxilary_buffer->configuration.discard_tmp_snapshot, 0);
/* copy to shodow */ /* copy to shodow */
VOLATILE_READ_8(shadow_config->timeout_sec, auxilary_buffer->configuration.timeout_sec); VOLATILE_READ_8(shadow_config->timeout_sec,
VOLATILE_READ_32(shadow_config->timeout_usec, auxilary_buffer->configuration.timeout_usec); auxilary_buffer->configuration.timeout_sec);
VOLATILE_READ_32(shadow_config->timeout_usec,
auxilary_buffer->configuration.timeout_usec);
//if(shadow_config->timeout_sec || shadow_config->timeout_usec){ // if(shadow_config->timeout_sec || shadow_config->timeout_usec){
/* apply only non-zero values */ /* apply only non-zero values */
update_itimer(&(GET_GLOBAL_STATE()->timeout_detector), shadow_config->timeout_sec, shadow_config->timeout_usec); update_itimer(&(GET_GLOBAL_STATE()->timeout_detector),
shadow_config->timeout_sec, shadow_config->timeout_usec);
//} //}
VOLATILE_READ_8(shadow_config->redqueen_mode, auxilary_buffer->configuration.redqueen_mode); VOLATILE_READ_8(shadow_config->redqueen_mode,
VOLATILE_READ_8(shadow_config->trace_mode, auxilary_buffer->configuration.trace_mode); auxilary_buffer->configuration.redqueen_mode);
VOLATILE_READ_8(shadow_config->reload_mode, auxilary_buffer->configuration.reload_mode); VOLATILE_READ_8(shadow_config->trace_mode,
auxilary_buffer->configuration.trace_mode);
VOLATILE_READ_8(shadow_config->reload_mode,
auxilary_buffer->configuration.reload_mode);
VOLATILE_READ_8(shadow_config->verbose_level, auxilary_buffer->configuration.verbose_level); VOLATILE_READ_8(shadow_config->verbose_level,
auxilary_buffer->configuration.verbose_level);
/* reset the 'changed' byte */ /* reset the 'changed' byte */
VOLATILE_WRITE_8(auxilary_buffer->configuration.changed, 0); VOLATILE_WRITE_8(auxilary_buffer->configuration.changed, 0);
} }
} }
void set_crash_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer){ void set_crash_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_crash); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_crash);
} }
void set_asan_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer){ void set_asan_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_sanitizer); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_sanitizer);
} }
void set_timeout_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer){ void set_timeout_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_timeout); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_timeout);
} }
void set_reload_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer){ void set_reload_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.reloaded, 1); VOLATILE_WRITE_8(auxilary_buffer->result.reloaded, 1);
} }
void set_pt_overflow_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer){ void set_pt_overflow_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.pt_overflow, 1); VOLATILE_WRITE_8(auxilary_buffer->result.pt_overflow, 1);
} }
void set_exec_done_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint32_t sec, uint32_t usec, uint32_t num_dirty_pages){ void set_exec_done_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
uint32_t sec,
uint32_t usec,
uint32_t num_dirty_pages)
{
VOLATILE_WRITE_8(auxilary_buffer->result.exec_done, 1); VOLATILE_WRITE_8(auxilary_buffer->result.exec_done, 1);
VOLATILE_WRITE_32(auxilary_buffer->result.runtime_sec, sec); VOLATILE_WRITE_32(auxilary_buffer->result.runtime_sec, sec);
@ -197,45 +221,62 @@ void set_exec_done_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, u
} }
void set_hprintf_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
void set_hprintf_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len){ char *msg,
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE-2)); uint32_t len)
volatile_memcpy((void*)&auxilary_buffer->misc.data, (void*)msg, (size_t)MIN(len, MISC_SIZE-2)); {
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE - 2));
volatile_memcpy((void *)&auxilary_buffer->misc.data, (void *)msg,
(size_t)MIN(len, MISC_SIZE - 2));
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_hprintf); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_hprintf);
} }
void set_crash_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len){ void set_crash_reason_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE-2)); char *msg,
volatile_memcpy((void*)&auxilary_buffer->misc.data, (void*)msg, (size_t) MIN(len, MISC_SIZE-2)); uint32_t len)
{
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE - 2));
volatile_memcpy((void *)&auxilary_buffer->misc.data, (void *)msg,
(size_t)MIN(len, MISC_SIZE - 2));
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_crash); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_crash);
} }
void set_abort_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len){ void set_abort_reason_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE-2)); char *msg,
volatile_memcpy((void*)&auxilary_buffer->misc.data, (void*)msg, (size_t) MIN(len, MISC_SIZE-2)); uint32_t len)
{
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE - 2));
volatile_memcpy((void *)&auxilary_buffer->misc.data, (void *)msg,
(size_t)MIN(len, MISC_SIZE - 2));
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_aborted); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_aborted);
} }
void set_state_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint8_t state){ void set_state_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
if(auxilary_buffer){ uint8_t state)
{
if (auxilary_buffer) {
VOLATILE_WRITE_8(auxilary_buffer->result.state, state); VOLATILE_WRITE_8(auxilary_buffer->result.state, state);
} } else {
else{
nyx_error("WARNING: auxilary_buffer pointer is zero\n"); nyx_error("WARNING: auxilary_buffer pointer is zero\n");
} }
} }
void set_page_not_found_result_buffer(auxilary_buffer_t* auxilary_buffer, uint64_t page_addr){ void set_page_not_found_result_buffer(auxilary_buffer_t *auxilary_buffer,
uint64_t page_addr)
{
VOLATILE_WRITE_8(auxilary_buffer->result.page_not_found, 1); VOLATILE_WRITE_8(auxilary_buffer->result.page_not_found, 1);
VOLATILE_WRITE_64(auxilary_buffer->result.page_addr, page_addr); VOLATILE_WRITE_64(auxilary_buffer->result.page_addr, page_addr);
} }
void reset_page_not_found_result_buffer(auxilary_buffer_t* auxilary_buffer){ void reset_page_not_found_result_buffer(auxilary_buffer_t *auxilary_buffer)
{
VOLATILE_WRITE_8(auxilary_buffer->result.page_not_found, 0); VOLATILE_WRITE_8(auxilary_buffer->result.page_not_found, 0);
} }
void set_success_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint8_t success){ void set_success_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
//TODO refactor to let caller directly set the result codes uint8_t success)
{
// TODO refactor to let caller directly set the result codes
if (success == 2) { if (success == 2) {
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_starved); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_starved);
} else { } else {
@ -243,35 +284,44 @@ void set_success_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uin
} }
} }
void set_payload_buffer_write_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len){ void set_payload_buffer_write_reason_auxiliary_buffer(
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE-2)); auxilary_buffer_t *auxilary_buffer, char *msg, uint32_t len)
volatile_memcpy((void*)&auxilary_buffer->misc.data, (void*)msg, (size_t) MIN(len, MISC_SIZE-2)); {
VOLATILE_WRITE_16(auxilary_buffer->misc.len, MIN(len, MISC_SIZE - 2));
volatile_memcpy((void *)&auxilary_buffer->misc.data, (void *)msg,
(size_t)MIN(len, MISC_SIZE - 2));
VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_input_buffer_write); VOLATILE_WRITE_8(auxilary_buffer->result.exec_result_code, rc_input_buffer_write);
} }
void set_tmp_snapshot_created(auxilary_buffer_t* auxilary_buffer, uint8_t value){ void set_tmp_snapshot_created(auxilary_buffer_t *auxilary_buffer, uint8_t value)
{
VOLATILE_WRITE_8(auxilary_buffer->result.tmp_snapshot_created, value); VOLATILE_WRITE_8(auxilary_buffer->result.tmp_snapshot_created, value);
} }
void set_cap_agent_trace_bitmap(auxilary_buffer_t* auxilary_buffer, bool value){ void set_cap_agent_trace_bitmap(auxilary_buffer_t *auxilary_buffer, bool value)
{
VOLATILE_WRITE_8(auxilary_buffer->capabilites.agent_trace_bitmap, value); VOLATILE_WRITE_8(auxilary_buffer->capabilites.agent_trace_bitmap, value);
} }
void set_cap_agent_ijon_trace_bitmap(auxilary_buffer_t* auxilary_buffer, bool value){ void set_cap_agent_ijon_trace_bitmap(auxilary_buffer_t *auxilary_buffer, bool value)
{
VOLATILE_WRITE_8(auxilary_buffer->capabilites.agent_ijon_trace_bitmap, value); VOLATILE_WRITE_8(auxilary_buffer->capabilites.agent_ijon_trace_bitmap, value);
} }
void set_result_dirty_pages(auxilary_buffer_t* auxilary_buffer, uint32_t value){ void set_result_dirty_pages(auxilary_buffer_t *auxilary_buffer, uint32_t value)
{
VOLATILE_WRITE_32(auxilary_buffer->result.dirty_pages, value); VOLATILE_WRITE_32(auxilary_buffer->result.dirty_pages, value);
} }
void set_result_pt_trace_size(auxilary_buffer_t* auxilary_buffer, uint32_t value){ void set_result_pt_trace_size(auxilary_buffer_t *auxilary_buffer, uint32_t value)
{
VOLATILE_WRITE_32(auxilary_buffer->result.pt_trace_size, value); VOLATILE_WRITE_32(auxilary_buffer->result.pt_trace_size, value);
} }
void set_result_bb_coverage(auxilary_buffer_t* auxilary_buffer, uint32_t value){ void set_result_bb_coverage(auxilary_buffer_t *auxilary_buffer, uint32_t value)
if (value != auxilary_buffer->result.bb_coverage){ {
if (value != auxilary_buffer->result.bb_coverage) {
VOLATILE_WRITE_32(auxilary_buffer->result.bb_coverage, value); VOLATILE_WRITE_32(auxilary_buffer->result.bb_coverage, value);
} }
} }

View File

@ -21,22 +21,23 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#pragma once #pragma once
#include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdint.h>
#define AUX_BUFFER_SIZE 4096 #define AUX_BUFFER_SIZE 4096
#define AUX_MAGIC 0x54502d554d4551 #define AUX_MAGIC 0x54502d554d4551
#define QEMU_PT_VERSION 3 /* let's start at 1 for the initial version using the aux buffer */ #define QEMU_PT_VERSION \
3 /* let's start at 1 for the initial version using the aux buffer */
#define HEADER_SIZE 128 #define HEADER_SIZE 128
#define CAP_SIZE 256 #define CAP_SIZE 256
#define CONFIG_SIZE 512 #define CONFIG_SIZE 512
#define STATE_SIZE 512 #define STATE_SIZE 512
#define MISC_SIZE 4096-(HEADER_SIZE+CAP_SIZE+CONFIG_SIZE+STATE_SIZE) #define MISC_SIZE 4096 - (HEADER_SIZE + CAP_SIZE + CONFIG_SIZE + STATE_SIZE)
#define ADD_PADDING(max, type) uint8_t type ## _padding [max - sizeof(type)] #define ADD_PADDING(max, type) uint8_t type##_padding[max - sizeof(type)]
enum nyx_result_codes { enum nyx_result_codes {
rc_success = 0, rc_success = 0,
@ -49,25 +50,28 @@ enum nyx_result_codes {
rc_starved = 7, rc_starved = 7,
}; };
typedef struct auxilary_buffer_header_s{ typedef struct auxilary_buffer_header_s {
uint64_t magic; uint64_t magic;
uint16_t version; uint16_t version;
uint16_t hash; uint16_t hash;
/* more to come */ /* more to come */
} __attribute__((packed)) auxilary_buffer_header_t; } __attribute__((packed)) auxilary_buffer_header_t;
typedef struct auxilary_buffer_cap_s{ typedef struct auxilary_buffer_cap_s {
uint8_t redqueen; uint8_t redqueen;
uint8_t agent_timeout_detection; /* agent implements its own timeout detection; host timeout detection is still in used, but treshold is increased by x2; */ uint8_t agent_timeout_detection; /* agent implements its own timeout detection;
host timeout detection is still in used, but treshold is increased by x2; */
uint8_t agent_trace_bitmap; /* agent implements its own tracing mechanism; PT tracing is disabled */ uint8_t agent_trace_bitmap; /* agent implements its own tracing mechanism; PT tracing is disabled */
uint8_t agent_ijon_trace_bitmap; /* agent uses the ijon shm buffer */ uint8_t agent_ijon_trace_bitmap; /* agent uses the ijon shm buffer */
uint32_t agent_input_buffer_size; /* agent requests a custom input buffer size (if the size is 0, the minimum buffer size is used) */ uint32_t agent_input_buffer_size; /* agent requests a custom input buffer size (if
uint32_t agent_coverage_bitmap_size; /* agent requests a custom coverage bitmap size (if the size is 0, the minimum buffer size is used) */ the size is 0, the minimum buffer size is used) */
uint32_t agent_coverage_bitmap_size; /* agent requests a custom coverage bitmap
size (if the size is 0, the minimum buffer size is used) */
/* more to come */ /* more to come */
} __attribute__((packed)) auxilary_buffer_cap_t; } __attribute__((packed)) auxilary_buffer_cap_t;
typedef struct auxilary_buffer_config_s{ typedef struct auxilary_buffer_config_s {
uint8_t changed; /* set this byte to kick in a rescan of this buffer */ uint8_t changed; /* set this byte to kick in a rescan of this buffer */
uint8_t timeout_sec; uint8_t timeout_sec;
@ -90,7 +94,7 @@ typedef struct auxilary_buffer_config_s{
1 -> decoding 1 -> decoding
2 -> decoding + full disassembling 2 -> decoding + full disassembling
*/ */
//uint8_t pt_processing_mode; // uint8_t pt_processing_mode;
/* snapshot extension */ /* snapshot extension */
uint8_t discard_tmp_snapshot; uint8_t discard_tmp_snapshot;
@ -98,7 +102,7 @@ typedef struct auxilary_buffer_config_s{
/* more to come */ /* more to come */
} __attribute__((packed)) auxilary_buffer_config_t; } __attribute__((packed)) auxilary_buffer_config_t;
typedef struct auxilary_buffer_result_s{ typedef struct auxilary_buffer_result_s {
/* 0 -> booting, /* 0 -> booting,
1 -> loader level 1, 1 -> loader level 1,
2 -> loader level 2, 2 -> loader level 2,
@ -124,13 +128,13 @@ typedef struct auxilary_buffer_result_s{
/* more to come */ /* more to come */
} __attribute__((packed)) auxilary_buffer_result_t; } __attribute__((packed)) auxilary_buffer_result_t;
typedef struct auxilary_buffer_misc_s{ typedef struct auxilary_buffer_misc_s {
uint16_t len; uint16_t len;
uint8_t data; uint8_t data;
/* non yet */ /* non yet */
} __attribute__((packed)) auxilary_buffer_misc_t; } __attribute__((packed)) auxilary_buffer_misc_t;
typedef struct auxilary_buffer_s{ typedef struct auxilary_buffer_s {
auxilary_buffer_header_t header; auxilary_buffer_header_t header;
ADD_PADDING(HEADER_SIZE, auxilary_buffer_header_t); ADD_PADDING(HEADER_SIZE, auxilary_buffer_header_t);
@ -148,33 +152,47 @@ typedef struct auxilary_buffer_s{
} __attribute__((packed)) auxilary_buffer_t; } __attribute__((packed)) auxilary_buffer_t;
void init_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer); void init_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer);
void check_auxiliary_config_buffer(auxilary_buffer_t* auxilary_buffer, auxilary_buffer_config_t* shadow_config); void check_auxiliary_config_buffer(auxilary_buffer_t *auxilary_buffer,
auxilary_buffer_config_t *shadow_config);
void set_crash_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer); void set_crash_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_asan_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer); void set_asan_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_timeout_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer); void set_timeout_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_reload_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer); void set_reload_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_pt_overflow_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer); void set_pt_overflow_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_exec_done_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint32_t sec, uint32_t usec, uint32_t num_dirty_pages); void set_exec_done_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
void set_state_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint8_t state); uint32_t sec,
void set_hprintf_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len); uint32_t usec,
uint32_t num_dirty_pages);
void set_state_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
uint8_t state);
void set_hprintf_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
char *msg,
uint32_t len);
void set_page_not_found_result_buffer(auxilary_buffer_t* auxilary_buffer, uint64_t page_addr); void set_page_not_found_result_buffer(auxilary_buffer_t *auxilary_buffer,
void reset_page_not_found_result_buffer(auxilary_buffer_t* auxilary_buffer); uint64_t page_addr);
void set_success_auxiliary_result_buffer(auxilary_buffer_t* auxilary_buffer, uint8_t success); void reset_page_not_found_result_buffer(auxilary_buffer_t *auxilary_buffer);
void set_crash_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len); void set_success_auxiliary_result_buffer(auxilary_buffer_t *auxilary_buffer,
void set_abort_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len); uint8_t success);
void set_crash_reason_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
char *msg,
uint32_t len);
void set_abort_reason_auxiliary_buffer(auxilary_buffer_t *auxilary_buffer,
char *msg,
uint32_t len);
void set_tmp_snapshot_created(auxilary_buffer_t* auxilary_buffer, uint8_t value); void set_tmp_snapshot_created(auxilary_buffer_t *auxilary_buffer, uint8_t value);
void set_cap_agent_trace_bitmap(auxilary_buffer_t* auxilary_buffer, bool value); void set_cap_agent_trace_bitmap(auxilary_buffer_t *auxilary_buffer, bool value);
void set_cap_agent_ijon_trace_bitmap(auxilary_buffer_t* auxilary_buffer, bool value); void set_cap_agent_ijon_trace_bitmap(auxilary_buffer_t *auxilary_buffer, bool value);
void set_result_dirty_pages(auxilary_buffer_t* auxilary_buffer, uint32_t value); void set_result_dirty_pages(auxilary_buffer_t *auxilary_buffer, uint32_t value);
void set_result_pt_trace_size(auxilary_buffer_t* auxilary_buffer, uint32_t value); void set_result_pt_trace_size(auxilary_buffer_t *auxilary_buffer, uint32_t value);
void set_result_bb_coverage(auxilary_buffer_t* auxilary_buffer, uint32_t value); void set_result_bb_coverage(auxilary_buffer_t *auxilary_buffer, uint32_t value);
void set_payload_buffer_write_reason_auxiliary_buffer(auxilary_buffer_t* auxilary_buffer, char* msg, uint32_t len); void set_payload_buffer_write_reason_auxiliary_buffer(
auxilary_buffer_t *auxilary_buffer, char *msg, uint32_t len);

View File

@ -1,8 +1,8 @@
#include <execinfo.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include <execinfo.h>
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "nyx/debug.h" #include "nyx/debug.h"
@ -11,7 +11,8 @@
#ifdef ENABLE_BACKTRACES #ifdef ENABLE_BACKTRACES
#define BT_BUF_SIZE 100 #define BT_BUF_SIZE 100
void qemu_backtrace(void){ void qemu_backtrace(void)
{
void *buffer[BT_BUF_SIZE]; void *buffer[BT_BUF_SIZE];
int nptrs = 0; int nptrs = 0;
int j; int j;
@ -24,7 +25,7 @@ void qemu_backtrace(void){
if (strings == NULL) { if (strings == NULL) {
fprintf(stderr, "backtrace_symbols failed!\n"); fprintf(stderr, "backtrace_symbols failed!\n");
return; return;
//exit(EXIT_FAILURE); // exit(EXIT_FAILURE);
} }
for (j = 0; j < nptrs; j++) for (j = 0; j < nptrs; j++)
@ -33,30 +34,36 @@ void qemu_backtrace(void){
free(strings); free(strings);
} }
static void sigsegfault_handler(int signo, siginfo_t *info, void *extra) { static void sigsegfault_handler(int signo, siginfo_t *info, void *extra)
fprintf(stderr, "[qemu-nyx] crash detected (pid: %d / signal: %d)\n", getpid(), signo); {
fprintf(stderr, "[qemu-nyx] crash detected (pid: %d / signal: %d)\n", getpid(),
signo);
qemu_backtrace(); qemu_backtrace();
fprintf(stderr, "WAITING FOR GDB ATTACH (PID: %d...\n", getpid()); fprintf(stderr, "WAITING FOR GDB ATTACH (PID: %d...\n", getpid());
while(1){ while (1) {
sleep(1); sleep(1);
} }
} }
static void sigabrt_handler(int signo, siginfo_t *info, void *extra) { static void sigabrt_handler(int signo, siginfo_t *info, void *extra)
fprintf(stderr, "[qemu-nyx] crash detected (pid: %d / signal: %d)\n", getpid(), signo); {
fprintf(stderr, "[qemu-nyx] crash detected (pid: %d / signal: %d)\n", getpid(),
signo);
qemu_backtrace(); qemu_backtrace();
fprintf(stderr, "WAITING FOR GDB ATTACH (PID: %d...\n", getpid()); fprintf(stderr, "WAITING FOR GDB ATTACH (PID: %d...\n", getpid());
while(1){ while (1) {
sleep(1); sleep(1);
} }
} }
static void sigint_handler(int signo, siginfo_t *info, void *extra) { static void sigint_handler(int signo, siginfo_t *info, void *extra)
{
fprintf(stderr, "[qemu-nyx] bye! (pid: %d / signal: %d)\n", getpid(), signo); fprintf(stderr, "[qemu-nyx] bye! (pid: %d / signal: %d)\n", getpid(), signo);
exit(0); exit(0);
} }
void init_crash_handler(void){ void init_crash_handler(void)
{
struct sigaction action; struct sigaction action;
action.sa_flags = SA_SIGINFO; action.sa_flags = SA_SIGINFO;
action.sa_sigaction = sigsegfault_handler; action.sa_sigaction = sigsegfault_handler;
@ -67,7 +74,6 @@ void init_crash_handler(void){
} }
action.sa_sigaction = sigabrt_handler; action.sa_sigaction = sigabrt_handler;
if (sigaction(SIGABRT, &action, NULL) == -1) { if (sigaction(SIGABRT, &action, NULL) == -1) {
@ -76,7 +82,7 @@ void init_crash_handler(void){
} }
/* don't install a SIGINT handler if the nyx block cow cache layer is disabled */ /* don't install a SIGINT handler if the nyx block cow cache layer is disabled */
if(!getenv("NYX_DISABLE_BLOCK_COW")){ if (!getenv("NYX_DISABLE_BLOCK_COW")) {
action.sa_sigaction = sigint_handler; action.sa_sigaction = sigint_handler;
if (sigaction(SIGINT, &action, NULL) == -1) { if (sigaction(SIGINT, &action, NULL) == -1) {
fprintf(stderr, "SIGINT: sigaction failed"); fprintf(stderr, "SIGINT: sigaction failed");
@ -85,27 +91,28 @@ void init_crash_handler(void){
} }
} }
void hexdump_kafl(const void* data, size_t size) { void hexdump_kafl(const void *data, size_t size)
{
char ascii[17]; char ascii[17];
size_t i, j; size_t i, j;
ascii[16] = '\0'; ascii[16] = '\0';
for (i = 0; i < size; ++i) { for (i = 0; i < size; ++i) {
printf("%02X ", ((unsigned char*)data)[i]); printf("%02X ", ((unsigned char *)data)[i]);
if (((unsigned char*)data)[i] >= ' ' && ((unsigned char*)data)[i] <= '~') { if (((unsigned char *)data)[i] >= ' ' && ((unsigned char *)data)[i] <= '~') {
ascii[i % 16] = ((unsigned char*)data)[i]; ascii[i % 16] = ((unsigned char *)data)[i];
} else { } else {
ascii[i % 16] = '.'; ascii[i % 16] = '.';
} }
if ((i+1) % 8 == 0 || i+1 == size) { if ((i + 1) % 8 == 0 || i + 1 == size) {
printf(" "); printf(" ");
if ((i+1) % 16 == 0) { if ((i + 1) % 16 == 0) {
printf("| %s \n", ascii); printf("| %s \n", ascii);
} else if (i+1 == size) { } else if (i + 1 == size) {
ascii[(i+1) % 16] = '\0'; ascii[(i + 1) % 16] = '\0';
if ((i+1) % 16 <= 8) { if ((i + 1) % 16 <= 8) {
printf(" "); printf(" ");
} }
for (j = (i+1) % 16; j < 16; ++j) { for (j = (i + 1) % 16; j < 16; ++j) {
printf(" "); printf(" ");
} }
printf("| %s \n", ascii); printf("| %s \n", ascii);

View File

@ -5,9 +5,9 @@
#include <stdlib.h> #include <stdlib.h>
#include <unistd.h> #include <unistd.h>
#include "qemu-common.h"
#include "qemu/log.h"
#include "qemu/error-report.h" #include "qemu/error-report.h"
#include "qemu/log.h"
#include "qemu-common.h"
#define ENABLE_BACKTRACES #define ENABLE_BACKTRACES
@ -27,9 +27,12 @@
* qemu_log() is the standard logging enabled with -D * qemu_log() is the standard logging enabled with -D
* qemu_log_mask() is activated with additional -t nyx option * qemu_log_mask() is activated with additional -t nyx option
*/ */
//#define nyx_debug(format, ...) qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX "(%s#:%d)\t"format, __BASE_FILE__, __LINE__, ##__VA_ARGS__) // #define nyx_debug(format, ...) qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX
#define nyx_debug(format, ...) qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX format, ##__VA_ARGS__) // "(%s#:%d)\t"format, __BASE_FILE__, __LINE__, ##__VA_ARGS__)
#define nyx_debug_p(PREFIX, format, ...) qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX PREFIX format, ##__VA_ARGS__) #define nyx_debug(format, ...) \
qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX format, ##__VA_ARGS__)
#define nyx_debug_p(PREFIX, format, ...) \
qemu_log_mask(LOG_NYX, NYX_LOG_PREFIX PREFIX format, ##__VA_ARGS__)
#else #else
#define nyx_debug(...) #define nyx_debug(...)
#define nyx_debug_p(...) #define nyx_debug_p(...)
@ -43,5 +46,5 @@
#ifdef ENABLE_BACKTRACES #ifdef ENABLE_BACKTRACES
void qemu_backtrace(void); void qemu_backtrace(void);
void init_crash_handler(void); void init_crash_handler(void);
void hexdump_kafl(const void* data, size_t size); void hexdump_kafl(const void *data, size_t size);
#endif #endif

View File

@ -19,69 +19,72 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include"qemu/osdep.h" #include "qemu/osdep.h"
#include<stdint.h> #include <stdint.h>
#include<sys/mman.h> #include <sys/mman.h>
#include<sys/stat.h> #include <sys/stat.h>
#include<sys/types.h> #include <sys/types.h>
#include<immintrin.h> #include <immintrin.h>
#include"block/qapi.h" #include "block/qapi.h"
#include"exec/ram_addr.h" #include "exec/ram_addr.h"
#include"migration/global_state.h" #include "migration/global_state.h"
#include"migration/migration.h" #include "migration/migration.h"
#include"migration/qemu-file.h" #include "migration/qemu-file.h"
#include"migration/register.h" #include "migration/register.h"
#include"migration/savevm.h" #include "migration/savevm.h"
#include"migration/vmstate.h" #include "migration/vmstate.h"
#include"qemu/main-loop.h" #include "qemu/main-loop.h"
#include"qemu/rcu_queue.h" #include "qemu/rcu_queue.h"
#include"sysemu/block-backend.h" #include "sysemu/block-backend.h"
#include"sysemu/cpus.h" #include "sysemu/cpus.h"
#include"sysemu/kvm_int.h" #include "sysemu/kvm_int.h"
#include"sysemu/reset.h" #include "sysemu/reset.h"
#include"sysemu/runstate.h" #include "sysemu/runstate.h"
#include"sysemu/sysemu.h" #include "sysemu/sysemu.h"
#include"nyx/debug.h" #include "nyx/debug.h"
#include"nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include"nyx/state/snapshot_state.h" #include "nyx/state/snapshot_state.h"
#include"nyx/state/state.h" #include "nyx/state/state.h"
#include"nyx/helpers.h" #include "nyx/helpers.h"
#include"nyx/memory_access.h" #include "nyx/memory_access.h"
#include"nyx/snapshot/helper.h" #include "nyx/snapshot/block/nyx_block_snapshot.h"
#include"nyx/snapshot/memory/block_list.h" #include "nyx/snapshot/devices/nyx_device_state.h"
#include"nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/helper.h"
#include"nyx/snapshot/block/nyx_block_snapshot.h" #include "nyx/snapshot/memory/backend/nyx_debug.h"
#include"nyx/snapshot/devices/nyx_device_state.h" #include "nyx/snapshot/memory/block_list.h"
#include"nyx/snapshot/memory/backend/nyx_debug.h" #include "nyx/snapshot/memory/shadow_memory.h"
FastReloadMemoryMode mode = RELOAD_MEMORY_MODE_DEBUG; FastReloadMemoryMode mode = RELOAD_MEMORY_MODE_DEBUG;
/* basic operations */ /* basic operations */
static void fast_snapshot_init_operation(fast_reload_t* self, const char* snapshot_folder, bool pre_snapshot){ static void fast_snapshot_init_operation(fast_reload_t *self,
const char *snapshot_folder,
bool pre_snapshot)
{
assert((snapshot_folder == NULL && pre_snapshot == false) || snapshot_folder); assert((snapshot_folder == NULL && pre_snapshot == false) || snapshot_folder);
if (snapshot_folder){ if (snapshot_folder) {
self->device_state = nyx_device_state_init_from_snapshot(snapshot_folder, pre_snapshot); self->device_state =
self->shadow_memory_state = shadow_memory_init_from_snapshot(snapshot_folder, pre_snapshot); nyx_device_state_init_from_snapshot(snapshot_folder, pre_snapshot);
} self->shadow_memory_state =
else{ shadow_memory_init_from_snapshot(snapshot_folder, pre_snapshot);
} else {
self->device_state = nyx_device_state_init(); self->device_state = nyx_device_state_init();
self->shadow_memory_state = shadow_memory_init(); self->shadow_memory_state = shadow_memory_init();
} }
if(!pre_snapshot){ if (!pre_snapshot) {
switch(mode){ switch (mode) {
case RELOAD_MEMORY_MODE_DEBUG: case RELOAD_MEMORY_MODE_DEBUG:
break; break;
case RELOAD_MEMORY_MODE_DEBUG_QUIET: case RELOAD_MEMORY_MODE_DEBUG_QUIET:
@ -104,51 +107,68 @@ static void fast_snapshot_init_operation(fast_reload_t* self, const char* snapsh
nyx_fdl_user_enable(self->fdl_user_state); nyx_fdl_user_enable(self->fdl_user_state);
} }
if (snapshot_folder){ if (snapshot_folder) {
self->block_state = nyx_block_snapshot_init_from_file(snapshot_folder, pre_snapshot); self->block_state =
} nyx_block_snapshot_init_from_file(snapshot_folder, pre_snapshot);
else{ } else {
self->block_state = nyx_block_snapshot_init(); self->block_state = nyx_block_snapshot_init();
} }
memory_global_dirty_log_start(); memory_global_dirty_log_start();
if(!pre_snapshot){ if (!pre_snapshot) {
self->root_snapshot_created = true; self->root_snapshot_created = true;
} }
} }
static void fast_snapshot_restore_operation(fast_reload_t* self){ static void fast_snapshot_restore_operation(fast_reload_t *self)
{
uint32_t num_dirty_pages = 0; uint32_t num_dirty_pages = 0;
switch(mode){ switch (mode) {
case RELOAD_MEMORY_MODE_DEBUG: case RELOAD_MEMORY_MODE_DEBUG:
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state, self->blocklist, true); num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state,
self->blocklist, true);
break; break;
case RELOAD_MEMORY_MODE_DEBUG_QUIET: case RELOAD_MEMORY_MODE_DEBUG_QUIET:
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state, self->blocklist, false); num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state,
self->blocklist, false);
break; break;
case RELOAD_MEMORY_MODE_FDL: case RELOAD_MEMORY_MODE_FDL:
num_dirty_pages += nyx_snapshot_nyx_fdl_restore(self->fdl_state, self->shadow_memory_state, self->blocklist); num_dirty_pages += nyx_snapshot_nyx_fdl_restore(self->fdl_state,
self->shadow_memory_state,
self->blocklist);
break; break;
case RELOAD_MEMORY_MODE_FDL_DEBUG: case RELOAD_MEMORY_MODE_FDL_DEBUG:
num_dirty_pages += nyx_snapshot_nyx_fdl_restore(self->fdl_state, self->shadow_memory_state, self->blocklist); num_dirty_pages += nyx_snapshot_nyx_fdl_restore(self->fdl_state,
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state, self->blocklist, true); self->shadow_memory_state,
self->blocklist);
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state,
self->blocklist, true);
break; break;
case RELOAD_MEMORY_MODE_DIRTY_RING: case RELOAD_MEMORY_MODE_DIRTY_RING:
num_dirty_pages += nyx_snapshot_nyx_dirty_ring_restore(self->dirty_ring_state, self->shadow_memory_state, self->blocklist); num_dirty_pages +=
nyx_snapshot_nyx_dirty_ring_restore(self->dirty_ring_state,
self->shadow_memory_state,
self->blocklist);
break; break;
case RELOAD_MEMORY_MODE_DIRTY_RING_DEBUG: case RELOAD_MEMORY_MODE_DIRTY_RING_DEBUG:
num_dirty_pages += nyx_snapshot_nyx_dirty_ring_restore(self->dirty_ring_state, self->shadow_memory_state, self->blocklist); num_dirty_pages +=
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state, self->blocklist, true); nyx_snapshot_nyx_dirty_ring_restore(self->dirty_ring_state,
self->shadow_memory_state,
self->blocklist);
num_dirty_pages += nyx_snapshot_debug_restore(self->shadow_memory_state,
self->blocklist, true);
break; break;
} }
num_dirty_pages += nyx_snapshot_user_fdl_restore(self->fdl_user_state, self->shadow_memory_state, self->blocklist); num_dirty_pages += nyx_snapshot_user_fdl_restore(self->fdl_user_state,
self->shadow_memory_state,
self->blocklist);
GET_GLOBAL_STATE()->num_dirty_pages = num_dirty_pages; GET_GLOBAL_STATE()->num_dirty_pages = num_dirty_pages;
} }
static inline void fast_snapshot_pre_create_incremental_operation(fast_reload_t* self){ static inline void fast_snapshot_pre_create_incremental_operation(fast_reload_t *self)
{
/* flush all pending block writes */ /* flush all pending block writes */
bdrv_drain_all(); bdrv_drain_all();
memory_global_dirty_log_sync(); memory_global_dirty_log_sync();
@ -157,34 +177,49 @@ static inline void fast_snapshot_pre_create_incremental_operation(fast_reload_t*
nyx_block_snapshot_switch_incremental(self->block_state); nyx_block_snapshot_switch_incremental(self->block_state);
} }
static inline void fast_snapshot_create_incremental_operation(fast_reload_t* self){ static inline void fast_snapshot_create_incremental_operation(fast_reload_t *self)
{
shadow_memory_prepare_incremental(self->shadow_memory_state); shadow_memory_prepare_incremental(self->shadow_memory_state);
nyx_device_state_save_tsc_incremental(self->device_state); nyx_device_state_save_tsc_incremental(self->device_state);
switch(mode){ switch (mode) {
case RELOAD_MEMORY_MODE_DEBUG: case RELOAD_MEMORY_MODE_DEBUG:
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state, self->blocklist, true); nyx_snapshot_debug_save_root_pages(self->shadow_memory_state,
self->blocklist, true);
break; break;
case RELOAD_MEMORY_MODE_DEBUG_QUIET: case RELOAD_MEMORY_MODE_DEBUG_QUIET:
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state, self->blocklist, false); nyx_snapshot_debug_save_root_pages(self->shadow_memory_state,
self->blocklist, false);
break; break;
case RELOAD_MEMORY_MODE_FDL: case RELOAD_MEMORY_MODE_FDL:
nyx_snapshot_nyx_fdl_save_root_pages(self->fdl_state, self->shadow_memory_state, self->blocklist); nyx_snapshot_nyx_fdl_save_root_pages(self->fdl_state,
self->shadow_memory_state,
self->blocklist);
break; break;
case RELOAD_MEMORY_MODE_FDL_DEBUG: case RELOAD_MEMORY_MODE_FDL_DEBUG:
nyx_snapshot_nyx_fdl_save_root_pages(self->fdl_state, self->shadow_memory_state, self->blocklist); nyx_snapshot_nyx_fdl_save_root_pages(self->fdl_state,
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state, self->blocklist, true); self->shadow_memory_state,
self->blocklist);
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state,
self->blocklist, true);
break; break;
case RELOAD_MEMORY_MODE_DIRTY_RING: case RELOAD_MEMORY_MODE_DIRTY_RING:
nyx_snapshot_nyx_dirty_ring_save_root_pages(self->dirty_ring_state, self->shadow_memory_state, self->blocklist); nyx_snapshot_nyx_dirty_ring_save_root_pages(self->dirty_ring_state,
self->shadow_memory_state,
self->blocklist);
break; break;
case RELOAD_MEMORY_MODE_DIRTY_RING_DEBUG: case RELOAD_MEMORY_MODE_DIRTY_RING_DEBUG:
nyx_snapshot_nyx_dirty_ring_save_root_pages(self->dirty_ring_state, self->shadow_memory_state, self->blocklist); nyx_snapshot_nyx_dirty_ring_save_root_pages(self->dirty_ring_state,
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state, self->blocklist, true); self->shadow_memory_state,
self->blocklist);
nyx_snapshot_debug_save_root_pages(self->shadow_memory_state,
self->blocklist, true);
break; break;
} }
nyx_snapshot_nyx_fdl_user_save_root_pages(self->fdl_user_state, self->shadow_memory_state, self->blocklist); nyx_snapshot_nyx_fdl_user_save_root_pages(self->fdl_user_state,
self->shadow_memory_state,
self->blocklist);
shadow_memory_switch_snapshot(self->shadow_memory_state, true); shadow_memory_switch_snapshot(self->shadow_memory_state, true);
kvm_arch_put_registers(qemu_get_cpu(0), KVM_PUT_FULL_STATE_FAST); kvm_arch_put_registers(qemu_get_cpu(0), KVM_PUT_FULL_STATE_FAST);
@ -192,8 +227,9 @@ static inline void fast_snapshot_create_incremental_operation(fast_reload_t* sel
} }
fast_reload_t* fast_reload_new(void){ fast_reload_t *fast_reload_new(void)
fast_reload_t* self = malloc(sizeof(fast_reload_t)); {
fast_reload_t *self = malloc(sizeof(fast_reload_t));
memset(self, 0x0, sizeof(fast_reload_t)); memset(self, 0x0, sizeof(fast_reload_t));
self->root_snapshot_created = false; self->root_snapshot_created = false;
@ -204,49 +240,52 @@ fast_reload_t* fast_reload_new(void){
return self; return self;
} }
void fast_reload_set_mode(fast_reload_t* self, FastReloadMemoryMode m){ void fast_reload_set_mode(fast_reload_t *self, FastReloadMemoryMode m)
{
assert(!self->root_snapshot_created); assert(!self->root_snapshot_created);
mode = m; mode = m;
} }
FastReloadMemoryMode fast_reload_get_mode(fast_reload_t* self){ FastReloadMemoryMode fast_reload_get_mode(fast_reload_t *self)
{
return mode; return mode;
} }
void fast_reload_init(fast_reload_t* self){ void fast_reload_init(fast_reload_t *self)
{
self->blocklist = snapshot_page_blocklist_init(); self->blocklist = snapshot_page_blocklist_init();
} }
/* fix this */ /* fix this */
void fast_reload_destroy(fast_reload_t* self){ void fast_reload_destroy(fast_reload_t *self)
{
/* TODO: complete me */ /* TODO: complete me */
//close(self->vmx_fdl_fd); // close(self->vmx_fdl_fd);
//munmap(self->fdl_data, (self->guest_ram_size/0x1000)*8); // munmap(self->fdl_data, (self->guest_ram_size/0x1000)*8);
/* /*
munmap(self->ptr, self->guest_ram_size); munmap(self->ptr, self->guest_ram_size);
free(self->black_list_pages); free(self->black_list_pages);
free(self); free(self);
*/ */
} }
inline static void unlock_snapshot(const char* folder){ inline static void unlock_snapshot(const char *folder)
char* info_file; {
char* lock_file; char *info_file;
char *lock_file;
/* info file */ /* info file */
assert(asprintf(&info_file, "%s/INFO.txt", folder) != -1); assert(asprintf(&info_file, "%s/INFO.txt", folder) != -1);
FILE* f_info = fopen(info_file, "w+b"); FILE *f_info = fopen(info_file, "w+b");
if(GET_GLOBAL_STATE()->fast_reload_pre_image){ if (GET_GLOBAL_STATE()->fast_reload_pre_image) {
const char* msg = "THIS IS A NYX PRE IMAGE SNAPSHOT FOLDER!\n"; const char *msg = "THIS IS A NYX PRE IMAGE SNAPSHOT FOLDER!\n";
fwrite(msg, strlen(msg), 1, f_info); fwrite(msg, strlen(msg), 1, f_info);
} } else {
else{ const char *msg = "THIS IS A NYX SNAPSHOT FOLDER!\n";
const char* msg = "THIS IS A NYX SNAPSHOT FOLDER!\n";
fwrite(msg, strlen(msg), 1, f_info); fwrite(msg, strlen(msg), 1, f_info);
} }
fclose(f_info); fclose(f_info);
@ -258,23 +297,26 @@ inline static void unlock_snapshot(const char* folder){
free(lock_file); free(lock_file);
} }
inline static void wait_for_snapshot(const char* folder){ inline static void wait_for_snapshot(const char *folder)
char* lock_file; {
char *lock_file;
assert(asprintf(&lock_file, "%s/ready.lock", folder) != -1); assert(asprintf(&lock_file, "%s/ready.lock", folder) != -1);
while( access(lock_file, F_OK ) == -1 ) { while (access(lock_file, F_OK) == -1) {
sleep(1); sleep(1);
} }
free(lock_file); free(lock_file);
} }
void fast_reload_serialize_to_file(fast_reload_t* self, const char* folder, bool is_pre_snapshot){ void fast_reload_serialize_to_file(fast_reload_t *self,
const char *folder,
bool is_pre_snapshot)
{
nyx_trace(); nyx_trace();
/* sanity check */ /* sanity check */
if(!folder_exits(folder)){ if (!folder_exits(folder)) {
nyx_debug_p(RELOAD_PREFIX,"Folder %s does not exist...failed!", folder); nyx_debug_p(RELOAD_PREFIX, "Folder %s does not exist...failed!", folder);
assert(0); assert(0);
} }
@ -295,14 +337,18 @@ void fast_reload_serialize_to_file(fast_reload_t* self, const char* folder, bool
} }
static void fast_reload_create_from_snapshot(fast_reload_t *self,
static void fast_reload_create_from_snapshot(fast_reload_t* self, const char* folder, bool lock_iothread, bool pre_snapshot){ const char *folder,
bool lock_iothread,
bool pre_snapshot)
{
nyx_trace(); nyx_trace();
assert(self != NULL); assert(self != NULL);
wait_for_snapshot(folder); wait_for_snapshot(folder);
nyx_debug_p(RELOAD_PREFIX,"=> CREATING FAST RELOAD SNAPSHOT FROM DUMP (located in: %s)", folder); nyx_debug_p(RELOAD_PREFIX,
"=> CREATING FAST RELOAD SNAPSHOT FROM DUMP (located in: %s)", folder);
rcu_read_lock(); rcu_read_lock();
@ -311,7 +357,7 @@ static void fast_reload_create_from_snapshot(fast_reload_t* self, const char* fo
cpu_synchronize_all_pre_loadvm(); cpu_synchronize_all_pre_loadvm();
if(!pre_snapshot){ if (!pre_snapshot) {
memory_global_dirty_log_stop(); memory_global_dirty_log_stop();
memory_global_dirty_log_sync(); memory_global_dirty_log_sync();
} }
@ -320,30 +366,36 @@ static void fast_reload_create_from_snapshot(fast_reload_t* self, const char* fo
rcu_read_unlock(); rcu_read_unlock();
if(!pre_snapshot){ if (!pre_snapshot) {
deserialize_state(folder); deserialize_state(folder);
} }
cpu_synchronize_all_post_init(); cpu_synchronize_all_post_init();
qemu_get_cpu(0)->vcpu_dirty = true; qemu_get_cpu(0)->vcpu_dirty = true;
kvm_arch_put_registers(qemu_get_cpu(0), KVM_PUT_FULL_STATE); kvm_arch_put_registers(qemu_get_cpu(0), KVM_PUT_FULL_STATE);
if(!pre_snapshot){ if (!pre_snapshot) {
nyx_device_state_save_tsc(self->device_state); nyx_device_state_save_tsc(self->device_state);
} }
} }
void fast_reload_create_from_file(fast_reload_t* self, const char* folder, bool lock_iothread){ void fast_reload_create_from_file(fast_reload_t *self,
const char *folder,
bool lock_iothread)
{
nyx_trace(); nyx_trace();
fast_reload_create_from_snapshot(self, folder, lock_iothread, false); fast_reload_create_from_snapshot(self, folder, lock_iothread, false);
} }
void fast_reload_create_from_file_pre_image(fast_reload_t* self, const char* folder, bool lock_iothread){ void fast_reload_create_from_file_pre_image(fast_reload_t *self,
const char *folder,
bool lock_iothread)
{
nyx_trace(); nyx_trace();
fast_reload_create_from_snapshot(self, folder, lock_iothread, true); fast_reload_create_from_snapshot(self, folder, lock_iothread, true);
} }
void fast_reload_create_in_memory(fast_reload_t* self){ void fast_reload_create_in_memory(fast_reload_t *self)
{
nyx_trace(); nyx_trace();
assert(self != NULL); assert(self != NULL);
@ -363,7 +415,8 @@ void fast_reload_create_in_memory(fast_reload_t* self){
cpu_synchronize_all_post_init(); cpu_synchronize_all_post_init();
} }
void fast_reload_restore(fast_reload_t* self){ void fast_reload_restore(fast_reload_t *self)
{
assert(self != NULL); assert(self != NULL);
self->dirty_pages = 0; self->dirty_pages = 0;
@ -387,13 +440,15 @@ void fast_reload_restore(fast_reload_t* self){
} }
bool read_snapshot_memory(fast_reload_t* self, uint64_t address, void* ptr, size_t size){ bool read_snapshot_memory(fast_reload_t *self, uint64_t address, void *ptr, size_t size)
return shadow_memory_read_physical_memory(self->shadow_memory_state, address, ptr, size); {
return shadow_memory_read_physical_memory(self->shadow_memory_state, address,
ptr, size);
} }
/* fix this */ /* fix this */
void* fast_reload_get_physmem_shadow_ptr(fast_reload_t* self, uint64_t physaddr){ void *fast_reload_get_physmem_shadow_ptr(fast_reload_t *self, uint64_t physaddr)
{
abort(); /* TODO: fix this function first -> pc_piix memory split issue */ abort(); /* TODO: fix this function first -> pc_piix memory split issue */
/* /*
@ -401,8 +456,9 @@ void* fast_reload_get_physmem_shadow_ptr(fast_reload_t* self, uint64_t physaddr)
assert(!(physaddr&0xFFF)); // physaddr must be 4kb align ! assert(!(physaddr&0xFFF)); // physaddr must be 4kb align !
if (self->shadow_memory_regions){ if (self->shadow_memory_regions){
for(uint64_t j = 0; j < self->shadow_memory_regions; j++){ for(uint64_t j = 0; j < self->shadow_memory_regions; j++){
if(physaddr >= self->ram_block_array[j]->offset && physaddr < (self->ram_block_array[j]->offset+self->ram_block_array[j]->used_length)){ if(physaddr >= self->ram_block_array[j]->offset && physaddr <
return self->shadow_memory[j]+(physaddr-self->ram_block_array[j]->offset); (self->ram_block_array[j]->offset+self->ram_block_array[j]->used_length)){ return
self->shadow_memory[j]+(physaddr-self->ram_block_array[j]->offset);
} }
} }
} }
@ -410,26 +466,28 @@ void* fast_reload_get_physmem_shadow_ptr(fast_reload_t* self, uint64_t physaddr)
return NULL; // not found ... sorry :( return NULL; // not found ... sorry :(
} }
void fast_reload_blacklist_page(fast_reload_t* self, uint64_t physaddr){ void fast_reload_blacklist_page(fast_reload_t *self, uint64_t physaddr)
{
assert(self->blocklist); assert(self->blocklist);
snapshot_page_blocklist_add(self->blocklist, physaddr); snapshot_page_blocklist_add(self->blocklist, physaddr);
} }
bool fast_reload_snapshot_exists(fast_reload_t* self){ bool fast_reload_snapshot_exists(fast_reload_t *self)
if(!self){ {
if (!self) {
return false; return false;
} }
return true; return true;
} }
void fast_reload_create_tmp_snapshot(fast_reload_t* self){ void fast_reload_create_tmp_snapshot(fast_reload_t *self)
{
assert(self); assert(self);
self->dirty_pages = 0; self->dirty_pages = 0;
fast_snapshot_pre_create_incremental_operation(self); fast_snapshot_pre_create_incremental_operation(self);
if(!self->bitmap_copy){ if (!self->bitmap_copy) {
self->bitmap_copy = new_coverage_bitmaps(); self->bitmap_copy = new_coverage_bitmaps();
} }
coverage_bitmap_copy_to_buffer(self->bitmap_copy); coverage_bitmap_copy_to_buffer(self->bitmap_copy);
@ -438,7 +496,8 @@ void fast_reload_create_tmp_snapshot(fast_reload_t* self){
self->incremental_snapshot_enabled = true; self->incremental_snapshot_enabled = true;
} }
void fast_reload_discard_tmp_snapshot(fast_reload_t* self){ void fast_reload_discard_tmp_snapshot(fast_reload_t *self)
{
assert(self && self->incremental_snapshot_enabled); assert(self && self->incremental_snapshot_enabled);
self->dirty_pages = 0; self->dirty_pages = 0;
@ -459,45 +518,53 @@ void fast_reload_discard_tmp_snapshot(fast_reload_t* self){
self->incremental_snapshot_enabled = false; self->incremental_snapshot_enabled = false;
} }
bool fast_reload_root_created(fast_reload_t* self){ bool fast_reload_root_created(fast_reload_t *self)
{
return self->root_snapshot_created; return self->root_snapshot_created;
} }
bool fast_reload_tmp_created(fast_reload_t* self){ bool fast_reload_tmp_created(fast_reload_t *self)
{
return self->incremental_snapshot_enabled; return self->incremental_snapshot_enabled;
} }
uint32_t get_dirty_page_num(fast_reload_t* self){ uint32_t get_dirty_page_num(fast_reload_t *self)
if(self){ {
if (self) {
return self->dirty_pages; return self->dirty_pages;
} } else {
else{
return 0; return 0;
} }
} }
bool fast_reload_set_bitmap(fast_reload_t* self){ bool fast_reload_set_bitmap(fast_reload_t *self)
if(self->incremental_snapshot_enabled){ {
if (self->incremental_snapshot_enabled) {
coverage_bitmap_copy_from_buffer(self->bitmap_copy); coverage_bitmap_copy_from_buffer(self->bitmap_copy);
return true; return true;
} }
return false; return false;
} }
void fast_reload_qemu_user_fdl_set_dirty(fast_reload_t* self, MemoryRegion *mr, uint64_t addr, uint64_t length){ void fast_reload_qemu_user_fdl_set_dirty(fast_reload_t *self,
MemoryRegion *mr,
uint64_t addr,
uint64_t length)
{
/* works only with PC.RAM's memory region */ /* works only with PC.RAM's memory region */
assert(mr->alias_offset == 0); assert(mr->alias_offset == 0);
nyx_fdl_user_set(self->fdl_user_state, self->shadow_memory_state, self->fdl_state, addr, length); nyx_fdl_user_set(self->fdl_user_state, self->shadow_memory_state,
self->fdl_state, addr, length);
} }
void fast_reload_handle_dirty_ring_full(fast_reload_t* self){ void fast_reload_handle_dirty_ring_full(fast_reload_t *self)
if(self->dirty_ring_state){ {
nyx_snapshot_nyx_dirty_ring_flush_and_collect(self->dirty_ring_state, self->shadow_memory_state, self->blocklist); if (self->dirty_ring_state) {
} nyx_snapshot_nyx_dirty_ring_flush_and_collect(self->dirty_ring_state,
else{ self->shadow_memory_state,
self->blocklist);
} else {
nyx_snapshot_nyx_dirty_ring_flush(); nyx_snapshot_nyx_dirty_ring_flush();
} }
} }

View File

@ -21,19 +21,19 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#pragma once #pragma once
#include"monitor/monitor.h" #include "monitor/monitor.h"
#include"sysemu/runstate.h" #include "sysemu/runstate.h"
#include"qemu-common.h" #include "qemu-common.h"
#include"nyx/snapshot/block/nyx_block_snapshot.h" #include "nyx/snapshot/block/nyx_block_snapshot.h"
#include"nyx/snapshot/devices/nyx_device_state.h" #include "nyx/snapshot/devices/nyx_device_state.h"
#include"nyx/snapshot/memory/backend/nyx_dirty_ring.h" #include "nyx/snapshot/memory/backend/nyx_dirty_ring.h"
#include"nyx/snapshot/memory/backend/nyx_fdl.h" #include "nyx/snapshot/memory/backend/nyx_fdl.h"
#include"nyx/snapshot/memory/block_list.h" #include "nyx/snapshot/memory/block_list.h"
#include"nyx/snapshot/memory/nyx_fdl_user.h" #include "nyx/snapshot/memory/nyx_fdl_user.h"
#include"nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/memory/shadow_memory.h"
#include"nyx/helpers.h" #include "nyx/helpers.h"
typedef enum FastReloadMemoryMode { typedef enum FastReloadMemoryMode {
@ -46,43 +46,40 @@ typedef enum FastReloadMemoryMode {
} FastReloadMemoryMode; } FastReloadMemoryMode;
typedef struct fast_reload_dump_head_s {
typedef struct fast_reload_dump_head_s{
uint32_t shadow_memory_regions; uint32_t shadow_memory_regions;
uint32_t ram_region_index; uint32_t ram_region_index;
} fast_reload_dump_head_t; } fast_reload_dump_head_t;
typedef struct fast_reload_s{ typedef struct fast_reload_s {
FastReloadMemoryMode mode; FastReloadMemoryMode mode;
/* memory snapshot */ /* memory snapshot */
shadow_memory_t* shadow_memory_state; shadow_memory_t *shadow_memory_state;
/* state of page frame blocklist */ /* state of page frame blocklist */
snapshot_page_blocklist_t* blocklist; snapshot_page_blocklist_t *blocklist;
/* state of FDL */ /* state of FDL */
nyx_fdl_t* fdl_state; nyx_fdl_t *fdl_state;
/* dirty ring state */ /* dirty ring state */
nyx_dirty_ring_t* dirty_ring_state; nyx_dirty_ring_t *dirty_ring_state;
/* state of user-level FDL */ /* state of user-level FDL */
nyx_fdl_user_t* fdl_user_state; nyx_fdl_user_t *fdl_user_state;
/* nyx's serialized device state */ /* nyx's serialized device state */
nyx_device_state_t* device_state; nyx_device_state_t *device_state;
nyx_block_t* block_state; nyx_block_t *block_state;
bool root_snapshot_created; bool root_snapshot_created;
bool incremental_snapshot_enabled; bool incremental_snapshot_enabled;
/* copy of the fuzzing bitmap & ijon state buffer */ /* copy of the fuzzing bitmap & ijon state buffer */
nyx_coverage_bitmap_copy_t* bitmap_copy; nyx_coverage_bitmap_copy_t *bitmap_copy;
uint32_t dirty_pages; uint32_t dirty_pages;
@ -90,46 +87,57 @@ typedef struct fast_reload_s{
} fast_reload_t; } fast_reload_t;
fast_reload_t* fast_reload_new(void); fast_reload_t *fast_reload_new(void);
/* TODO: get rid of this */ /* TODO: get rid of this */
void fast_reload_create_to_file(fast_reload_t* self, const char* folder, bool lock_iothread); void fast_reload_create_to_file(fast_reload_t *self,
void fast_reload_create_from_file(fast_reload_t* self, const char* folder, bool lock_iothread); const char *folder,
void fast_reload_create_from_file_pre_image(fast_reload_t* self, const char* folder, bool lock_iothread); bool lock_iothread);
void fast_reload_create_from_file(fast_reload_t *self,
const char *folder,
bool lock_iothread);
void fast_reload_create_from_file_pre_image(fast_reload_t *self,
const char *folder,
bool lock_iothread);
/* keep this */ /* keep this */
void fast_reload_create_in_memory(fast_reload_t* self); void fast_reload_create_in_memory(fast_reload_t *self);
void fast_reload_serialize_to_file(fast_reload_t* self, const char* folder, bool is_pre_snapshot); void fast_reload_serialize_to_file(fast_reload_t *self,
const char *folder,
bool is_pre_snapshot);
void fast_reload_restore(fast_reload_t* self); void fast_reload_restore(fast_reload_t *self);
void fast_reload_blacklist_page(fast_reload_t* self, uint64_t physaddr); void fast_reload_blacklist_page(fast_reload_t *self, uint64_t physaddr);
void* fast_reload_get_physmem_shadow_ptr(fast_reload_t* self, uint64_t physaddr); void *fast_reload_get_physmem_shadow_ptr(fast_reload_t *self, uint64_t physaddr);
bool fast_reload_snapshot_exists(fast_reload_t* self); bool fast_reload_snapshot_exists(fast_reload_t *self);
bool read_snapshot_memory(fast_reload_t* self, uint64_t address, void* ptr, size_t size); bool read_snapshot_memory(fast_reload_t *self, uint64_t address, void *ptr, size_t size);
void fast_reload_destroy(fast_reload_t* self); void fast_reload_destroy(fast_reload_t *self);
void fast_reload_qemu_user_fdl_set_dirty(fast_reload_t* self, MemoryRegion *mr, uint64_t addr, uint64_t length); void fast_reload_qemu_user_fdl_set_dirty(fast_reload_t *self,
MemoryRegion *mr,
uint64_t addr,
uint64_t length);
void fast_reload_create_tmp_snapshot(fast_reload_t* self); void fast_reload_create_tmp_snapshot(fast_reload_t *self);
void fast_reload_discard_tmp_snapshot(fast_reload_t* self); void fast_reload_discard_tmp_snapshot(fast_reload_t *self);
bool fast_reload_root_created(fast_reload_t* self); bool fast_reload_root_created(fast_reload_t *self);
bool fast_reload_tmp_created(fast_reload_t* self); bool fast_reload_tmp_created(fast_reload_t *self);
bool fast_reload_set_bitmap(fast_reload_t* self); bool fast_reload_set_bitmap(fast_reload_t *self);
uint32_t get_dirty_page_num(fast_reload_t* self); uint32_t get_dirty_page_num(fast_reload_t *self);
void fast_reload_init(fast_reload_t* self); void fast_reload_init(fast_reload_t *self);
void fast_reload_set_mode(fast_reload_t* self, FastReloadMemoryMode m); void fast_reload_set_mode(fast_reload_t *self, FastReloadMemoryMode m);
void fast_reload_handle_dirty_ring_full(fast_reload_t* self); void fast_reload_handle_dirty_ring_full(fast_reload_t *self);
FastReloadMemoryMode fast_reload_get_mode(fast_reload_t* self); FastReloadMemoryMode fast_reload_get_mode(fast_reload_t *self);

View File

@ -1,30 +1,31 @@
#include"qemu/osdep.h" #include "qemu/osdep.h"
#include<assert.h> #include <assert.h>
#include<stdint.h> #include <stdint.h>
#include<stdio.h> #include <stdio.h>
#include"exec/memory.h" #include "exec/memory.h"
#include"qapi/error.h" #include "qapi/error.h"
#include"qapi/qapi-types-run-state.h" #include "qapi/qapi-types-run-state.h"
#include"qemu/main-loop.h" #include "qemu/main-loop.h"
#include"qemu-common.h" #include "qemu-common.h"
#include"sysemu/kvm.h" #include "sysemu/kvm.h"
#include"sysemu/kvm_int.h" #include "sysemu/kvm_int.h"
#include"sysemu/runstate.h" #include "sysemu/runstate.h"
#include"fast_vm_reload_sync.h" #include "fast_vm_reload_sync.h"
#include"nyx/debug.h" #include "nyx/debug.h"
#include"nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include"nyx/kvm_nested.h" #include "nyx/kvm_nested.h"
#include"nyx/state/state.h" #include "nyx/state/state.h"
extern int save_snapshot(const char *name, Error **errp); extern int save_snapshot(const char *name, Error **errp);
extern int load_snapshot(const char *name, Error **errp); extern int load_snapshot(const char *name, Error **errp);
static void adjust_rip(CPUX86State *env, fast_reload_t* snapshot){ static void adjust_rip(CPUX86State *env, fast_reload_t *snapshot)
switch(fast_reload_get_mode(snapshot)){ {
switch (fast_reload_get_mode(snapshot)) {
case RELOAD_MEMORY_MODE_DEBUG: case RELOAD_MEMORY_MODE_DEBUG:
case RELOAD_MEMORY_MODE_DEBUG_QUIET: case RELOAD_MEMORY_MODE_DEBUG_QUIET:
env->eip -= 1; /* out */ env->eip -= 1; /* out */
@ -40,8 +41,9 @@ static void adjust_rip(CPUX86State *env, fast_reload_t* snapshot){
} }
} }
fast_vm_reload_sync_t* init_fast_vm_reload_sync(void){ fast_vm_reload_sync_t *init_fast_vm_reload_sync(void)
fast_vm_reload_sync_t* self = malloc(sizeof(fast_vm_reload_sync_t)); {
fast_vm_reload_sync_t *self = malloc(sizeof(fast_vm_reload_sync_t));
memset(self, 0, sizeof(fast_vm_reload_sync_t)); memset(self, 0, sizeof(fast_vm_reload_sync_t));
self->request_exists = false; self->request_exists = false;
@ -55,11 +57,11 @@ fast_vm_reload_sync_t* init_fast_vm_reload_sync(void){
return self; return self;
} }
bool fast_snapshot_exists(fast_vm_reload_sync_t* self, FastReloadRequest type){ bool fast_snapshot_exists(fast_vm_reload_sync_t *self, FastReloadRequest type)
{
assert(self->mode != RELOAD_MODE_DEBUG); assert(self->mode != RELOAD_MODE_DEBUG);
switch(type){ switch (type) {
case REQUEST_PRE_EXISTS: case REQUEST_PRE_EXISTS:
abort(); abort();
case REQUEST_ROOT_EXISTS: case REQUEST_ROOT_EXISTS:
@ -72,11 +74,12 @@ bool fast_snapshot_exists(fast_vm_reload_sync_t* self, FastReloadRequest type){
} }
static inline void perform_task_debug_mode(fast_vm_reload_sync_t *self,
FastReloadRequest request)
{
struct Error *errp = NULL;
static inline void perform_task_debug_mode(fast_vm_reload_sync_t* self, FastReloadRequest request){ switch (request) {
struct Error* errp = NULL;
switch(request){
case REQUEST_SAVE_SNAPSHOT_PRE_FIX_RIP: case REQUEST_SAVE_SNAPSHOT_PRE_FIX_RIP:
abort(); abort();
case REQUEST_SAVE_SNAPSHOT_PRE: case REQUEST_SAVE_SNAPSHOT_PRE:
@ -120,39 +123,42 @@ static inline void perform_task_debug_mode(fast_vm_reload_sync_t* self, FastRelo
vm_start(); vm_start();
} }
static inline void create_root_snapshot(void){ static inline void create_root_snapshot(void)
if (GET_GLOBAL_STATE()->fast_reload_enabled){ {
if (GET_GLOBAL_STATE()->fast_reload_enabled) {
nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_enabled: TRUE\n"); nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_enabled: TRUE\n");
if (GET_GLOBAL_STATE()->fast_reload_mode){ if (GET_GLOBAL_STATE()->fast_reload_mode) {
nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_mode: TRUE\n"); nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_mode: TRUE\n");
/* we've loaded an external snapshot folder - so do nothing and don't create any new snapshot files */ /* we've loaded an external snapshot folder - so do nothing and don't create any new snapshot files */
} } else {
else{
nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_mode: FALSE\n"); nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_mode: FALSE\n");
/* store the current state as a snapshot folder */ /* store the current state as a snapshot folder */
fast_reload_create_in_memory(get_fast_reload_snapshot()); fast_reload_create_in_memory(get_fast_reload_snapshot());
fast_reload_serialize_to_file(get_fast_reload_snapshot(), GET_GLOBAL_STATE()->fast_reload_path, false); fast_reload_serialize_to_file(get_fast_reload_snapshot(),
GET_GLOBAL_STATE()->fast_reload_path, false);
} }
} } else {
else{
nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_enabled: FALSE\n"); nyx_debug("===> GET_GLOBAL_STATE()->fast_reload_enabled: FALSE\n");
/* so we haven't set a path for our snapshot files - just store everything in memory */ /* so we haven't set a path for our snapshot files - just store everything in memory */
fast_reload_create_in_memory(get_fast_reload_snapshot()); fast_reload_create_in_memory(get_fast_reload_snapshot());
} }
} }
static inline void perform_task_no_block_mode(fast_vm_reload_sync_t* self, FastReloadRequest request){ static inline void perform_task_no_block_mode(fast_vm_reload_sync_t *self,
CPUState* cpu = qemu_get_cpu(0); FastReloadRequest request)
{
CPUState *cpu = qemu_get_cpu(0);
X86CPU *x86_cpu = X86_CPU(cpu); X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env; CPUX86State *env = &x86_cpu->env;
qemu_mutex_lock_iothread(); qemu_mutex_lock_iothread();
switch(request){ switch (request) {
case REQUEST_SAVE_SNAPSHOT_PRE: case REQUEST_SAVE_SNAPSHOT_PRE:
vm_stop(RUN_STATE_SAVE_VM); vm_stop(RUN_STATE_SAVE_VM);
fast_reload_create_in_memory(get_fast_reload_snapshot()); fast_reload_create_in_memory(get_fast_reload_snapshot());
fast_reload_serialize_to_file(get_fast_reload_snapshot(), GET_GLOBAL_STATE()->fast_reload_pre_path, true); fast_reload_serialize_to_file(get_fast_reload_snapshot(),
GET_GLOBAL_STATE()->fast_reload_pre_path, true);
qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN); qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
qemu_mutex_unlock_iothread(); qemu_mutex_unlock_iothread();
@ -203,13 +209,16 @@ static inline void perform_task_no_block_mode(fast_vm_reload_sync_t* self, FastR
qemu_mutex_unlock_iothread(); qemu_mutex_unlock_iothread();
} }
static inline void perform_task_block_mode(fast_vm_reload_sync_t* self, FastReloadRequest request){ static inline void perform_task_block_mode(fast_vm_reload_sync_t *self,
switch(request){ FastReloadRequest request)
{
switch (request) {
case REQUEST_SAVE_SNAPSHOT_PRE_FIX_RIP: case REQUEST_SAVE_SNAPSHOT_PRE_FIX_RIP:
case REQUEST_SAVE_SNAPSHOT_PRE: case REQUEST_SAVE_SNAPSHOT_PRE:
vm_stop(RUN_STATE_SAVE_VM); vm_stop(RUN_STATE_SAVE_VM);
fast_reload_create_in_memory(get_fast_reload_snapshot()); fast_reload_create_in_memory(get_fast_reload_snapshot());
fast_reload_serialize_to_file(get_fast_reload_snapshot(), GET_GLOBAL_STATE()->fast_reload_pre_path, true); fast_reload_serialize_to_file(get_fast_reload_snapshot(),
GET_GLOBAL_STATE()->fast_reload_pre_path, true);
qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN); qemu_system_shutdown_request(SHUTDOWN_CAUSE_GUEST_SHUTDOWN);
return; /* return here to skip the vm_start call */ return; /* return here to skip the vm_start call */
case REQUEST_SAVE_SNAPSHOT_ROOT_FIX_RIP: case REQUEST_SAVE_SNAPSHOT_ROOT_FIX_RIP:
@ -237,8 +246,9 @@ static inline void perform_task_block_mode(fast_vm_reload_sync_t* self, FastRelo
vm_start(); vm_start();
} }
static inline void perform_task(fast_vm_reload_sync_t* self, FastReloadRequest request){ static inline void perform_task(fast_vm_reload_sync_t *self, FastReloadRequest request)
switch(self->mode){ {
switch (self->mode) {
case RELOAD_MODE_DEBUG: case RELOAD_MODE_DEBUG:
abort(); abort();
perform_task_debug_mode(self, request); perform_task_debug_mode(self, request);
@ -252,45 +262,47 @@ static inline void perform_task(fast_vm_reload_sync_t* self, FastReloadRequest r
} }
} }
void request_fast_vm_reload(fast_vm_reload_sync_t* self, FastReloadRequest request){ void request_fast_vm_reload(fast_vm_reload_sync_t *self, FastReloadRequest request)
{
assert(!self->request_exists); assert(!self->request_exists);
assert(self->current_request == REQUEST_VOID); assert(self->current_request == REQUEST_VOID);
if(self->mode == RELOAD_MODE_NO_BLOCK){ if (self->mode == RELOAD_MODE_NO_BLOCK) {
CPUState* cpu = qemu_get_cpu(0); CPUState *cpu = qemu_get_cpu(0);
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
//perform_task(self, request); // perform_task(self, request);
perform_task_no_block_mode(self, request); perform_task_no_block_mode(self, request);
} } else {
else{
self->current_request = request; self->current_request = request;
self->request_exists = true; self->request_exists = true;
self->request_exists_pre = true; self->request_exists_pre = true;
} }
} }
bool reload_request_exists(fast_vm_reload_sync_t* self){ bool reload_request_exists(fast_vm_reload_sync_t *self)
{
return self->request_exists_pre; return self->request_exists_pre;
} }
void reload_request_discard_tmp(fast_vm_reload_sync_t* self){ void reload_request_discard_tmp(fast_vm_reload_sync_t *self)
{
fast_reload_discard_tmp_snapshot(get_fast_reload_snapshot()); fast_reload_discard_tmp_snapshot(get_fast_reload_snapshot());
} }
bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t* self){ bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t *self)
{
/* TODO: always returns false or abort() ? */ /* TODO: always returns false or abort() ? */
if(self->request_exists_pre){ if (self->request_exists_pre) {
self->request_exists_pre = false; self->request_exists_pre = false;
abort(); abort();
CPUState* cpu = qemu_get_cpu(0); CPUState *cpu = qemu_get_cpu(0);
X86CPU *x86_cpu = X86_CPU(cpu); X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env; CPUX86State *env = &x86_cpu->env;
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
switch(self->current_request){ switch (self->current_request) {
case REQUEST_VOID: case REQUEST_VOID:
fprintf(stderr, "%s: REQUEST_VOID requested!\n", __func__); fprintf(stderr, "%s: REQUEST_VOID requested!\n", __func__);
abort(); abort();
@ -323,7 +335,8 @@ bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t* self){
break; break;
default: default:
fprintf(stderr, "%s: Unkown request: %d\n", __func__, self->current_request); fprintf(stderr, "%s: Unkown request: %d\n", __func__,
self->current_request);
abort(); abort();
} }
return true; return true;
@ -331,8 +344,9 @@ bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t* self){
return false; return false;
} }
bool check_if_relood_request_exists_post(fast_vm_reload_sync_t* self){ bool check_if_relood_request_exists_post(fast_vm_reload_sync_t *self)
if(self->request_exists){ {
if (self->request_exists) {
FastReloadRequest request = self->current_request; FastReloadRequest request = self->current_request;
self->request_exists = false; self->request_exists = false;

View File

@ -29,7 +29,7 @@ typedef enum FastReloadRequest {
REQUEST_ROOT_EXISTS, REQUEST_ROOT_EXISTS,
REQUEST_TMP_EXISTS, REQUEST_TMP_EXISTS,
//REQUEST_DISCARD_SNAPSHOT_TMP, // REQUEST_DISCARD_SNAPSHOT_TMP,
} FastReloadRequest; } FastReloadRequest;
typedef enum FastReloadMode { typedef enum FastReloadMode {
@ -39,9 +39,7 @@ typedef enum FastReloadMode {
} FastReloadMode; } FastReloadMode;
typedef struct fast_vm_reload_sync_s {
typedef struct fast_vm_reload_sync_s{
bool request_exists; bool request_exists;
bool request_exists_pre; bool request_exists_pre;
bool debug_mode; bool debug_mode;
@ -50,12 +48,12 @@ typedef struct fast_vm_reload_sync_s{
} fast_vm_reload_sync_t; } fast_vm_reload_sync_t;
fast_vm_reload_sync_t* init_fast_vm_reload_sync(void); fast_vm_reload_sync_t *init_fast_vm_reload_sync(void);
void request_fast_vm_reload(fast_vm_reload_sync_t* self, FastReloadRequest request); void request_fast_vm_reload(fast_vm_reload_sync_t *self, FastReloadRequest request);
bool reload_request_exists(fast_vm_reload_sync_t* self); bool reload_request_exists(fast_vm_reload_sync_t *self);
bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t* self); bool check_if_relood_request_exists_pre(fast_vm_reload_sync_t *self);
bool check_if_relood_request_exists_post(fast_vm_reload_sync_t* self); bool check_if_relood_request_exists_post(fast_vm_reload_sync_t *self);
bool fast_snapshot_exists(fast_vm_reload_sync_t* self, FastReloadRequest type); bool fast_snapshot_exists(fast_vm_reload_sync_t *self, FastReloadRequest type);
void reload_request_discard_tmp(fast_vm_reload_sync_t* self); void reload_request_discard_tmp(fast_vm_reload_sync_t *self);

View File

@ -1,13 +1,13 @@
#include <assert.h> #include <assert.h>
#include <string.h> #include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include "nyx/redqueen.h" #include "nyx/redqueen.h"
//#include "debug.h" // #include "debug.h"
#include "nyx/file_helper.h" #include "nyx/file_helper.h"
@ -15,15 +15,16 @@
* Private Helper Functions Declarations * Private Helper Functions Declarations
*/ */
size_t _count_lines_in_file(FILE* fp); size_t _count_lines_in_file(FILE *fp);
void _parse_addresses_in_file(FILE* fp, size_t num_addrs, uint64_t* addrs); void _parse_addresses_in_file(FILE *fp, size_t num_addrs, uint64_t *addrs);
/* /*
* Public Functions * Public Functions
*/ */
void write_debug_result(char* buf){ void write_debug_result(char *buf)
{
int unused __attribute__((unused)); int unused __attribute__((unused));
int fd = open("/tmp/qemu_debug.txt", O_WRONLY | O_CREAT | O_APPEND, S_IRWXU); int fd = open("/tmp/qemu_debug.txt", O_WRONLY | O_CREAT | O_APPEND, S_IRWXU);
assert(fd > 0); assert(fd > 0);
@ -31,25 +32,26 @@ void write_debug_result(char* buf){
close(fd); close(fd);
} }
void parse_address_file(char* path, size_t* num_addrs, uint64_t** addrs){ void parse_address_file(char *path, size_t *num_addrs, uint64_t **addrs)
FILE* fp = fopen(path,"r"); {
if(!fp){ FILE *fp = fopen(path, "r");
if (!fp) {
*num_addrs = 0; *num_addrs = 0;
*addrs = NULL; *addrs = NULL;
return; return;
} }
*num_addrs = _count_lines_in_file(fp); *num_addrs = _count_lines_in_file(fp);
if(*num_addrs == 0){ if (*num_addrs == 0) {
*addrs = NULL; *addrs = NULL;
goto exit_function; goto exit_function;
} }
assert(*num_addrs < 0xffff); assert(*num_addrs < 0xffff);
*addrs = malloc(sizeof(uint64_t)*(*num_addrs)); *addrs = malloc(sizeof(uint64_t) * (*num_addrs));
_parse_addresses_in_file(fp, *num_addrs, *addrs); _parse_addresses_in_file(fp, *num_addrs, *addrs);
exit_function: exit_function:
fclose(fp); fclose(fp);
} }
@ -57,37 +59,45 @@ void parse_address_file(char* path, size_t* num_addrs, uint64_t** addrs){
int re_fd = 0; int re_fd = 0;
int se_fd = 0; int se_fd = 0;
void write_re_result(char* buf){ void write_re_result(char *buf)
{
int unused __attribute__((unused)); int unused __attribute__((unused));
if (!re_fd) if (!re_fd)
re_fd = open(redqueen_workdir.redqueen_results, O_WRONLY | O_CREAT | O_APPEND, S_IRWXU); re_fd = open(redqueen_workdir.redqueen_results,
O_WRONLY | O_CREAT | O_APPEND, S_IRWXU);
unused = write(re_fd, buf, strlen(buf)); unused = write(re_fd, buf, strlen(buf));
} }
void fsync_redqueen_files(void){ void fsync_redqueen_files(void)
if (!se_fd){ {
if (!se_fd) {
fsync(se_fd); fsync(se_fd);
} }
if (!re_fd){ if (!re_fd) {
fsync(re_fd); fsync(re_fd);
} }
} }
void write_se_result(char* buf){ void write_se_result(char *buf)
//int fd; {
// int fd;
int unused __attribute__((unused)); int unused __attribute__((unused));
if (!se_fd) if (!se_fd)
se_fd = open(redqueen_workdir.symbolic_results, O_WRONLY | O_CREAT | O_APPEND, S_IRWXU); se_fd = open(redqueen_workdir.symbolic_results,
O_WRONLY | O_CREAT | O_APPEND, S_IRWXU);
unused = write(se_fd, buf, strlen(buf)); unused = write(se_fd, buf, strlen(buf));
//close(fd); // close(fd);
} }
void delete_redqueen_files(void){ void delete_redqueen_files(void)
{
int unused __attribute__((unused)); int unused __attribute__((unused));
if (!re_fd) if (!re_fd)
re_fd = open(redqueen_workdir.redqueen_results, O_WRONLY | O_CREAT | O_APPEND, S_IRWXU); re_fd = open(redqueen_workdir.redqueen_results,
O_WRONLY | O_CREAT | O_APPEND, S_IRWXU);
if (!se_fd) if (!se_fd)
se_fd = open(redqueen_workdir.symbolic_results, O_WRONLY | O_CREAT | O_APPEND, S_IRWXU); se_fd = open(redqueen_workdir.symbolic_results,
O_WRONLY | O_CREAT | O_APPEND, S_IRWXU);
unused = ftruncate(re_fd, 0); unused = ftruncate(re_fd, 0);
unused = ftruncate(se_fd, 0); unused = ftruncate(se_fd, 0);
} }
@ -96,25 +106,28 @@ void delete_redqueen_files(void){
* Private Helper Functions Definitions * Private Helper Functions Definitions
*/ */
size_t _count_lines_in_file(FILE* fp){ size_t _count_lines_in_file(FILE *fp)
{
size_t val = 0; size_t val = 0;
size_t count = 0; size_t count = 0;
while(1){ while (1) {
int scanres = fscanf(fp, "%lx", &val); int scanres = fscanf(fp, "%lx", &val);
if(scanres == 0){ if (scanres == 0) {
printf("WARNING, invalid line in address file"); printf("WARNING, invalid line in address file");
assert(scanres != 0); assert(scanres != 0);
} }
if(scanres == -1){break;} if (scanres == -1) {
count+=1; break;
}
count += 1;
} }
rewind(fp); rewind(fp);
return count; return count;
} }
void _parse_addresses_in_file(FILE* fp, size_t num_addrs, uint64_t* addrs){ void _parse_addresses_in_file(FILE *fp, size_t num_addrs, uint64_t *addrs)
for(size_t i = 0; i < num_addrs; i++){ {
for (size_t i = 0; i < num_addrs; i++) {
assert(fscanf(fp, "%lx", &addrs[i]) == 1); assert(fscanf(fp, "%lx", &addrs[i]) == 1);
} }
} }

View File

@ -1,20 +1,21 @@
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#pragma once #pragma once
//doesn't take ownership of path, num_addrs or addrs #include <stdint.h>
void parse_address_file(char* path, size_t* num_addrs, uint64_t** addrs); #include <stdio.h>
#include <stdlib.h>
//doesn't take ownership of buf
void write_re_result(char* buf);
//doesn't take ownership of buf // doesn't take ownership of path, num_addrs or addrs
void write_se_result(char* buf); void parse_address_file(char *path, size_t *num_addrs, uint64_t **addrs);
//doesn' take ownership of buf // doesn't take ownership of buf
void write_debug_result(char* buf); void write_re_result(char *buf);
// doesn't take ownership of buf
void write_se_result(char *buf);
// doesn' take ownership of buf
void write_debug_result(char *buf);
void delete_redqueen_files(void); void delete_redqueen_files(void);

View File

@ -12,30 +12,34 @@
#include "sysemu/kvm_int.h" #include "sysemu/kvm_int.h"
#include "qemu-common.h" #include "qemu-common.h"
#include "nyx/helpers.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
void nyx_abort(char* msg){ void nyx_abort(char *msg)
set_abort_reason_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer, msg, strlen(msg)); {
set_abort_reason_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer, msg,
strlen(msg));
synchronization_lock(); synchronization_lock();
exit(1); exit(1);
} }
bool is_called_in_fuzzing_mode(const char* hypercall){ bool is_called_in_fuzzing_mode(const char *hypercall)
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ {
char* tmp = NULL; if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
assert(asprintf(&tmp, "Hypercall <%s> called during fuzzing...", hypercall) != -1); char *tmp = NULL;
nyx_abort((char*)tmp); assert(asprintf(&tmp, "Hypercall <%s> called during fuzzing...", hypercall) !=
-1);
nyx_abort((char *)tmp);
free(tmp); free(tmp);
return true; return true;
} }
return false; return false;
} }
uint64_t get_rip(CPUState *cpu){ uint64_t get_rip(CPUState *cpu)
{
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
X86CPU *x86_cpu = X86_CPU(cpu); X86CPU *x86_cpu = X86_CPU(cpu);
CPUX86State *env = &x86_cpu->env; CPUX86State *env = &x86_cpu->env;
@ -43,8 +47,9 @@ uint64_t get_rip(CPUState *cpu){
return env->eip; return env->eip;
} }
int get_capstone_mode(int word_width_in_bits){ int get_capstone_mode(int word_width_in_bits)
switch(word_width_in_bits){ {
switch (word_width_in_bits) {
case 64: case 64:
return CS_MODE_64; return CS_MODE_64;
case 32: case 32:
@ -54,8 +59,9 @@ int get_capstone_mode(int word_width_in_bits){
} }
} }
nyx_coverage_bitmap_copy_t* new_coverage_bitmaps(void){ nyx_coverage_bitmap_copy_t *new_coverage_bitmaps(void)
nyx_coverage_bitmap_copy_t* bitmaps = malloc(sizeof(nyx_coverage_bitmap_copy_t)); {
nyx_coverage_bitmap_copy_t *bitmaps = malloc(sizeof(nyx_coverage_bitmap_copy_t));
memset(bitmaps, 0, sizeof(nyx_coverage_bitmap_copy_t)); memset(bitmaps, 0, sizeof(nyx_coverage_bitmap_copy_t));
assert(GET_GLOBAL_STATE()->shared_bitmap_size); assert(GET_GLOBAL_STATE()->shared_bitmap_size);
@ -67,36 +73,46 @@ nyx_coverage_bitmap_copy_t* new_coverage_bitmaps(void){
return bitmaps; return bitmaps;
} }
void coverage_bitmap_reset(void){ void coverage_bitmap_reset(void)
if(GET_GLOBAL_STATE()->shared_bitmap_ptr){ {
memset(GET_GLOBAL_STATE()->shared_bitmap_ptr, 0x00, GET_GLOBAL_STATE()->shared_bitmap_real_size); if (GET_GLOBAL_STATE()->shared_bitmap_ptr) {
memset(GET_GLOBAL_STATE()->shared_bitmap_ptr, 0x00,
GET_GLOBAL_STATE()->shared_bitmap_real_size);
} }
if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr && GET_GLOBAL_STATE()->shared_ijon_bitmap_size){ if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr &&
memset(GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr, 0x00, GET_GLOBAL_STATE()->shared_ijon_bitmap_size); GET_GLOBAL_STATE()->shared_ijon_bitmap_size)
{
memset(GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr, 0x00,
GET_GLOBAL_STATE()->shared_ijon_bitmap_size);
} }
} }
void coverage_bitmap_copy_to_buffer(nyx_coverage_bitmap_copy_t* buffer){ void coverage_bitmap_copy_to_buffer(nyx_coverage_bitmap_copy_t *buffer)
{
if(GET_GLOBAL_STATE()->shared_bitmap_ptr){ if (GET_GLOBAL_STATE()->shared_bitmap_ptr) {
memcpy(buffer->coverage_bitmap, GET_GLOBAL_STATE()->shared_bitmap_ptr, GET_GLOBAL_STATE()->shared_bitmap_real_size); memcpy(buffer->coverage_bitmap, GET_GLOBAL_STATE()->shared_bitmap_ptr,
GET_GLOBAL_STATE()->shared_bitmap_real_size);
} }
if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr){ if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr) {
memcpy(buffer->ijon_bitmap_buffer, GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr, GET_GLOBAL_STATE()->shared_ijon_bitmap_size); memcpy(buffer->ijon_bitmap_buffer, GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr,
GET_GLOBAL_STATE()->shared_ijon_bitmap_size);
} }
} }
void coverage_bitmap_copy_from_buffer(nyx_coverage_bitmap_copy_t* buffer){ void coverage_bitmap_copy_from_buffer(nyx_coverage_bitmap_copy_t *buffer)
{
if(GET_GLOBAL_STATE()->shared_bitmap_ptr){ if (GET_GLOBAL_STATE()->shared_bitmap_ptr) {
memcpy(GET_GLOBAL_STATE()->shared_bitmap_ptr, buffer->coverage_bitmap, GET_GLOBAL_STATE()->shared_bitmap_real_size); memcpy(GET_GLOBAL_STATE()->shared_bitmap_ptr, buffer->coverage_bitmap,
GET_GLOBAL_STATE()->shared_bitmap_real_size);
} }
if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr){ if (GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr) {
memcpy(GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr, buffer->ijon_bitmap_buffer, GET_GLOBAL_STATE()->shared_ijon_bitmap_size); memcpy(GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr, buffer->ijon_bitmap_buffer,
GET_GLOBAL_STATE()->shared_ijon_bitmap_size);
} }
} }
static void resize_coverage_bitmap(uint32_t new_bitmap_size){ static void resize_coverage_bitmap(uint32_t new_bitmap_size)
{
uint32_t new_bitmap_shm_size = new_bitmap_size; uint32_t new_bitmap_shm_size = new_bitmap_size;
if (new_bitmap_shm_size % 64 > 0) { if (new_bitmap_shm_size % 64 > 0) {
@ -104,83 +120,118 @@ static void resize_coverage_bitmap(uint32_t new_bitmap_size){
} }
GET_GLOBAL_STATE()->shared_bitmap_real_size = new_bitmap_shm_size; GET_GLOBAL_STATE()->shared_bitmap_real_size = new_bitmap_shm_size;
resize_shared_memory(new_bitmap_shm_size, &GET_GLOBAL_STATE()->shared_bitmap_size, &GET_GLOBAL_STATE()->shared_bitmap_ptr, GET_GLOBAL_STATE()->shared_bitmap_fd); resize_shared_memory(new_bitmap_shm_size, &GET_GLOBAL_STATE()->shared_bitmap_size,
&GET_GLOBAL_STATE()->shared_bitmap_ptr,
GET_GLOBAL_STATE()->shared_bitmap_fd);
/* pass the actual bitmap buffer size to the front-end */ /* pass the actual bitmap buffer size to the front-end */
GET_GLOBAL_STATE()->auxilary_buffer->capabilites.agent_coverage_bitmap_size = new_bitmap_size; GET_GLOBAL_STATE()->auxilary_buffer->capabilites.agent_coverage_bitmap_size =
new_bitmap_size;
if(new_bitmap_size & (PAGE_SIZE-1)){ if (new_bitmap_size & (PAGE_SIZE - 1)) {
GET_GLOBAL_STATE()->shared_bitmap_size = (new_bitmap_size & ~(PAGE_SIZE-1)) + PAGE_SIZE; GET_GLOBAL_STATE()->shared_bitmap_size =
(new_bitmap_size & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
} }
} }
bool apply_capabilities(CPUState *cpu){ bool apply_capabilities(CPUState *cpu)
{
nyx_debug("%s: agent supports timeout detection: %d\n", __func__,
GET_GLOBAL_STATE()->cap_timeout_detection);
nyx_debug("%s: agent supports only-reload mode: %d\n", __func__,
GET_GLOBAL_STATE()->cap_only_reload_mode);
nyx_debug("%s: agent supports compile-time tracing: %d\n", __func__,
GET_GLOBAL_STATE()->cap_compile_time_tracing);
nyx_debug("%s: agent supports timeout detection: %d\n", __func__, GET_GLOBAL_STATE()->cap_timeout_detection); if (GET_GLOBAL_STATE()->cap_compile_time_tracing) {
nyx_debug("%s: agent supports only-reload mode: %d\n", __func__, GET_GLOBAL_STATE()->cap_only_reload_mode);
nyx_debug("%s: agent supports compile-time tracing: %d\n", __func__, GET_GLOBAL_STATE()->cap_compile_time_tracing );
if(GET_GLOBAL_STATE()->cap_compile_time_tracing){
GET_GLOBAL_STATE()->pt_trace_mode = false; GET_GLOBAL_STATE()->pt_trace_mode = false;
nyx_debug("%s: agent trace buffer at vaddr: %lx\n", __func__, GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr); nyx_debug("%s: agent trace buffer at vaddr: %lx\n", __func__,
GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr);
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
nyx_debug("--------------------------\n"); nyx_debug("--------------------------\n");
nyx_debug("GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr: %lx\n", GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr); nyx_debug("GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr: %lx\n",
nyx_debug("GET_GLOBAL_STATE()->shared_bitmap_fd: %d\n", GET_GLOBAL_STATE()->shared_bitmap_fd); GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr);
nyx_debug("GET_GLOBAL_STATE()->shared_bitmap_size: %x\n", GET_GLOBAL_STATE()->shared_bitmap_size); nyx_debug("GET_GLOBAL_STATE()->shared_bitmap_fd: %d\n",
GET_GLOBAL_STATE()->shared_bitmap_fd);
nyx_debug("GET_GLOBAL_STATE()->shared_bitmap_size: %x\n",
GET_GLOBAL_STATE()->shared_bitmap_size);
nyx_debug("GET_GLOBAL_STATE()->cap_cr3: %lx\n", GET_GLOBAL_STATE()->cap_cr3); nyx_debug("GET_GLOBAL_STATE()->cap_cr3: %lx\n", GET_GLOBAL_STATE()->cap_cr3);
nyx_debug("--------------------------\n"); nyx_debug("--------------------------\n");
if (GET_GLOBAL_STATE()->input_buffer_size != GET_GLOBAL_STATE()->shared_payload_buffer_size){ if (GET_GLOBAL_STATE()->input_buffer_size !=
resize_shared_memory(GET_GLOBAL_STATE()->input_buffer_size, &GET_GLOBAL_STATE()->shared_payload_buffer_size, NULL, GET_GLOBAL_STATE()->shared_payload_buffer_fd); GET_GLOBAL_STATE()->shared_payload_buffer_size)
GET_GLOBAL_STATE()->shared_payload_buffer_size = GET_GLOBAL_STATE()->input_buffer_size; {
resize_shared_memory(GET_GLOBAL_STATE()->input_buffer_size,
&GET_GLOBAL_STATE()->shared_payload_buffer_size,
NULL, GET_GLOBAL_STATE()->shared_payload_buffer_fd);
GET_GLOBAL_STATE()->shared_payload_buffer_size =
GET_GLOBAL_STATE()->input_buffer_size;
} }
if(GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr&0xfff){ if (GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr & 0xfff) {
fprintf(stderr, "[QEMU-Nyx] Error: guest's trace bitmap v_addr (0x%lx) is not page aligned!\n", GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr); fprintf(stderr, "[QEMU-Nyx] Error: guest's trace bitmap v_addr (0x%lx) is not page aligned!\n",
GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr);
return false; return false;
} }
if (GET_GLOBAL_STATE()->cap_coverage_bitmap_size){ if (GET_GLOBAL_STATE()->cap_coverage_bitmap_size) {
resize_coverage_bitmap(GET_GLOBAL_STATE()->cap_coverage_bitmap_size); resize_coverage_bitmap(GET_GLOBAL_STATE()->cap_coverage_bitmap_size);
} }
for(uint64_t i = 0; i < GET_GLOBAL_STATE()->shared_bitmap_size; i += 0x1000){ for (uint64_t i = 0; i < GET_GLOBAL_STATE()->shared_bitmap_size; i += 0x1000)
assert(remap_slot(GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr+ i, i/0x1000, cpu, GET_GLOBAL_STATE()->shared_bitmap_fd, GET_GLOBAL_STATE()->shared_bitmap_size, true, GET_GLOBAL_STATE()->cap_cr3)); {
assert(remap_slot(GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr +
i,
i / 0x1000, cpu, GET_GLOBAL_STATE()->shared_bitmap_fd,
GET_GLOBAL_STATE()->shared_bitmap_size, true,
GET_GLOBAL_STATE()->cap_cr3));
} }
set_cap_agent_trace_bitmap(GET_GLOBAL_STATE()->auxilary_buffer, true); set_cap_agent_trace_bitmap(GET_GLOBAL_STATE()->auxilary_buffer, true);
} }
if(GET_GLOBAL_STATE()->cap_ijon_tracing){ if (GET_GLOBAL_STATE()->cap_ijon_tracing) {
nyx_debug("%s: agent trace buffer at vaddr: %lx\n", __func__, GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr); nyx_debug("%s: agent trace buffer at vaddr: %lx\n", __func__,
GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr);
if(GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr&0xfff){ if (GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr & 0xfff) {
error_printf("[QEMU-Nyx] Error: guest's ijon buffer v_addr (0x%lx) is not page aligned!\n", GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr); error_printf("[QEMU-Nyx] Error: guest's ijon buffer v_addr (0x%lx) is "
"not page aligned!\n",
GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr);
return false; return false;
} }
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
for(uint64_t i = 0; i < GET_GLOBAL_STATE()->shared_ijon_bitmap_size; i += 0x1000){ for (uint64_t i = 0; i < GET_GLOBAL_STATE()->shared_ijon_bitmap_size;
assert(remap_slot(GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr + i, i/0x1000, cpu, GET_GLOBAL_STATE()->shared_ijon_bitmap_fd, GET_GLOBAL_STATE()->shared_ijon_bitmap_size+GET_GLOBAL_STATE()->shared_ijon_bitmap_size, true, GET_GLOBAL_STATE()->cap_cr3)); i += 0x1000)
{
assert(remap_slot(GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr + i,
i / 0x1000, cpu,
GET_GLOBAL_STATE()->shared_ijon_bitmap_fd,
GET_GLOBAL_STATE()->shared_ijon_bitmap_size +
GET_GLOBAL_STATE()->shared_ijon_bitmap_size,
true, GET_GLOBAL_STATE()->cap_cr3));
} }
set_cap_agent_ijon_trace_bitmap(GET_GLOBAL_STATE()->auxilary_buffer, true); set_cap_agent_ijon_trace_bitmap(GET_GLOBAL_STATE()->auxilary_buffer, true);
} }
/* pass the actual input buffer size to the front-end */ /* pass the actual input buffer size to the front-end */
GET_GLOBAL_STATE()->auxilary_buffer->capabilites.agent_input_buffer_size = GET_GLOBAL_STATE()->shared_payload_buffer_size; GET_GLOBAL_STATE()->auxilary_buffer->capabilites.agent_input_buffer_size =
GET_GLOBAL_STATE()->shared_payload_buffer_size;
return true; return true;
} }
bool folder_exits(const char* path){ bool folder_exits(const char *path)
{
struct stat sb; struct stat sb;
return (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode)); return (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode));
} }
bool file_exits(const char* path){ bool file_exits(const char *path)
{
struct stat sb; struct stat sb;
return (stat (path, &sb) == 0); return (stat(path, &sb) == 0);
} }

View File

@ -2,22 +2,22 @@
uint64_t get_rip(CPUState *cpu); uint64_t get_rip(CPUState *cpu);
typedef struct nyx_coverage_bitmap_copy_s{ typedef struct nyx_coverage_bitmap_copy_s {
void* coverage_bitmap; void *coverage_bitmap;
void* ijon_bitmap_buffer; void *ijon_bitmap_buffer;
}nyx_coverage_bitmap_copy_t; } nyx_coverage_bitmap_copy_t;
void nyx_abort(char* msg); void nyx_abort(char *msg);
bool is_called_in_fuzzing_mode(const char* hypercall); bool is_called_in_fuzzing_mode(const char *hypercall);
nyx_coverage_bitmap_copy_t* new_coverage_bitmaps(void); nyx_coverage_bitmap_copy_t *new_coverage_bitmaps(void);
void coverage_bitmap_reset(void); void coverage_bitmap_reset(void);
void coverage_bitmap_copy_to_buffer(nyx_coverage_bitmap_copy_t* buffer); void coverage_bitmap_copy_to_buffer(nyx_coverage_bitmap_copy_t *buffer);
void coverage_bitmap_copy_from_buffer(nyx_coverage_bitmap_copy_t* buffer); void coverage_bitmap_copy_from_buffer(nyx_coverage_bitmap_copy_t *buffer);
int get_capstone_mode(int word_width_in_bits); int get_capstone_mode(int word_width_in_bits);
bool apply_capabilities(CPUState *cpu); bool apply_capabilities(CPUState *cpu);
bool folder_exits(const char* path); bool folder_exits(const char *path);
bool file_exits(const char* path); bool file_exits(const char *path);

View File

@ -1,24 +1,27 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "nyx/state/state.h" #include "nyx/helpers.h"
#include "nyx/hypercall/configuration.h" #include "nyx/hypercall/configuration.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/helpers.h" #include "nyx/state/state.h"
void handle_hypercall_kafl_get_host_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_get_host_config(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
uint64_t vaddr = hypercall_arg; uint64_t vaddr = hypercall_arg;
host_config_t config; host_config_t config;
if(is_called_in_fuzzing_mode("KVM_EXIT_KAFL_GET_HOST_CONFIG")){ if (is_called_in_fuzzing_mode("KVM_EXIT_KAFL_GET_HOST_CONFIG")) {
return; return;
} }
if (GET_GLOBAL_STATE()->get_host_config_done){ if (GET_GLOBAL_STATE()->get_host_config_done) {
nyx_abort((char*)"KVM_EXIT_KAFL_GET_HOST_CONFIG called twice..."); nyx_abort((char *)"KVM_EXIT_KAFL_GET_HOST_CONFIG called twice...");
return; return;
} }
memset((void*)&config, 0, sizeof(host_config_t)); memset((void *)&config, 0, sizeof(host_config_t));
config.host_magic = NYX_HOST_MAGIC; config.host_magic = NYX_HOST_MAGIC;
config.host_version = NYX_HOST_VERSION; config.host_version = NYX_HOST_VERSION;
@ -27,34 +30,38 @@ void handle_hypercall_kafl_get_host_config(struct kvm_run *run, CPUState *cpu, u
config.payload_buffer_size = GET_GLOBAL_STATE()->shared_payload_buffer_size; config.payload_buffer_size = GET_GLOBAL_STATE()->shared_payload_buffer_size;
config.worker_id = GET_GLOBAL_STATE()->worker_id; config.worker_id = GET_GLOBAL_STATE()->worker_id;
write_virtual_memory(vaddr, (uint8_t*)&config, sizeof(host_config_t), cpu); write_virtual_memory(vaddr, (uint8_t *)&config, sizeof(host_config_t), cpu);
GET_GLOBAL_STATE()->get_host_config_done = true; GET_GLOBAL_STATE()->get_host_config_done = true;
} }
void handle_hypercall_kafl_set_agent_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_set_agent_config(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
uint64_t vaddr = hypercall_arg; uint64_t vaddr = hypercall_arg;
agent_config_t config; agent_config_t config;
if(is_called_in_fuzzing_mode("KVM_EXIT_KAFL_SET_AGENT_CONFIG")){ if (is_called_in_fuzzing_mode("KVM_EXIT_KAFL_SET_AGENT_CONFIG")) {
return; return;
} }
if (GET_GLOBAL_STATE()->set_agent_config_done){ if (GET_GLOBAL_STATE()->set_agent_config_done) {
nyx_abort((char*)"KVM_EXIT_KAFL_SET_AGENT_CONFIG called twice..."); nyx_abort((char *)"KVM_EXIT_KAFL_SET_AGENT_CONFIG called twice...");
return; return;
} }
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
if(read_virtual_memory(vaddr, (uint8_t*)&config, sizeof(agent_config_t), cpu)){ if (read_virtual_memory(vaddr, (uint8_t *)&config, sizeof(agent_config_t), cpu)) {
if (config.agent_magic != NYX_AGENT_MAGIC) {
if (config.agent_magic != NYX_AGENT_MAGIC){ fprintf(stderr,
fprintf(stderr, "[QEMU-Nyx] Error: NYX_AGENT_MAGIC not found in agent configuration - You are probably using an outdated agent...\n"); "[QEMU-Nyx] Error: NYX_AGENT_MAGIC not found in agent "
"configuration - You are probably using an outdated agent...\n");
exit(1); exit(1);
} }
if (config.agent_version != NYX_AGENT_VERSION){ if (config.agent_version != NYX_AGENT_VERSION) {
fprintf(stderr, fprintf(stderr,
"[QEMU-Nyx] Error: NYX_AGENT_VERSION does not match in agent " "[QEMU-Nyx] Error: NYX_AGENT_VERSION does not match in agent "
"configuration (%d != %d) - " "configuration (%d != %d) - "
@ -64,44 +71,54 @@ void handle_hypercall_kafl_set_agent_config(struct kvm_run *run, CPUState *cpu,
} }
GET_GLOBAL_STATE()->cap_timeout_detection = config.agent_timeout_detection; GET_GLOBAL_STATE()->cap_timeout_detection = config.agent_timeout_detection;
GET_GLOBAL_STATE()->cap_only_reload_mode = !!!config.agent_non_reload_mode; /* fix this */ GET_GLOBAL_STATE()->cap_only_reload_mode =
!!!config.agent_non_reload_mode; /* fix this */
GET_GLOBAL_STATE()->cap_compile_time_tracing = config.agent_tracing; GET_GLOBAL_STATE()->cap_compile_time_tracing = config.agent_tracing;
if(!GET_GLOBAL_STATE()->cap_compile_time_tracing && !GET_GLOBAL_STATE()->nyx_fdl){ if (!GET_GLOBAL_STATE()->cap_compile_time_tracing &&
fprintf(stderr, "[QEMU-Nyx] Error: Attempt to fuzz target without compile-time instrumentation - Intel PT is not supported on this KVM build!\n"); !GET_GLOBAL_STATE()->nyx_fdl)
{
fprintf(
stderr,
"[QEMU-Nyx] Error: Attempt to fuzz target without compile-time "
"instrumentation - Intel PT is not supported on this KVM build!\n");
exit(1); exit(1);
} }
GET_GLOBAL_STATE()->cap_ijon_tracing = config.agent_ijon_tracing; GET_GLOBAL_STATE()->cap_ijon_tracing = config.agent_ijon_tracing;
if(config.agent_tracing){ if (config.agent_tracing) {
GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr = config.trace_buffer_vaddr; GET_GLOBAL_STATE()->cap_compile_time_tracing_buffer_vaddr =
config.trace_buffer_vaddr;
GET_GLOBAL_STATE()->pt_trace_mode = false; GET_GLOBAL_STATE()->pt_trace_mode = false;
} }
if(config.agent_ijon_tracing){ if (config.agent_ijon_tracing) {
GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr = config.ijon_trace_buffer_vaddr; GET_GLOBAL_STATE()->cap_ijon_tracing_buffer_vaddr =
config.ijon_trace_buffer_vaddr;
} }
GET_GLOBAL_STATE()->cap_cr3 = env->cr[3]; GET_GLOBAL_STATE()->cap_cr3 = env->cr[3];
GET_GLOBAL_STATE()->cap_coverage_bitmap_size = config.coverage_bitmap_size; GET_GLOBAL_STATE()->cap_coverage_bitmap_size = config.coverage_bitmap_size;
GET_GLOBAL_STATE()->input_buffer_size = GET_GLOBAL_STATE()->shared_payload_buffer_size; GET_GLOBAL_STATE()->input_buffer_size =
GET_GLOBAL_STATE()->shared_payload_buffer_size;
if (config.input_buffer_size){ if (config.input_buffer_size) {
abort(); abort();
} }
if(apply_capabilities(cpu) == false){ if (apply_capabilities(cpu) == false) {
nyx_abort((char*)"applying agent configuration failed..."); nyx_abort((char *)"applying agent configuration failed...");
} }
if(getenv("DUMP_PAYLOAD_MODE")){ if (getenv("DUMP_PAYLOAD_MODE")) {
config.dump_payloads = 1; config.dump_payloads = 1;
write_virtual_memory(vaddr, (uint8_t*)&config, sizeof(agent_config_t), cpu); write_virtual_memory(vaddr, (uint8_t *)&config, sizeof(agent_config_t),
cpu);
} }
} } else {
else{ fprintf(stderr, "[QEMU-Nyx] Error: %s - failed (vaddr: 0x%lx)!\n", __func__,
fprintf(stderr, "[QEMU-Nyx] Error: %s - failed (vaddr: 0x%lx)!\n", __func__, vaddr); vaddr);
exit(1); exit(1);
} }
GET_GLOBAL_STATE()->set_agent_config_done = true; GET_GLOBAL_STATE()->set_agent_config_done = true;

View File

@ -5,9 +5,13 @@
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
void handle_hypercall_kafl_get_host_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_get_host_config(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_set_agent_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_set_agent_config(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
#define NYX_HOST_MAGIC 0x4878794e #define NYX_HOST_MAGIC 0x4878794e
@ -16,7 +20,7 @@ void handle_hypercall_kafl_set_agent_config(struct kvm_run *run, CPUState *cpu,
#define NYX_HOST_VERSION 2 #define NYX_HOST_VERSION 2
#define NYX_AGENT_VERSION 1 #define NYX_AGENT_VERSION 1
typedef struct host_config_s{ typedef struct host_config_s {
uint32_t host_magic; uint32_t host_magic;
uint32_t host_version; uint32_t host_version;
uint32_t bitmap_size; uint32_t bitmap_size;
@ -26,7 +30,7 @@ typedef struct host_config_s{
/* more to come */ /* more to come */
} __attribute__((packed)) host_config_t; } __attribute__((packed)) host_config_t;
typedef struct agent_config_s{ typedef struct agent_config_s {
uint32_t agent_magic; uint32_t agent_magic;
uint32_t agent_version; uint32_t agent_version;
uint8_t agent_timeout_detection; uint8_t agent_timeout_detection;

View File

@ -1,88 +1,102 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <sys/time.h>
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
#include <sys/time.h>
#include "nyx/synchronization.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/state/state.h"
#include "nyx/hypercall/debug.h" #include "nyx/hypercall/debug.h"
#include "nyx/state/state.h"
#include "nyx/synchronization.h"
//#define NYX_ENABLE_DEBUG_HYPERCALLS // #define NYX_ENABLE_DEBUG_HYPERCALLS
#ifdef NYX_ENABLE_DEBUG_HYPERCALLS #ifdef NYX_ENABLE_DEBUG_HYPERCALLS
static double get_time(void){ static double get_time(void)
{
struct timeval t; struct timeval t;
struct timezone tzp; struct timezone tzp;
gettimeofday(&t, &tzp); gettimeofday(&t, &tzp);
return t.tv_sec + t.tv_usec*1e-6; return t.tv_sec + t.tv_usec * 1e-6;
} }
static void print_time_diff(int iterations){ static void print_time_diff(int iterations)
{
static bool init = true; static bool init = true;
static double start_time = 0.0; static double start_time = 0.0;
static double end_time = 0.0; static double end_time = 0.0;
if(init){ if (init) {
init = false; init = false;
printf("start time is zero!\n"); printf("start time is zero!\n");
start_time = get_time(); start_time = get_time();
} } else {
else{
end_time = get_time(); end_time = get_time();
double elapsed_time = end_time - start_time; double elapsed_time = end_time - start_time;
printf("Done in %f seconds\n", elapsed_time); printf("Done in %f seconds\n", elapsed_time);
printf("Performance: %f\n", iterations/elapsed_time); printf("Performance: %f\n", iterations / elapsed_time);
start_time = get_time(); start_time = get_time();
} }
} }
static void meassure_performance(void){ static void meassure_performance(void)
{
static int perf_counter = 0; static int perf_counter = 0;
if ((perf_counter%1000) == 0){ if ((perf_counter % 1000) == 0) {
print_time_diff(1000); print_time_diff(1000);
} }
perf_counter++; perf_counter++;
} }
void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
static bool first = true; static bool first = true;
switch(hypercall_arg&0xFFF){ switch (hypercall_arg & 0xFFF) {
case 0: /* create root snapshot */ case 0: /* create root snapshot */
if(!fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_ROOT_EXISTS)){ if (!fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state,
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_ROOT); REQUEST_ROOT_EXISTS))
{
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
REQUEST_SAVE_SNAPSHOT_ROOT);
} }
break; break;
case 1: /* create tmp snapshot */ case 1: /* create tmp snapshot */
if(!fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS)){ if (!fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS))
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_TMP); {
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
REQUEST_SAVE_SNAPSHOT_TMP);
} }
break; break;
case 2: /* load root snapshot (+ discard tmp snapshot) */ case 2: /* load root snapshot (+ discard tmp snapshot) */
if(fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS)){ if (fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS))
{
reload_request_discard_tmp(GET_GLOBAL_STATE()->reload_state); reload_request_discard_tmp(GET_GLOBAL_STATE()->reload_state);
} }
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_LOAD_SNAPSHOT_ROOT); request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
REQUEST_LOAD_SNAPSHOT_ROOT);
meassure_performance(); meassure_performance();
break; break;
case 3: /* load tmp snapshot */ case 3: /* load tmp snapshot */
if(fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS)){ if (fast_snapshot_exists(GET_GLOBAL_STATE()->reload_state, REQUEST_TMP_EXISTS))
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_LOAD_SNAPSHOT_TMP); {
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
REQUEST_LOAD_SNAPSHOT_TMP);
meassure_performance(); meassure_performance();
} }
break; break;
case 5: // firefox debug hypercall case 5: // firefox debug hypercall
if(first){ if (first) {
first = false; first = false;
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_ROOT); request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
//request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_TMP); REQUEST_SAVE_SNAPSHOT_ROOT);
// request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_TMP);
break; break;
} } else {
else{ request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_LOAD_SNAPSHOT_ROOT); REQUEST_LOAD_SNAPSHOT_ROOT);
break; break;
} }
default: default:
@ -91,8 +105,10 @@ void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run, CPUState *cpu
} }
#else /* NYX_ENABLE_DEBUG_HYPERCALLS */ #else /* NYX_ENABLE_DEBUG_HYPERCALLS */
void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
fprintf(stderr, "[QEMU-Nyx] Error: HYPERCALL_KAFL_DEBUG_TMP not enabled!\n"); fprintf(stderr, "[QEMU-Nyx] Error: HYPERCALL_KAFL_DEBUG_TMP not enabled!\n");
set_abort_reason_auxiliary_buffer( set_abort_reason_auxiliary_buffer(
GET_GLOBAL_STATE()->auxilary_buffer, GET_GLOBAL_STATE()->auxilary_buffer,

View File

@ -1,6 +1,8 @@
#pragma once #pragma once
#include <stdint.h>
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
#include <stdint.h>
void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_debug_tmp_snapshot(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);

File diff suppressed because it is too large Load Diff

View File

@ -31,7 +31,7 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#define KAFL_MODE_32 1 #define KAFL_MODE_32 1
#define KAFL_MODE_16 2 #define KAFL_MODE_16 2
typedef struct{ typedef struct {
uint64_t ip[4]; uint64_t ip[4];
uint64_t size[4]; uint64_t size[4];
uint8_t enabled[4]; uint8_t enabled[4];
@ -39,7 +39,7 @@ typedef struct{
bool check_bitmap_byte(uint32_t value); bool check_bitmap_byte(uint32_t value);
//#define PANIC_DEBUG // #define PANIC_DEBUG
/* /*
* Panic Notifier Payload (x86-64) * Panic Notifier Payload (x86-64)
@ -50,7 +50,9 @@ bool check_bitmap_byte(uint32_t value);
* 0f 01 c1 vmcall * 0f 01 c1 vmcall
* f4 hlt * f4 hlt
*/ */
#define PANIC_PAYLOAD_64 "\xFA\x48\xC7\xC0\x1F\x00\x00\x00\x48\xC7\xC3\x08\x00\x00\x00\x48\xC7\xC1\x00\x00\x00\x00\x0F\x01\xC1\xF4" #define PANIC_PAYLOAD_64 \
"\xFA\x48\xC7\xC0\x1F\x00\x00\x00\x48\xC7\xC3\x08\x00\x00\x00\x48\xC7\xC1\x00" \
"\x00\x00\x00\x0F\x01\xC1\xF4"
/* /*
* Panic Notifier Payload (x86-32) * Panic Notifier Payload (x86-32)
@ -61,7 +63,9 @@ bool check_bitmap_byte(uint32_t value);
* 0f 01 c1 vmcall * 0f 01 c1 vmcall
* f4 hlt * f4 hlt
*/ */
#define PANIC_PAYLOAD_32 "\xFA\xB8\x1F\x00\x00\x00\xBB\x08\x00\x00\x00\xB9\x00\x00\x00\x00\x0F\x01\xC1\xF4" #define PANIC_PAYLOAD_32 \
"\xFA\xB8\x1F\x00\x00\x00\xBB\x08\x00\x00\x00\xB9\x00\x00\x00\x00\x0F\x01\xC1" \
"\xF4"
/* /*
* KASAN Notifier Payload (x86-64) * KASAN Notifier Payload (x86-64)
@ -72,7 +76,9 @@ bool check_bitmap_byte(uint32_t value);
* 0f 01 c1 vmcall * 0f 01 c1 vmcall
* f4 hlt * f4 hlt
*/ */
#define KASAN_PAYLOAD_64 "\xFA\x48\xC7\xC0\x1F\x00\x00\x00\x48\xC7\xC3\x09\x00\x00\x00\x48\xC7\xC1\x00\x00\x00\x00\x0F\x01\xC1\xF4" #define KASAN_PAYLOAD_64 \
"\xFA\x48\xC7\xC0\x1F\x00\x00\x00\x48\xC7\xC3\x09\x00\x00\x00\x48\xC7\xC1\x00" \
"\x00\x00\x00\x0F\x01\xC1\xF4"
/* /*
* KASAN Notifier Payload (x86-32) * KASAN Notifier Payload (x86-32)
@ -83,10 +89,12 @@ bool check_bitmap_byte(uint32_t value);
* 0f 01 c1 vmcall * 0f 01 c1 vmcall
* f4 hlt * f4 hlt
*/ */
#define KASAN_PAYLOAD_32 "\xFA\xB8\x1F\x00\x00\x00\xBB\x09\x00\x00\x00\xB9\x00\x00\x00\x00\x0F\x01\xC1\xF4" #define KASAN_PAYLOAD_32 \
"\xFA\xB8\x1F\x00\x00\x00\xBB\x09\x00\x00\x00\xB9\x00\x00\x00\x00\x0F\x01\xC1" \
"\xF4"
void pt_setup_program(void* ptr); void pt_setup_program(void *ptr);
void pt_setup_snd_handler(void (*tmp)(char, void*), void* tmp_s); void pt_setup_snd_handler(void (*tmp)(char, void *), void *tmp_s);
void pt_setup_ip_filters(uint8_t filter_id, uint64_t start, uint64_t end); void pt_setup_ip_filters(uint8_t filter_id, uint64_t start, uint64_t end);
void pt_setup_enable_hypercalls(void); void pt_setup_enable_hypercalls(void);
@ -107,38 +115,56 @@ bool pt_hypercalls_enabled(void);
void hypercall_unlock(void); void hypercall_unlock(void);
void hypercall_reload(void); void hypercall_reload(void);
void handle_hypercall_kafl_acquire(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_acquire(struct kvm_run *run,
void handle_hypercall_kafl_release(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); CPUState *cpu,
void handle_hypercall_kafl_panic(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); uint64_t hypercall_arg);
void handle_hypercall_kafl_release(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_panic(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_page_dump_bp(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg, uint64_t page); void handle_hypercall_kafl_page_dump_bp(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg,
uint64_t page);
void hprintf(char* msg); void hprintf(char *msg);
bool handle_hypercall_kafl_next_payload(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); bool handle_hypercall_kafl_next_payload(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void hypercall_reset_hprintf_counter(void); void hypercall_reset_hprintf_counter(void);
bool handle_hypercall_kafl_hook(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); bool handle_hypercall_kafl_hook(struct kvm_run *run,
void handle_hypercall_kafl_mtf(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_mtf(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void pt_enable_rqo(CPUState *cpu); void pt_enable_rqo(CPUState *cpu);
void pt_disable_rqo(CPUState *cpu); void pt_disable_rqo(CPUState *cpu);
void pt_enable_rqi(CPUState *cpu); void pt_enable_rqi(CPUState *cpu);
void pt_disable_rqi(CPUState *cpu); void pt_disable_rqi(CPUState *cpu);
void pt_set_redqueen_instrumentation_mode(CPUState *cpu, int redqueen_instruction_mode); void pt_set_redqueen_instrumentation_mode(CPUState *cpu,
int redqueen_instruction_mode);
void pt_set_redqueen_update_blacklist(CPUState *cpu, bool newval); void pt_set_redqueen_update_blacklist(CPUState *cpu, bool newval);
void pt_set_enable_patches_pending(CPUState *cpu); void pt_set_enable_patches_pending(CPUState *cpu);
void pt_set_disable_patches_pending(CPUState *cpu); void pt_set_disable_patches_pending(CPUState *cpu);
void create_fast_snapshot(CPUState *cpu, bool nested); void create_fast_snapshot(CPUState *cpu, bool nested);
int handle_kafl_hypercall(struct kvm_run *run, CPUState *cpu, uint64_t hypercall, uint64_t arg); int handle_kafl_hypercall(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall,
uint64_t arg);
void skip_init(void); void skip_init(void);
typedef struct kafl_dump_file_s{ typedef struct kafl_dump_file_s {
uint64_t file_name_str_ptr; uint64_t file_name_str_ptr;
uint64_t data_ptr; uint64_t data_ptr;
uint64_t bytes; uint64_t bytes;
uint8_t append; uint8_t append;
} __attribute__((packed)) kafl_dump_file_t; } __attribute__((packed)) kafl_dump_file_t;

View File

@ -26,43 +26,42 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#include <sys/stat.h> #include <sys/stat.h>
#include <time.h> #include <time.h>
#include "qapi/error.h" #include "chardev/char-fe.h"
#include "qemu/cutils.h" #include "exec/ram_addr.h"
#include "hw/qdev-properties.h"
#include "hw/hw.h" #include "hw/hw.h"
#include "hw/i386/pc.h" #include "hw/i386/pc.h"
#include "hw/pci/pci.h"
#include "hw/pci/msi.h" #include "hw/pci/msi.h"
#include "hw/pci/msix.h" #include "hw/pci/msix.h"
#include "sysemu/kvm.h" #include "hw/pci/pci.h"
#include "hw/qdev-properties.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qapi/error.h"
#include "qapi/visitor.h"
#include "qemu/cutils.h"
#include "qemu/error-report.h" #include "qemu/error-report.h"
#include "qemu/event_notifier.h" #include "qemu/event_notifier.h"
#include "qom/object_interfaces.h" #include "qom/object_interfaces.h"
#include "chardev/char-fe.h"
#include "sysemu/hostmem.h" #include "sysemu/hostmem.h"
#include "sysemu/kvm.h"
#include "sysemu/qtest.h" #include "sysemu/qtest.h"
#include "qapi/visitor.h" #include "nyx/debug.h"
#include "exec/ram_addr.h" #include "nyx/helpers.h"
#include "pt.h"
#include "nyx/hypercall/hypercall.h" #include "nyx/hypercall/hypercall.h"
#include "nyx/interface.h" #include "nyx/interface.h"
#include "nyx/debug.h"
#include "nyx/synchronization.h"
#include "nyx/snapshot/devices/state_reallocation.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/state/state.h"
#include "nyx/sharedir.h" #include "nyx/sharedir.h"
#include "nyx/helpers.h" #include "nyx/snapshot/devices/state_reallocation.h"
#include "nyx/state/state.h"
#include "nyx/synchronization.h"
#include "nyx/trace_dump.h" #include "nyx/trace_dump.h"
#include "pt.h"
#include "redqueen.h" #include "redqueen.h"
#define CONVERT_UINT64(x) (uint64_t)(strtoull(x, NULL, 16)) #define CONVERT_UINT64(x) (uint64_t)(strtoull(x, NULL, 16))
#define TYPE_NYX_MEM "nyx" #define TYPE_NYX_MEM "nyx"
#define NYX_MEM(obj) \ #define NYX_MEM(obj) OBJECT_CHECK(nyx_interface_state, (obj), TYPE_NYX_MEM)
OBJECT_CHECK(nyx_interface_state, (obj), TYPE_NYX_MEM)
static void nyx_realize(DeviceState *dev, Error **errp); static void nyx_realize(DeviceState *dev, Error **errp);
@ -72,20 +71,20 @@ typedef struct nyx_interface_state {
Chardev *nyx_chr_drv_state; Chardev *nyx_chr_drv_state;
CharBackend chr; CharBackend chr;
char* sharedir; char *sharedir;
char* workdir; char *workdir;
uint32_t worker_id; uint32_t worker_id;
uint64_t cow_primary_size; uint64_t cow_primary_size;
char* redqueen_workdir; char *redqueen_workdir;
char* data_bar_fd_0; char *data_bar_fd_0;
char* data_bar_fd_1; char *data_bar_fd_1;
char* data_bar_fd_2; char *data_bar_fd_2;
char* bitmap_file; char *bitmap_file;
char* filter_bitmap[4]; char *filter_bitmap[4];
char* ip_filter[4][2]; char *ip_filter[4][2];
uint32_t bitmap_size; uint32_t bitmap_size;
uint32_t input_buffer_size; uint32_t input_buffer_size;
@ -97,41 +96,46 @@ typedef struct nyx_interface_state {
} nyx_interface_state; } nyx_interface_state;
static void nyx_interface_event(void *opaque, int event){ static void nyx_interface_event(void *opaque, int event)
{
} }
static void send_char(char val, void* tmp_s){ static void send_char(char val, void *tmp_s)
{
nyx_interface_state *s = tmp_s; nyx_interface_state *s = tmp_s;
assert(val == NYX_INTERFACE_PING); assert(val == NYX_INTERFACE_PING);
__sync_synchronize(); __sync_synchronize();
qemu_chr_fe_write(&s->chr, (const uint8_t *) &val, 1); qemu_chr_fe_write(&s->chr, (const uint8_t *)&val, 1);
} }
static int nyx_interface_can_receive(void * opaque){ static int nyx_interface_can_receive(void *opaque)
{
return sizeof(int64_t); return sizeof(int64_t);
} }
static nyx_interface_state* state = NULL; static nyx_interface_state *state = NULL;
static void init_send_char(nyx_interface_state* s){ static void init_send_char(nyx_interface_state *s)
{
state = s; state = s;
} }
bool interface_send_char(char val){ bool interface_send_char(char val)
{
if(state){ if (state) {
send_char(val, state); send_char(val, state);
return true; return true;
} }
return false; return false;
} }
static void nyx_interface_receive(void *opaque, const uint8_t * buf, int size){ static void nyx_interface_receive(void *opaque, const uint8_t *buf, int size)
{
int i; int i;
for(i = 0; i < size; i++){ for (i = 0; i < size; i++) {
switch(buf[i]){ switch (buf[i]) {
case NYX_INTERFACE_PING: case NYX_INTERFACE_PING:
synchronization_unlock(); synchronization_unlock();
break; break;
@ -146,15 +150,20 @@ static void nyx_interface_receive(void *opaque, const uint8_t * buf, int size){
} }
} }
static int nyx_create_payload_buffer(nyx_interface_state *s, uint64_t buffer_size, const char* file, Error **errp){ static int nyx_create_payload_buffer(nyx_interface_state *s,
void * ptr; uint64_t buffer_size,
const char *file,
Error **errp)
{
void *ptr;
int fd; int fd;
struct stat st; struct stat st;
fd = open(file, O_CREAT|O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO); fd = open(file, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
assert(ftruncate(fd, buffer_size) == 0); assert(ftruncate(fd, buffer_size) == 0);
stat(file, &st); stat(file, &st);
nyx_debug_p(INTERFACE_PREFIX, "new shm file: (max size: %lx) %lx", buffer_size, st.st_size); nyx_debug_p(INTERFACE_PREFIX, "new shm file: (max size: %lx) %lx", buffer_size,
st.st_size);
assert(buffer_size == st.st_size); assert(buffer_size == st.st_size);
ptr = mmap(0, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ptr = mmap(0, buffer_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
@ -172,46 +181,51 @@ static int nyx_create_payload_buffer(nyx_interface_state *s, uint64_t buffer_siz
return 0; return 0;
} }
static void nyx_guest_setup_bitmap(nyx_interface_state *s, char* filename, uint32_t bitmap_size){ static void nyx_guest_setup_bitmap(nyx_interface_state *s,
void * ptr; char *filename,
uint32_t bitmap_size)
{
void *ptr;
int fd; int fd;
struct stat st; struct stat st;
fd = open(filename, O_CREAT|O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO); fd = open(filename, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
assert(ftruncate(fd, bitmap_size) == 0); assert(ftruncate(fd, bitmap_size) == 0);
stat(filename, &st); stat(filename, &st);
assert(bitmap_size == st.st_size); assert(bitmap_size == st.st_size);
ptr = mmap(0, bitmap_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); ptr = mmap(0, bitmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
GET_GLOBAL_STATE()->shared_bitmap_ptr = (void*)ptr; GET_GLOBAL_STATE()->shared_bitmap_ptr = (void *)ptr;
GET_GLOBAL_STATE()->shared_bitmap_fd = fd; GET_GLOBAL_STATE()->shared_bitmap_fd = fd;
GET_GLOBAL_STATE()->shared_bitmap_size = bitmap_size; GET_GLOBAL_STATE()->shared_bitmap_size = bitmap_size;
GET_GLOBAL_STATE()->shared_bitmap_real_size = bitmap_size; GET_GLOBAL_STATE()->shared_bitmap_real_size = bitmap_size;
} }
static void nyx_guest_setup_ijon_buffer(nyx_interface_state *s, char* filename){ static void nyx_guest_setup_ijon_buffer(nyx_interface_state *s, char *filename)
void * ptr; {
void *ptr;
int fd; int fd;
struct stat st; struct stat st;
fd = open(filename, O_CREAT|O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO); fd = open(filename, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
assert(ftruncate(fd, DEFAULT_NYX_IJON_BITMAP_SIZE) == 0); assert(ftruncate(fd, DEFAULT_NYX_IJON_BITMAP_SIZE) == 0);
stat(filename, &st); stat(filename, &st);
assert(DEFAULT_NYX_IJON_BITMAP_SIZE == st.st_size); assert(DEFAULT_NYX_IJON_BITMAP_SIZE == st.st_size);
ptr = mmap(0, DEFAULT_NYX_IJON_BITMAP_SIZE, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); ptr = mmap(0, DEFAULT_NYX_IJON_BITMAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED,
fd, 0);
GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr = (void*)ptr; GET_GLOBAL_STATE()->shared_ijon_bitmap_ptr = (void *)ptr;
GET_GLOBAL_STATE()->shared_ijon_bitmap_fd = fd; GET_GLOBAL_STATE()->shared_ijon_bitmap_fd = fd;
GET_GLOBAL_STATE()->shared_ijon_bitmap_size = DEFAULT_NYX_IJON_BITMAP_SIZE; GET_GLOBAL_STATE()->shared_ijon_bitmap_size = DEFAULT_NYX_IJON_BITMAP_SIZE;
} }
static bool verify_workdir_state(nyx_interface_state *s, Error **errp){ static bool verify_workdir_state(nyx_interface_state *s, Error **errp)
{
char* workdir = s->workdir; char *workdir = s->workdir;
uint32_t id = s->worker_id; uint32_t id = s->worker_id;
char* tmp; char *tmp;
if (!folder_exits(workdir)){ if (!folder_exits(workdir)) {
nyx_error("Error: %s does not exist...\n", workdir); nyx_error("Error: %s does not exist...\n", workdir);
return false; return false;
} }
@ -219,13 +233,13 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
set_workdir_path(workdir); set_workdir_path(workdir);
assert(asprintf(&tmp, "%s/dump/", workdir) != -1); assert(asprintf(&tmp, "%s/dump/", workdir) != -1);
if (!folder_exits(tmp)){ if (!folder_exits(tmp)) {
mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); mkdir(tmp, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
} }
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/interface_%d", workdir, id) != -1); assert(asprintf(&tmp, "%s/interface_%d", workdir, id) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
@ -233,18 +247,17 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/payload_%d", workdir, id) != -1); assert(asprintf(&tmp, "%s/payload_%d", workdir, id) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
} } else {
else {
nyx_create_payload_buffer(s, s->input_buffer_size, tmp, errp); nyx_create_payload_buffer(s, s->input_buffer_size, tmp, errp);
} }
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/bitmap_%d", workdir, id) != -1); assert(asprintf(&tmp, "%s/bitmap_%d", workdir, id) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
@ -254,7 +267,7 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/ijon_%d", workdir, id) != -1); assert(asprintf(&tmp, "%s/ijon_%d", workdir, id) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
@ -264,7 +277,7 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/page_cache.lock", workdir) != -1); assert(asprintf(&tmp, "%s/page_cache.lock", workdir) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...", tmp); nyx_error("Error: %s does not exist...", tmp);
free(tmp); free(tmp);
return false; return false;
@ -272,7 +285,7 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/page_cache.addr", workdir) != -1); assert(asprintf(&tmp, "%s/page_cache.addr", workdir) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
@ -280,7 +293,7 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
free(tmp); free(tmp);
assert(asprintf(&tmp, "%s/page_cache.dump", workdir) != -1); assert(asprintf(&tmp, "%s/page_cache.dump", workdir) != -1);
if (!file_exits(tmp)){ if (!file_exits(tmp)) {
nyx_error("Error: %s does not exist...\n", tmp); nyx_error("Error: %s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
@ -291,25 +304,24 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
init_page_cache(tmp); init_page_cache(tmp);
assert(asprintf(&tmp, "%s/redqueen_workdir_%d/", workdir, id) != -1); assert(asprintf(&tmp, "%s/redqueen_workdir_%d/", workdir, id) != -1);
if (!folder_exits(tmp)){ if (!folder_exits(tmp)) {
nyx_error("%s does not exist...\n", tmp); nyx_error("%s does not exist...\n", tmp);
free(tmp); free(tmp);
return false; return false;
} } else {
else {
setup_redqueen_workdir(tmp); setup_redqueen_workdir(tmp);
} }
free(tmp); free(tmp);
init_redqueen_state(); init_redqueen_state();
if(s->dump_pt_trace){ if (s->dump_pt_trace) {
assert(asprintf(&tmp, "%s/pt_trace_dump_%d", workdir, id) != -1); assert(asprintf(&tmp, "%s/pt_trace_dump_%d", workdir, id) != -1);
pt_trace_dump_init(tmp); pt_trace_dump_init(tmp);
free(tmp); free(tmp);
} }
if(s->edge_cb_trace){ if (s->edge_cb_trace) {
redqueen_trace_init(); redqueen_trace_init();
} }
@ -324,24 +336,26 @@ static bool verify_workdir_state(nyx_interface_state *s, Error **errp){
#define KVM_VMX_PT_GET_ADDRN _IO(KVMIO, 0xe9) #define KVM_VMX_PT_GET_ADDRN _IO(KVMIO, 0xe9)
static void check_ipt_range(uint8_t i){ static void check_ipt_range(uint8_t i)
{
int ret = 0; int ret = 0;
int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC); int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
ret = ioctl(kvm, KVM_VMX_PT_GET_ADDRN, NULL); ret = ioctl(kvm, KVM_VMX_PT_GET_ADDRN, NULL);
if(ret == -1){ if (ret == -1) {
nyx_error("Error: Multi range tracing is not supported!\n"); nyx_error("Error: Multi range tracing is not supported!\n");
exit(1); exit(1);
} }
if(ret < (i+1)){ if (ret < (i + 1)) {
nyx_error("Error: CPU supports only %d IP filters!\n", ret); nyx_error("Error: CPU supports only %d IP filters!\n", ret);
exit(1); exit(1);
} }
close(kvm); close(kvm);
} }
static void check_available_ipt_ranges(nyx_interface_state* s){ static void check_available_ipt_ranges(nyx_interface_state *s)
{
uint64_t addr_a, addr_b; uint64_t addr_a, addr_b;
int kvm_fd = qemu_open("/dev/kvm", O_RDWR); int kvm_fd = qemu_open("/dev/kvm", O_RDWR);
@ -350,15 +364,17 @@ static void check_available_ipt_ranges(nyx_interface_state* s){
exit(1); exit(1);
} }
if (ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_PT) == 1 && ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_FDL) == 1) { if (ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_PT) == 1 &&
for(uint8_t i = 0; i < INTEL_PT_MAX_RANGES; i++){ ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_NYX_FDL) == 1)
if(s->ip_filter[i][0] && s->ip_filter[i][1]){ {
if(i >= 1){ for (uint8_t i = 0; i < INTEL_PT_MAX_RANGES; i++) {
if (s->ip_filter[i][0] && s->ip_filter[i][1]) {
if (i >= 1) {
check_ipt_range(i); check_ipt_range(i);
} }
addr_a = CONVERT_UINT64(s->ip_filter[i][0]); addr_a = CONVERT_UINT64(s->ip_filter[i][0]);
addr_b = CONVERT_UINT64(s->ip_filter[i][1]); addr_b = CONVERT_UINT64(s->ip_filter[i][1]);
if (addr_a < addr_b){ if (addr_a < addr_b) {
pt_setup_ip_filters(i, addr_a, addr_b); pt_setup_ip_filters(i, addr_a, addr_b);
} }
} }
@ -367,49 +383,51 @@ static void check_available_ipt_ranges(nyx_interface_state* s){
close(kvm_fd); close(kvm_fd);
} }
static bool verify_sharedir_state(nyx_interface_state *s, Error **errp){ static bool verify_sharedir_state(nyx_interface_state *s, Error **errp)
{
char *sharedir = s->sharedir;
char* sharedir = s->sharedir; if (!folder_exits(sharedir)) {
if (!folder_exits(sharedir)){
return false; return false;
} }
return true; return true;
} }
static void nyx_realize(DeviceState *dev, Error **errp){ static void nyx_realize(DeviceState *dev, Error **errp)
{
nyx_interface_state *s = NYX_MEM(dev); nyx_interface_state *s = NYX_MEM(dev);
if(s->bitmap_size <= 0){ if (s->bitmap_size <= 0) {
s->bitmap_size = DEFAULT_NYX_BITMAP_SIZE; s->bitmap_size = DEFAULT_NYX_BITMAP_SIZE;
} }
if(s->worker_id == 0xFFFF){ if (s->worker_id == 0xFFFF) {
nyx_error("Error: Invalid worker id...\n"); nyx_error("Error: Invalid worker id...\n");
exit(1); exit(1);
} }
if(s->cow_primary_size){ if (s->cow_primary_size) {
set_global_cow_cache_primary_size(s->cow_primary_size); set_global_cow_cache_primary_size(s->cow_primary_size);
} }
GET_GLOBAL_STATE()->worker_id = s->worker_id; GET_GLOBAL_STATE()->worker_id = s->worker_id;
if (!s->workdir || !verify_workdir_state(s, errp)){ if (!s->workdir || !verify_workdir_state(s, errp)) {
nyx_error("Error: Invalid work dir...\n"); nyx_error("Error: Invalid work dir...\n");
exit(1); exit(1);
} }
if (!s->sharedir || !verify_sharedir_state(s, errp)){ if (!s->sharedir || !verify_sharedir_state(s, errp)) {
nyx_error("Warning: Invalid sharedir...\n"); nyx_error("Warning: Invalid sharedir...\n");
} } else {
else{
sharedir_set_dir(GET_GLOBAL_STATE()->sharedir, s->sharedir); sharedir_set_dir(GET_GLOBAL_STATE()->sharedir, s->sharedir);
} }
if(&s->chr){ if (&s->chr) {
qemu_chr_fe_set_handlers(&s->chr, nyx_interface_can_receive, nyx_interface_receive, nyx_interface_event, NULL, s, NULL, true); qemu_chr_fe_set_handlers(&s->chr, nyx_interface_can_receive,
nyx_interface_receive, nyx_interface_event, NULL, s,
NULL, true);
} }
check_available_ipt_ranges(s); check_available_ipt_ranges(s);
@ -439,8 +457,14 @@ static Property nyx_interface_properties[] = {
DEFINE_PROP_STRING("ip3_b", nyx_interface_state, ip_filter[3][1]), DEFINE_PROP_STRING("ip3_b", nyx_interface_state, ip_filter[3][1]),
DEFINE_PROP_UINT32("bitmap_size", nyx_interface_state, bitmap_size, DEFAULT_NYX_BITMAP_SIZE), DEFINE_PROP_UINT32("bitmap_size",
DEFINE_PROP_UINT32("input_buffer_size", nyx_interface_state, input_buffer_size, DEFAULT_NYX_BITMAP_SIZE), nyx_interface_state,
bitmap_size,
DEFAULT_NYX_BITMAP_SIZE),
DEFINE_PROP_UINT32("input_buffer_size",
nyx_interface_state,
input_buffer_size,
DEFAULT_NYX_BITMAP_SIZE),
DEFINE_PROP_BOOL("dump_pt_trace", nyx_interface_state, dump_pt_trace, false), DEFINE_PROP_BOOL("dump_pt_trace", nyx_interface_state, dump_pt_trace, false),
DEFINE_PROP_BOOL("edge_cb_trace", nyx_interface_state, edge_cb_trace, false), DEFINE_PROP_BOOL("edge_cb_trace", nyx_interface_state, edge_cb_trace, false),
@ -448,7 +472,8 @@ static Property nyx_interface_properties[] = {
DEFINE_PROP_END_OF_LIST(), DEFINE_PROP_END_OF_LIST(),
}; };
static void nyx_interface_class_init(ObjectClass *klass, void *data){ static void nyx_interface_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass); DeviceClass *dc = DEVICE_CLASS(klass);
dc->realize = nyx_realize; dc->realize = nyx_realize;
dc->props = nyx_interface_properties; dc->props = nyx_interface_properties;
@ -456,7 +481,8 @@ static void nyx_interface_class_init(ObjectClass *klass, void *data){
dc->desc = "Nyx Interface"; dc->desc = "Nyx Interface";
} }
static void nyx_interface_init(Object *obj){ static void nyx_interface_init(Object *obj)
{
} }
static const TypeInfo nyx_interface_info = { static const TypeInfo nyx_interface_info = {
@ -467,7 +493,8 @@ static const TypeInfo nyx_interface_info = {
.class_init = nyx_interface_class_init, .class_init = nyx_interface_class_init,
}; };
static void nyx_interface_register_types(void){ static void nyx_interface_register_types(void)
{
type_register_static(&nyx_interface_info); type_register_static(&nyx_interface_info);
} }

View File

@ -1,13 +1,13 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <linux/kvm.h>
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
#include <linux/kvm.h>
#include "qemu-common.h"
#include "nyx/kvm_nested.h"
#include "cpu.h"
#include "nyx/debug.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h" #include "qemu/rcu_queue.h"
#include "qemu-common.h"
#include "cpu.h"
#include "nyx/debug.h"
#include "nyx/kvm_nested.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
#include "pt.h" #include "pt.h"
@ -20,12 +20,12 @@
#define SIGN_EXTEND_TRESHOLD 0x100 #define SIGN_EXTEND_TRESHOLD 0x100
#define SIGN_EXTEND 0xFFFF000000000000ULL #define SIGN_EXTEND 0xFFFF000000000000ULL
#define PAGETABLE_MASK 0xFFFFFFFFFF000ULL #define PAGETABLE_MASK 0xFFFFFFFFFF000ULL
#define CHECK_BIT(var,pos) !!(((var) & (1ULL<<(pos)))) #define CHECK_BIT(var, pos) !!(((var) & (1ULL << (pos))))
struct vmcs_hdr { struct vmcs_hdr {
uint32_t revision_id:31; uint32_t revision_id : 31;
uint32_t shadow_vmcs:1; uint32_t shadow_vmcs : 1;
}; };
struct __attribute__((__packed__)) vmcs12 { struct __attribute__((__packed__)) vmcs12 {
@ -193,82 +193,120 @@ struct __attribute__((__packed__)) vmcs12 {
}; };
static void write_address(uint64_t address, uint64_t size, uint64_t prot){ static void write_address(uint64_t address, uint64_t size, uint64_t prot)
{
static uint64_t next_address = PAGETABLE_MASK; static uint64_t next_address = PAGETABLE_MASK;
static uint64_t last_address = 0x0; static uint64_t last_address = 0x0;
static uint64_t last_prot = 0; static uint64_t last_prot = 0;
if(address != next_address || prot != last_prot){ if (address != next_address || prot != last_prot) {
/* do not print guard pages or empty pages without any permissions */ /* do not print guard pages or empty pages without any permissions */
if(last_address && (CHECK_BIT(last_prot, 1) || !CHECK_BIT(last_prot, 63))){ if (last_address && (CHECK_BIT(last_prot, 1) || !CHECK_BIT(last_prot, 63))) {
if(CHECK_BIT(last_prot, 1) && !CHECK_BIT(last_prot, 63)){ if (CHECK_BIT(last_prot, 1) && !CHECK_BIT(last_prot, 63)) {
nyx_debug_p(NESTED_VM_PREFIX, "%016lx - %016lx %c%c%c [WARNING]", nyx_debug_p(NESTED_VM_PREFIX, "%016lx - %016lx %c%c%c [WARNING]",
last_address, next_address, last_address, next_address,
CHECK_BIT(last_prot, 1) ? 'W' : '-', CHECK_BIT(last_prot, 1) ? 'W' : '-',
CHECK_BIT(last_prot, 2) ? 'U' : 'K', CHECK_BIT(last_prot, 2) ? 'U' : 'K',
!CHECK_BIT(last_prot, 63)? 'X' : '-'); !CHECK_BIT(last_prot, 63) ? 'X' : '-');
} } else {
else{ nyx_debug_p(NESTED_VM_PREFIX, "%016lx - %016lx %c%c%c", last_address,
nyx_debug_p(NESTED_VM_PREFIX, "%016lx - %016lx %c%c%c", next_address, CHECK_BIT(last_prot, 1) ? 'W' : '-',
last_address, next_address,
CHECK_BIT(last_prot, 1) ? 'W' : '-',
CHECK_BIT(last_prot, 2) ? 'U' : 'K', CHECK_BIT(last_prot, 2) ? 'U' : 'K',
!CHECK_BIT(last_prot, 63)? 'X' : '-'); !CHECK_BIT(last_prot, 63) ? 'X' : '-');
} }
} }
last_address = address; last_address = address;
} }
next_address = address+size; next_address = address + size;
last_prot = prot; last_prot = prot;
} }
void print_48_paging(uint64_t cr3){ void print_48_paging(uint64_t cr3)
{
uint64_t paging_entries_level_1[PENTRIES]; uint64_t paging_entries_level_1[PENTRIES];
uint64_t paging_entries_level_2[PENTRIES]; uint64_t paging_entries_level_2[PENTRIES];
uint64_t paging_entries_level_3[PENTRIES]; uint64_t paging_entries_level_3[PENTRIES];
uint64_t paging_entries_level_4[PENTRIES]; uint64_t paging_entries_level_4[PENTRIES];
uint64_t address_identifier_1, address_identifier_2, address_identifier_3, address_identifier_4; uint64_t address_identifier_1, address_identifier_2, address_identifier_3,
uint32_t i1, i2, i3,i4; address_identifier_4;
uint32_t i1, i2, i3, i4;
cpu_physical_memory_rw((cr3&PAGETABLE_MASK), (uint8_t *) paging_entries_level_1, PPAGE_SIZE, false); cpu_physical_memory_rw((cr3 & PAGETABLE_MASK), (uint8_t *)paging_entries_level_1,
for(i1 = 0; i1 < 512; i1++){ PPAGE_SIZE, false);
if(paging_entries_level_1[i1]){ for (i1 = 0; i1 < 512; i1++) {
if (paging_entries_level_1[i1]) {
address_identifier_1 = ((uint64_t)i1) << PLEVEL_1_SHIFT; address_identifier_1 = ((uint64_t)i1) << PLEVEL_1_SHIFT;
if (i1 & SIGN_EXTEND_TRESHOLD){ if (i1 & SIGN_EXTEND_TRESHOLD) {
address_identifier_1 |= SIGN_EXTEND; address_identifier_1 |= SIGN_EXTEND;
} }
if(CHECK_BIT(paging_entries_level_1[i1], 0)){ /* otherwise swapped out */ if (CHECK_BIT(paging_entries_level_1[i1], 0))
cpu_physical_memory_rw((paging_entries_level_1[i1]&PAGETABLE_MASK), (uint8_t *) paging_entries_level_2, PPAGE_SIZE, false); { /* otherwise swapped out */
for(i2 = 0; i2 < PENTRIES; i2++){ cpu_physical_memory_rw((paging_entries_level_1[i1] & PAGETABLE_MASK),
if(paging_entries_level_2[i2]){ (uint8_t *)paging_entries_level_2, PPAGE_SIZE,
address_identifier_2 = (((uint64_t)i2) << PLEVEL_2_SHIFT) + address_identifier_1; false);
if (CHECK_BIT(paging_entries_level_2[i2], 0)){ /* otherwise swapped out */ for (i2 = 0; i2 < PENTRIES; i2++) {
if((paging_entries_level_2[i2]&PAGETABLE_MASK) == (paging_entries_level_1[i1]&PAGETABLE_MASK)){ if (paging_entries_level_2[i2]) {
address_identifier_2 = (((uint64_t)i2) << PLEVEL_2_SHIFT) +
address_identifier_1;
if (CHECK_BIT(paging_entries_level_2[i2], 0))
{ /* otherwise swapped out */
if ((paging_entries_level_2[i2] & PAGETABLE_MASK) ==
(paging_entries_level_1[i1] & PAGETABLE_MASK))
{
/* loop */ /* loop */
continue; continue;
} }
if (CHECK_BIT(paging_entries_level_2[i2], 7)){ if (CHECK_BIT(paging_entries_level_2[i2], 7)) {
write_address(address_identifier_2, 0x40000000, (uint64_t)paging_entries_level_2[i2] & ((1ULL<<63) | (1ULL<<2) | (1ULL<<1))); write_address(address_identifier_2, 0x40000000,
} (uint64_t)paging_entries_level_2[i2] &
else{ ((1ULL << 63) | (1ULL << 2) |
(1ULL << 1)));
} else {
/* otherwise this PDPE references a 1GB page */ /* otherwise this PDPE references a 1GB page */
cpu_physical_memory_rw((paging_entries_level_2[i2]&PAGETABLE_MASK), (uint8_t *) paging_entries_level_3, PPAGE_SIZE, false); cpu_physical_memory_rw((paging_entries_level_2[i2] &
for(i3 = 0; i3 < PENTRIES; i3++){ PAGETABLE_MASK),
if(paging_entries_level_3[i3]){ (uint8_t *)paging_entries_level_3,
address_identifier_3 = (((uint64_t)i3) << PLEVEL_3_SHIFT) + address_identifier_2; PPAGE_SIZE, false);
if (CHECK_BIT(paging_entries_level_3[i3], 0)){ /* otherwise swapped out */ for (i3 = 0; i3 < PENTRIES; i3++) {
if (CHECK_BIT(paging_entries_level_3[i3], 7)){ if (paging_entries_level_3[i3]) {
write_address(address_identifier_3, 0x200000, (uint64_t)paging_entries_level_3[i3] & ((1ULL<<63) | (1ULL<<2) | (1ULL<<1))); address_identifier_3 =
} (((uint64_t)i3) << PLEVEL_3_SHIFT) +
else{ address_identifier_2;
cpu_physical_memory_rw((paging_entries_level_3[i3]&PAGETABLE_MASK), (uint8_t *) paging_entries_level_4, PPAGE_SIZE, false); if (CHECK_BIT(paging_entries_level_3[i3], 0))
for(i4 = 0; i4 < PENTRIES; i4++){ { /* otherwise swapped out */
if(paging_entries_level_4[i4]){ if (CHECK_BIT(paging_entries_level_3[i3],
address_identifier_4 = (((uint64_t)i4) << PLEVEL_4_SHIFT) + address_identifier_3; 7))
if (CHECK_BIT(paging_entries_level_4[i4], 0)){ {
write_address(address_identifier_4, 0x1000, (uint64_t)paging_entries_level_4[i4] & ((1ULL<<63) | (1ULL<<2) | (1ULL<<1))); write_address(
address_identifier_3, 0x200000,
(uint64_t)paging_entries_level_3[i3] &
((1ULL << 63) | (1ULL << 2) |
(1ULL << 1)));
} else {
cpu_physical_memory_rw(
(paging_entries_level_3[i3] &
PAGETABLE_MASK),
(uint8_t *)paging_entries_level_4,
PPAGE_SIZE, false);
for (i4 = 0; i4 < PENTRIES; i4++) {
if (paging_entries_level_4[i4]) {
address_identifier_4 =
(((uint64_t)i4)
<< PLEVEL_4_SHIFT) +
address_identifier_3;
if (CHECK_BIT(
paging_entries_level_4[i4],
0))
{
write_address(
address_identifier_4,
0x1000,
(uint64_t)paging_entries_level_4
[i4] &
((1ULL << 63) |
(1ULL << 2) |
(1ULL << 1)));
} }
} }
} }
@ -276,7 +314,6 @@ void print_48_paging(uint64_t cr3){
} }
} }
} }
} }
} }
} }
@ -287,60 +324,62 @@ void print_48_paging(uint64_t cr3){
write_address(0, 0x1000, 0); write_address(0, 0x1000, 0);
} }
uint64_t get_nested_guest_rip(CPUState *cpu){ uint64_t get_nested_guest_rip(CPUState *cpu)
{
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state); kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state);
struct vmcs12* saved_vmcs = (struct vmcs12*)&(env->nested_state->data); struct vmcs12 *saved_vmcs = (struct vmcs12 *)&(env->nested_state->data);
return saved_vmcs->guest_rip; return saved_vmcs->guest_rip;
} }
uint64_t get_nested_host_rip(CPUState *cpu){ uint64_t get_nested_host_rip(CPUState *cpu)
{
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state); kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state);
struct vmcs12* saved_vmcs = (struct vmcs12*)&(env->nested_state->data); struct vmcs12 *saved_vmcs = (struct vmcs12 *)&(env->nested_state->data);
return saved_vmcs->host_rip; return saved_vmcs->host_rip;
} }
uint64_t get_nested_host_cr3(CPUState *cpu){ uint64_t get_nested_host_cr3(CPUState *cpu)
{
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state); kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state);
struct vmcs12* saved_vmcs = (struct vmcs12*)&(env->nested_state->data); struct vmcs12 *saved_vmcs = (struct vmcs12 *)&(env->nested_state->data);
return saved_vmcs->host_cr3; return saved_vmcs->host_cr3;
} }
void set_nested_rip(CPUState *cpu, uint64_t rip){ void set_nested_rip(CPUState *cpu, uint64_t rip)
{
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
struct vmcs12* saved_vmcs = (struct vmcs12*)&(env->nested_state->data); struct vmcs12 *saved_vmcs = (struct vmcs12 *)&(env->nested_state->data);
saved_vmcs->guest_rip = rip; saved_vmcs->guest_rip = rip;
} }
void kvm_nested_get_info(CPUState *cpu){ void kvm_nested_get_info(CPUState *cpu)
{
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
CPUX86State *env = &cpux86->env; CPUX86State *env = &cpux86->env;
kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state); kvm_vcpu_ioctl(cpu, KVM_GET_NESTED_STATE, env->nested_state);
__attribute__((unused)) struct vmcs12* saved_vmcs = (struct vmcs12*)&(env->nested_state->data); __attribute__((unused)) struct vmcs12 *saved_vmcs =
(struct vmcs12 *)&(env->nested_state->data);
nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr3:\t%lx", saved_vmcs->host_cr3); nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr3:\t%lx", saved_vmcs->host_cr3);
nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr4:\t%lx", saved_vmcs->host_cr4); nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr4:\t%lx", saved_vmcs->host_cr4);
nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_ia32_efer:\t%lx", saved_vmcs->host_ia32_efer); nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_ia32_efer:\t%lx",
saved_vmcs->host_ia32_efer);
nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr0:\t%lx", saved_vmcs->host_cr0); nyx_debug_p(NESTED_VM_PREFIX, "VMCS host_cr0:\t%lx", saved_vmcs->host_cr0);
return; return;
@ -354,7 +393,7 @@ typedef struct {
uint32_t size; uint32_t size;
uint32_t virtual_base; uint32_t virtual_base;
char desc[AREA_DESC_LEN]; char desc[AREA_DESC_LEN];
}area_t_export_t; } area_t_export_t;
typedef struct { typedef struct {
uint32_t magic; uint32_t magic;
@ -362,29 +401,39 @@ typedef struct {
uint8_t num_io_areas; uint8_t num_io_areas;
uint8_t num_alloc_areas; uint8_t num_alloc_areas;
uint8_t padding; uint8_t padding;
}config_t; } config_t;
void print_configuration(FILE *stream, void* configuration, size_t size){ void print_configuration(FILE *stream, void *configuration, size_t size)
{
fprintf(stream, "%s: size: %lx\n", __func__, size); fprintf(stream, "%s: size: %lx\n", __func__, size);
assert((size-sizeof(config_t))%sizeof(area_t_export_t) == 0); assert((size - sizeof(config_t)) % sizeof(area_t_export_t) == 0);
assert(((config_t*)configuration)->magic == MAGIC_NUMBER); assert(((config_t *)configuration)->magic == MAGIC_NUMBER);
fprintf(stream, "%s: num_mmio_areas: %x\n", __func__, ((config_t*)configuration)->num_mmio_areas); fprintf(stream, "%s: num_mmio_areas: %x\n", __func__,
fprintf(stream, "%s: num_io_areas: %x\n", __func__, ((config_t*)configuration)->num_io_areas); ((config_t *)configuration)->num_mmio_areas);
fprintf(stream, "%s: num_alloc_areas: %x\n", __func__, ((config_t*)configuration)->num_alloc_areas); fprintf(stream, "%s: num_io_areas: %x\n", __func__,
((config_t *)configuration)->num_io_areas);
fprintf(stream, "%s: num_alloc_areas: %x\n", __func__,
((config_t *)configuration)->num_alloc_areas);
for(int i = 0; i < ((config_t*)configuration)->num_mmio_areas; i++){ for (int i = 0; i < ((config_t *)configuration)->num_mmio_areas; i++) {
fprintf(stream, "\t-> MMIO: 0x%x (V: 0x%x) [0x%x]\t%s\n", ((area_t_export_t*)(configuration+sizeof(config_t)))[i].base, fprintf(stream, "\t-> MMIO: 0x%x (V: 0x%x) [0x%x]\t%s\n",
((area_t_export_t*)(configuration+sizeof(config_t)))[i].virtual_base, ((area_t_export_t *)(configuration + sizeof(config_t)))[i].base,
((area_t_export_t*)(configuration+sizeof(config_t)))[i].size, ((area_t_export_t *)(configuration + sizeof(config_t)))[i].virtual_base,
((area_t_export_t*)(configuration+sizeof(config_t)))[i].desc ); ((area_t_export_t *)(configuration + sizeof(config_t)))[i].size,
((area_t_export_t *)(configuration + sizeof(config_t)))[i].desc);
} }
for(int i = ((config_t*)configuration)->num_mmio_areas; i < (((config_t*)configuration)->num_mmio_areas+((config_t*)configuration)->num_io_areas); i++){ for (int i = ((config_t *)configuration)->num_mmio_areas;
fprintf(stream, "\t-> IO: 0x%x [0x%x]\t%s\n", ((area_t_export_t*)(configuration+sizeof(config_t)))[i].base, i < (((config_t *)configuration)->num_mmio_areas +
((area_t_export_t*)(configuration+sizeof(config_t)))[i].size, ((config_t *)configuration)->num_io_areas);
((area_t_export_t*)(configuration+sizeof(config_t)))[i].desc ); i++)
{
fprintf(stream, "\t-> IO: 0x%x [0x%x]\t%s\n",
((area_t_export_t *)(configuration + sizeof(config_t)))[i].base,
((area_t_export_t *)(configuration + sizeof(config_t)))[i].size,
((area_t_export_t *)(configuration + sizeof(config_t)))[i].desc);
} }
} }

View File

@ -10,4 +10,4 @@ uint64_t get_nested_host_rip(CPUState *cpu);
uint64_t get_nested_host_cr3(CPUState *cpu); uint64_t get_nested_host_cr3(CPUState *cpu);
void set_nested_rip(CPUState *cpu, uint64_t rip); void set_nested_rip(CPUState *cpu, uint64_t rip);
void print_configuration(FILE *stream, void* configuration, size_t size); void print_configuration(FILE *stream, void *configuration, size_t size);

View File

@ -20,29 +20,32 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <errno.h>
#include "exec/gdbstub.h" #include "exec/gdbstub.h"
#include <errno.h>
#include "sysemu/sysemu.h"
#include "cpu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h" #include "qemu/rcu_queue.h"
#include "sysemu/sysemu.h"
#include "cpu.h"
#include "memory_access.h"
#include "nyx/hypercall/hypercall.h"
#include "debug.h" #include "debug.h"
#include "memory_access.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/state/state.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "nyx/hypercall/hypercall.h"
#include "nyx/state/state.h"
#define INVALID_ADDRESS 0xFFFFFFFFFFFFFFFFULL #define INVALID_ADDRESS 0xFFFFFFFFFFFFFFFFULL
static uint64_t get_48_paging_phys_addr(uint64_t cr3, uint64_t addr, bool read_from_snapshot); static uint64_t get_48_paging_phys_addr(uint64_t cr3,
uint64_t addr,
bool read_from_snapshot);
#define x86_64_PAGE_SIZE 0x1000 #define x86_64_PAGE_SIZE 0x1000
#define x86_64_PAGE_MASK ~(x86_64_PAGE_SIZE - 1) #define x86_64_PAGE_MASK ~(x86_64_PAGE_SIZE - 1)
mem_mode_t get_current_mem_mode(CPUState *cpu){ mem_mode_t get_current_mem_mode(CPUState *cpu)
{
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
X86CPU *cpux86 = X86_CPU(cpu); X86CPU *cpux86 = X86_CPU(cpu);
@ -50,8 +53,7 @@ mem_mode_t get_current_mem_mode(CPUState *cpu){
if (!(env->cr[0] & CR0_PG_MASK)) { if (!(env->cr[0] & CR0_PG_MASK)) {
return mm_32_protected; return mm_32_protected;
} } else {
else{
if (env->cr[4] & CR4_PAE_MASK) { if (env->cr[4] & CR4_PAE_MASK) {
if (env->hflags & HF_LMA_MASK) { if (env->hflags & HF_LMA_MASK) {
if (env->cr[4] & CR4_LA57_MASK) { if (env->cr[4] & CR4_LA57_MASK) {
@ -59,12 +61,10 @@ mem_mode_t get_current_mem_mode(CPUState *cpu){
} else { } else {
return mm_64_l4_paging; return mm_64_l4_paging;
} }
} } else {
else{
return mm_32_pae; return mm_32_pae;
} }
} } else {
else {
return mm_32_paging; return mm_32_paging;
} }
} }
@ -72,17 +72,19 @@ mem_mode_t get_current_mem_mode(CPUState *cpu){
return mm_unkown; return mm_unkown;
} }
static void set_mem_mode(CPUState *cpu){ static void set_mem_mode(CPUState *cpu)
{
GET_GLOBAL_STATE()->mem_mode = get_current_mem_mode(cpu); GET_GLOBAL_STATE()->mem_mode = get_current_mem_mode(cpu);
} }
/* Warning: This might break memory handling for hypervisor fuzzing => FIXME LATER */ /* Warning: This might break memory handling for hypervisor fuzzing => FIXME LATER */
uint64_t get_paging_phys_addr(CPUState *cpu, uint64_t cr3, uint64_t addr){ uint64_t get_paging_phys_addr(CPUState *cpu, uint64_t cr3, uint64_t addr)
if(GET_GLOBAL_STATE()->mem_mode == mm_unkown){ {
if (GET_GLOBAL_STATE()->mem_mode == mm_unkown) {
set_mem_mode(cpu); set_mem_mode(cpu);
} }
switch(GET_GLOBAL_STATE()->mem_mode){ switch (GET_GLOBAL_STATE()->mem_mode) {
case mm_32_protected: case mm_32_protected:
return addr & 0xFFFFFFFFULL; return addr & 0xFFFFFFFFULL;
case mm_32_paging: case mm_32_paging:
@ -103,12 +105,13 @@ uint64_t get_paging_phys_addr(CPUState *cpu, uint64_t cr3, uint64_t addr){
return 0; return 0;
} }
static uint64_t get_paging_phys_addr_snapshot(CPUState *cpu, uint64_t cr3, uint64_t addr){ static uint64_t get_paging_phys_addr_snapshot(CPUState *cpu, uint64_t cr3, uint64_t addr)
if(GET_GLOBAL_STATE()->mem_mode == mm_unkown){ {
if (GET_GLOBAL_STATE()->mem_mode == mm_unkown) {
set_mem_mode(cpu); set_mem_mode(cpu);
} }
switch(GET_GLOBAL_STATE()->mem_mode){ switch (GET_GLOBAL_STATE()->mem_mode) {
case mm_32_protected: case mm_32_protected:
return addr & 0xFFFFFFFFULL; return addr & 0xFFFFFFFFULL;
case mm_32_paging: case mm_32_paging:
@ -129,43 +132,52 @@ static uint64_t get_paging_phys_addr_snapshot(CPUState *cpu, uint64_t cr3, uint6
return 0; return 0;
} }
bool read_physical_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu){ bool read_physical_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu)
{
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
cpu_physical_memory_read(address, data, size); cpu_physical_memory_read(address, data, size);
return true; return true;
} }
bool write_physical_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu){ bool write_physical_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu)
{
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
cpu_physical_memory_write(address, data, size); cpu_physical_memory_write(address, data, size);
return true; return true;
} }
static void refresh_kvm(CPUState *cpu){ static void refresh_kvm(CPUState *cpu)
{
if (!cpu->vcpu_dirty) { if (!cpu->vcpu_dirty) {
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
} }
} }
static void refresh_kvm_non_dirty(CPUState *cpu){ static void refresh_kvm_non_dirty(CPUState *cpu)
{
if (!cpu->vcpu_dirty) { if (!cpu->vcpu_dirty) {
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
} }
} }
bool remap_payload_slot(uint64_t phys_addr, uint32_t slot, CPUState *cpu){ bool remap_payload_slot(uint64_t phys_addr, uint32_t slot, CPUState *cpu)
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd && GET_GLOBAL_STATE()->shared_payload_buffer_size); {
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd &&
GET_GLOBAL_STATE()->shared_payload_buffer_size);
RAMBlock *block; RAMBlock *block;
refresh_kvm_non_dirty(cpu); refresh_kvm_non_dirty(cpu);
uint32_t i = slot; uint32_t i = slot;
uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr); uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr);
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
if(!memcmp(block->idstr, "pc.ram", 6)){ if (!memcmp(block->idstr, "pc.ram", 6)) {
/* TODO: put assert calls here */ /* TODO: put assert calls here */
munmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), x86_64_PAGE_SIZE); munmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
mmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, GET_GLOBAL_STATE()->shared_payload_buffer_fd, (i*x86_64_PAGE_SIZE)); x86_64_PAGE_SIZE);
mmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000,
PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED,
GET_GLOBAL_STATE()->shared_payload_buffer_fd, (i * x86_64_PAGE_SIZE));
fast_reload_blacklist_page(get_fast_reload_snapshot(), phys_addr); fast_reload_blacklist_page(get_fast_reload_snapshot(), phys_addr);
break; break;
@ -175,9 +187,16 @@ bool remap_payload_slot(uint64_t phys_addr, uint32_t slot, CPUState *cpu){
return true; return true;
} }
bool remap_slot(uint64_t addr, uint32_t slot, CPUState *cpu, int fd, uint64_t shm_size, bool virtual, uint64_t cr3){ bool remap_slot(uint64_t addr,
uint32_t slot,
CPUState *cpu,
int fd,
uint64_t shm_size,
bool virtual,
uint64_t cr3)
{
assert(fd && shm_size); assert(fd && shm_size);
assert((slot*x86_64_PAGE_SIZE) < shm_size); assert((slot * x86_64_PAGE_SIZE) < shm_size);
RAMBlock *block; RAMBlock *block;
refresh_kvm_non_dirty(cpu); refresh_kvm_non_dirty(cpu);
@ -185,12 +204,14 @@ bool remap_slot(uint64_t addr, uint32_t slot, CPUState *cpu, int fd, uint64_t sh
uint32_t i = slot; uint32_t i = slot;
uint64_t phys_addr = addr; uint64_t phys_addr = addr;
if(virtual){ if (virtual) {
phys_addr = get_paging_phys_addr(cpu, cr3, (addr & x86_64_PAGE_MASK)); phys_addr = get_paging_phys_addr(cpu, cr3, (addr & x86_64_PAGE_MASK));
if(phys_addr == INVALID_ADDRESS){ if (phys_addr == INVALID_ADDRESS) {
fprintf(stderr, "[QEMU-Nyx] Error: failed to translate v_addr (0x%lx) to p_addr!\n", addr); fprintf(stderr, "[QEMU-Nyx] Error: failed to translate v_addr (0x%lx) to p_addr!\n",
fprintf(stderr, "[QEMU-Nyx] Check if the buffer is present in the guest's memory...\n"); addr);
fprintf(stderr, "[QEMU-Nyx] Check if the buffer is present in the "
"guest's memory...\n");
exit(1); exit(1);
} }
} }
@ -198,14 +219,19 @@ bool remap_slot(uint64_t addr, uint32_t slot, CPUState *cpu, int fd, uint64_t sh
nyx_debug("%s: addr => %lx phys_addr => %lx\n", __func__, addr, phys_addr); nyx_debug("%s: addr => %lx phys_addr => %lx\n", __func__, addr, phys_addr);
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
if(!memcmp(block->idstr, "pc.ram", 6)){ if (!memcmp(block->idstr, "pc.ram", 6)) {
/* TODO: put assert calls here */ /* TODO: put assert calls here */
if (munmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), x86_64_PAGE_SIZE) == -1) { if (munmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
x86_64_PAGE_SIZE) == -1)
{
nyx_error("%s: munmap failed!\n", __func__); nyx_error("%s: munmap failed!\n", __func__);
assert(false); assert(false);
} }
if (mmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd, (i*x86_64_PAGE_SIZE)) == MAP_FAILED) { if (mmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, fd,
(i * x86_64_PAGE_SIZE)) == MAP_FAILED)
{
nyx_error("%s: mmap failed!\n", __func__); nyx_error("%s: mmap failed!\n", __func__);
assert(false); assert(false);
} }
@ -218,8 +244,10 @@ bool remap_slot(uint64_t addr, uint32_t slot, CPUState *cpu, int fd, uint64_t sh
return true; return true;
} }
bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *cpu){ bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *cpu)
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd && GET_GLOBAL_STATE()->shared_payload_buffer_size); {
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd &&
GET_GLOBAL_STATE()->shared_payload_buffer_size);
RAMBlock *block; RAMBlock *block;
refresh_kvm_non_dirty(cpu); refresh_kvm_non_dirty(cpu);
@ -227,12 +255,14 @@ bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *c
uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr); uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr);
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
if(!memcmp(block->idstr, "pc.ram", 6)){ if (!memcmp(block->idstr, "pc.ram", 6)) {
/* TODO: put assert calls here */ /* TODO: put assert calls here */
munmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), x86_64_PAGE_SIZE); munmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
mmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000, PROT_READ , MAP_SHARED | MAP_FIXED, GET_GLOBAL_STATE()->shared_payload_buffer_fd, (i*x86_64_PAGE_SIZE)); x86_64_PAGE_SIZE);
mmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000,
PROT_READ, MAP_SHARED | MAP_FIXED,
GET_GLOBAL_STATE()->shared_payload_buffer_fd, (i * x86_64_PAGE_SIZE));
fast_reload_blacklist_page(get_fast_reload_snapshot(), phys_addr); fast_reload_blacklist_page(get_fast_reload_snapshot(), phys_addr);
break; break;
@ -242,15 +272,16 @@ bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *c
return true; return true;
} }
void resize_shared_memory(uint32_t new_size, uint32_t* shm_size, void** shm_ptr, int fd){ void resize_shared_memory(uint32_t new_size, uint32_t *shm_size, void **shm_ptr, int fd)
{
assert(fd && *shm_size); assert(fd && *shm_size);
/* check if the new_size is a multiple of PAGE_SIZE */ /* check if the new_size is a multiple of PAGE_SIZE */
if(new_size & (PAGE_SIZE-1)){ if (new_size & (PAGE_SIZE - 1)) {
new_size = (new_size & ~(PAGE_SIZE-1)) + PAGE_SIZE; new_size = (new_size & ~(PAGE_SIZE - 1)) + PAGE_SIZE;
} }
if(*shm_size >= new_size){ if (*shm_size >= new_size) {
/* no need no resize the buffer -> early exit */ /* no need no resize the buffer -> early exit */
return; return;
} }
@ -258,42 +289,56 @@ void resize_shared_memory(uint32_t new_size, uint32_t* shm_size, void** shm_ptr,
assert(!GET_GLOBAL_STATE()->in_fuzzing_mode); assert(!GET_GLOBAL_STATE()->in_fuzzing_mode);
assert(ftruncate(fd, new_size) == 0); assert(ftruncate(fd, new_size) == 0);
if(shm_ptr){ if (shm_ptr) {
munmap(*shm_ptr , *shm_size); munmap(*shm_ptr, *shm_size);
*shm_ptr = (void*)mmap(0, new_size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); *shm_ptr =
(void *)mmap(0, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
assert(*shm_ptr != MAP_FAILED); assert(*shm_ptr != MAP_FAILED);
} }
*shm_size = new_size; *shm_size = new_size;
} }
bool remap_payload_buffer(uint64_t virt_guest_addr, CPUState *cpu){ bool remap_payload_buffer(uint64_t virt_guest_addr, CPUState *cpu)
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd && GET_GLOBAL_STATE()->shared_payload_buffer_size); {
assert(GET_GLOBAL_STATE()->shared_payload_buffer_fd &&
GET_GLOBAL_STATE()->shared_payload_buffer_size);
assert(GET_GLOBAL_STATE()->shared_payload_buffer_size % x86_64_PAGE_SIZE == 0); assert(GET_GLOBAL_STATE()->shared_payload_buffer_size % x86_64_PAGE_SIZE == 0);
RAMBlock *block; RAMBlock *block;
refresh_kvm_non_dirty(cpu); refresh_kvm_non_dirty(cpu);
for(uint32_t i = 0; i < (GET_GLOBAL_STATE()->shared_payload_buffer_size/x86_64_PAGE_SIZE); i++){ for (uint32_t i = 0;
uint64_t phys_addr = get_paging_phys_addr(cpu, GET_GLOBAL_STATE()->parent_cr3, ((virt_guest_addr+(i*x86_64_PAGE_SIZE)) & x86_64_PAGE_MASK)); i < (GET_GLOBAL_STATE()->shared_payload_buffer_size / x86_64_PAGE_SIZE); i++)
{
uint64_t phys_addr =
get_paging_phys_addr(cpu, GET_GLOBAL_STATE()->parent_cr3,
((virt_guest_addr + (i * x86_64_PAGE_SIZE)) &
x86_64_PAGE_MASK));
assert(phys_addr != INVALID_ADDRESS); assert(phys_addr != INVALID_ADDRESS);
uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr); uint64_t phys_addr_ram_offset = address_to_ram_offset(phys_addr);
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
if(!memcmp(block->idstr, "pc.ram", 6)){ if (!memcmp(block->idstr, "pc.ram", 6)) {
if(munmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), x86_64_PAGE_SIZE) == -1){ if (munmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
x86_64_PAGE_SIZE) == -1)
{
nyx_error("munmap failed!\n"); nyx_error("munmap failed!\n");
assert(false); assert(false);
} }
if(mmap((void*)(((uint64_t)block->host) + phys_addr_ram_offset), 0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, GET_GLOBAL_STATE()->shared_payload_buffer_fd, (i*x86_64_PAGE_SIZE)) == MAP_FAILED){ if (mmap((void *)(((uint64_t)block->host) + phys_addr_ram_offset),
0x1000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED,
GET_GLOBAL_STATE()->shared_payload_buffer_fd,
(i * x86_64_PAGE_SIZE)) == MAP_FAILED)
{
nyx_error("mmap failed!\n"); nyx_error("mmap failed!\n");
assert(false); assert(false);
} }
memset((block->host) + phys_addr_ram_offset, 0xab, 0x1000); memset((block->host) + phys_addr_ram_offset, 0xab, 0x1000);
if(GET_GLOBAL_STATE()->protect_payload_buffer){ if (GET_GLOBAL_STATE()->protect_payload_buffer) {
mprotect((block->host) + phys_addr_ram_offset, 0x1000, PROT_READ); mprotect((block->host) + phys_addr_ram_offset, 0x1000, PROT_READ);
} }
@ -305,7 +350,7 @@ bool remap_payload_buffer(uint64_t virt_guest_addr, CPUState *cpu){
return true; return true;
} }
bool write_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu) bool write_virtual_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu)
{ {
/* TODO: later &address_space_memory + phys_addr -> mmap SHARED */ /* TODO: later &address_space_memory + phys_addr -> mmap SHARED */
int asidx; int asidx;
@ -316,7 +361,7 @@ bool write_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUSta
uint64_t counter, l, i; uint64_t counter, l, i;
counter = size; counter = size;
while(counter != 0){ while (counter != 0) {
l = x86_64_PAGE_SIZE; l = x86_64_PAGE_SIZE;
if (l > counter) if (l > counter)
l = counter; l = counter;
@ -324,16 +369,18 @@ bool write_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUSta
refresh_kvm(cpu); refresh_kvm(cpu);
asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED); asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED);
attrs = MEMTXATTRS_UNSPECIFIED; attrs = MEMTXATTRS_UNSPECIFIED;
phys_addr = cpu_get_phys_page_attrs_debug(cpu, (address & x86_64_PAGE_MASK), &attrs); phys_addr =
cpu_get_phys_page_attrs_debug(cpu, (address & x86_64_PAGE_MASK), &attrs);
if (phys_addr == INVALID_ADDRESS){ if (phys_addr == INVALID_ADDRESS) {
nyx_debug_p(MEM_PREFIX, "phys_addr == -1:\t%lx", address); nyx_debug_p(MEM_PREFIX, "phys_addr == -1:\t%lx", address);
return false; return false;
} }
phys_addr += (address & ~x86_64_PAGE_MASK); phys_addr += (address & ~x86_64_PAGE_MASK);
res = address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, data, l, true); res = address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr,
if (res != MEMTX_OK){ MEMTXATTRS_UNSPECIFIED, data, l, true);
if (res != MEMTX_OK) {
nyx_debug_p(MEM_PREFIX, "!MEMTX_OK:\t%lx", address); nyx_debug_p(MEM_PREFIX, "!MEMTX_OK:\t%lx", address);
return false; return false;
} }
@ -348,22 +395,23 @@ bool write_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUSta
} }
void hexdump_virtual_memory(uint64_t address, uint32_t size, CPUState *cpu){ void hexdump_virtual_memory(uint64_t address, uint32_t size, CPUState *cpu)
{
assert(size < 0x100000); // 1MB max assert(size < 0x100000); // 1MB max
uint64_t i = 0; uint64_t i = 0;
uint8_t tmp[17]; uint8_t tmp[17];
uint8_t* data = malloc(size); uint8_t *data = malloc(size);
bool success = read_virtual_memory(address, data, size, cpu); bool success = read_virtual_memory(address, data, size, cpu);
if(success){ if (success) {
for (i = 0; i < size; i++){ for (i = 0; i < size; i++) {
if(!(i % 16)){ if (!(i % 16)) {
if (i != 0){ if (i != 0) {
printf (" %s\n", tmp); printf(" %s\n", tmp);
} }
printf (" %04lx ", i); printf(" %04lx ", i);
} }
printf (" %02x", data[i]); printf(" %02x", data[i]);
if ((data[i] < 0x20) || (data[i] > 0x7e)) if ((data[i] < 0x20) || (data[i] > 0x7e))
tmp[i % 16] = '.'; tmp[i % 16] = '.';
@ -373,10 +421,10 @@ void hexdump_virtual_memory(uint64_t address, uint32_t size, CPUState *cpu){
} }
while ((i % 16) != 0) { while ((i % 16) != 0) {
printf (" "); printf(" ");
i++; i++;
} }
printf (" %s\n", tmp); printf(" %s\n", tmp);
} }
free(data); free(data);
@ -387,12 +435,16 @@ static int redqueen_insert_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint
{ {
static const uint8_t int3 = 0xcc; static const uint8_t int3 = 0xcc;
hwaddr phys_addr = (hwaddr) get_paging_phys_addr(cs, GET_GLOBAL_STATE()->parent_cr3, bp->pc); hwaddr phys_addr =
(hwaddr)get_paging_phys_addr(cs, GET_GLOBAL_STATE()->parent_cr3, bp->pc);
int asidx = cpu_asidx_from_attrs(cs, MEMTXATTRS_UNSPECIFIED); int asidx = cpu_asidx_from_attrs(cs, MEMTXATTRS_UNSPECIFIED);
if (address_space_rw(cpu_get_address_space(cs, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, (uint8_t *)&bp->saved_insn, 1, 0) || if (address_space_rw(cpu_get_address_space(cs, asidx), phys_addr,
address_space_rw(cpu_get_address_space(cs, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, (uint8_t *)&int3, 1, 1)) { MEMTXATTRS_UNSPECIFIED, (uint8_t *)&bp->saved_insn, 1, 0) ||
//fprintf(stderr, "%s WRITTE AT %lx %lx failed!\n", __func__, bp->pc, phys_addr); address_space_rw(cpu_get_address_space(cs, asidx), phys_addr,
MEMTXATTRS_UNSPECIFIED, (uint8_t *)&int3, 1, 1))
{
// fprintf(stderr, "%s WRITTE AT %lx %lx failed!\n", __func__, bp->pc, phys_addr);
return -EINVAL; return -EINVAL;
} }
@ -403,22 +455,29 @@ static int redqueen_remove_sw_breakpoint(CPUState *cs, struct kvm_sw_breakpoint
{ {
uint8_t int3; uint8_t int3;
hwaddr phys_addr = (hwaddr) get_paging_phys_addr(cs, GET_GLOBAL_STATE()->parent_cr3, bp->pc); hwaddr phys_addr =
(hwaddr)get_paging_phys_addr(cs, GET_GLOBAL_STATE()->parent_cr3, bp->pc);
int asidx = cpu_asidx_from_attrs(cs, MEMTXATTRS_UNSPECIFIED); int asidx = cpu_asidx_from_attrs(cs, MEMTXATTRS_UNSPECIFIED);
if (address_space_rw(cpu_get_address_space(cs, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, (uint8_t *)&int3, 1, 0) || int3 != 0xcc || if (address_space_rw(cpu_get_address_space(cs, asidx), phys_addr,
address_space_rw(cpu_get_address_space(cs, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, (uint8_t *)&bp->saved_insn, 1, 1)) { MEMTXATTRS_UNSPECIFIED, (uint8_t *)&int3, 1, 0) ||
//fprintf(stderr, "%s failed\n", __func__); int3 != 0xcc ||
address_space_rw(cpu_get_address_space(cs, asidx), phys_addr,
MEMTXATTRS_UNSPECIFIED, (uint8_t *)&bp->saved_insn, 1, 1))
{
// fprintf(stderr, "%s failed\n", __func__);
return -EINVAL; return -EINVAL;
} }
return 0; return 0;
} }
static struct kvm_sw_breakpoint *redqueen_find_breakpoint(CPUState *cpu, target_ulong pc){ static struct kvm_sw_breakpoint *redqueen_find_breakpoint(CPUState *cpu,
target_ulong pc)
{
struct kvm_sw_breakpoint *bp; struct kvm_sw_breakpoint *bp;
QTAILQ_FOREACH(bp, &GET_GLOBAL_STATE()->redqueen_breakpoints, entry) { QTAILQ_FOREACH (bp, &GET_GLOBAL_STATE()->redqueen_breakpoints, entry) {
if (bp->pc == pc) { if (bp->pc == pc) {
return bp; return bp;
} }
@ -426,7 +485,8 @@ static struct kvm_sw_breakpoint *redqueen_find_breakpoint(CPUState *cpu, target_
return NULL; return NULL;
} }
static int redqueen_breakpoints_active(CPUState *cpu){ static int redqueen_breakpoints_active(CPUState *cpu)
{
return !QTAILQ_EMPTY(&GET_GLOBAL_STATE()->redqueen_breakpoints); return !QTAILQ_EMPTY(&GET_GLOBAL_STATE()->redqueen_breakpoints);
} }
@ -435,7 +495,8 @@ struct kvm_set_guest_debug_data {
int err; int err;
}; };
static int redqueen_update_guest_debug(CPUState *cpu) { static int redqueen_update_guest_debug(CPUState *cpu)
{
struct kvm_set_guest_debug_data data; struct kvm_set_guest_debug_data data;
data.dbg.control = 0; data.dbg.control = 0;
@ -447,10 +508,11 @@ static int redqueen_update_guest_debug(CPUState *cpu) {
return kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG, &data.dbg); return kvm_vcpu_ioctl(cpu, KVM_SET_GUEST_DEBUG, &data.dbg);
} }
static void redqueen_remove_all_breakpoints(CPUState *cpu) { static void redqueen_remove_all_breakpoints(CPUState *cpu)
{
struct kvm_sw_breakpoint *bp, *next; struct kvm_sw_breakpoint *bp, *next;
QTAILQ_FOREACH_SAFE(bp, &GET_GLOBAL_STATE()->redqueen_breakpoints, entry, next) { QTAILQ_FOREACH_SAFE (bp, &GET_GLOBAL_STATE()->redqueen_breakpoints, entry, next) {
redqueen_remove_sw_breakpoint(cpu, bp); redqueen_remove_sw_breakpoint(cpu, bp);
QTAILQ_REMOVE(&GET_GLOBAL_STATE()->redqueen_breakpoints, bp, entry); QTAILQ_REMOVE(&GET_GLOBAL_STATE()->redqueen_breakpoints, bp, entry);
g_free(bp); g_free(bp);
@ -459,7 +521,8 @@ static void redqueen_remove_all_breakpoints(CPUState *cpu) {
redqueen_update_guest_debug(cpu); redqueen_update_guest_debug(cpu);
} }
static int redqueen_insert_breakpoint(CPUState *cpu, target_ulong addr, target_ulong len){ static int redqueen_insert_breakpoint(CPUState *cpu, target_ulong addr, target_ulong len)
{
struct kvm_sw_breakpoint *bp; struct kvm_sw_breakpoint *bp;
int err; int err;
@ -482,14 +545,15 @@ static int redqueen_insert_breakpoint(CPUState *cpu, target_ulong addr, target_u
QTAILQ_INSERT_HEAD(&GET_GLOBAL_STATE()->redqueen_breakpoints, bp, entry); QTAILQ_INSERT_HEAD(&GET_GLOBAL_STATE()->redqueen_breakpoints, bp, entry);
err = redqueen_update_guest_debug(cpu); err = redqueen_update_guest_debug(cpu);
if(err){ if (err) {
return err; return err;
} }
return 0; return 0;
} }
static int redqueen_remove_breakpoint(CPUState *cpu, target_ulong addr, target_ulong len){ static int redqueen_remove_breakpoint(CPUState *cpu, target_ulong addr, target_ulong len)
{
struct kvm_sw_breakpoint *bp; struct kvm_sw_breakpoint *bp;
int err; int err;
@ -512,27 +576,30 @@ static int redqueen_remove_breakpoint(CPUState *cpu, target_ulong addr, target_u
g_free(bp); g_free(bp);
err = redqueen_update_guest_debug(cpu); err = redqueen_update_guest_debug(cpu);
if(err){ if (err) {
return err; return err;
} }
return 0; return 0;
} }
int insert_breakpoint(CPUState *cpu, uint64_t addr, uint64_t len){ int insert_breakpoint(CPUState *cpu, uint64_t addr, uint64_t len)
{
redqueen_insert_breakpoint(cpu, addr, len); redqueen_insert_breakpoint(cpu, addr, len);
redqueen_update_guest_debug(cpu); redqueen_update_guest_debug(cpu);
return 0; return 0;
} }
int remove_breakpoint(CPUState *cpu, uint64_t addr, uint64_t len){ int remove_breakpoint(CPUState *cpu, uint64_t addr, uint64_t len)
{
redqueen_remove_breakpoint(cpu, addr, len); redqueen_remove_breakpoint(cpu, addr, len);
redqueen_update_guest_debug(cpu); redqueen_update_guest_debug(cpu);
return 0; return 0;
} }
void remove_all_breakpoints(CPUState *cpu){ void remove_all_breakpoints(CPUState *cpu)
{
redqueen_remove_all_breakpoints(cpu); redqueen_remove_all_breakpoints(cpu);
} }
@ -540,15 +607,18 @@ void remove_all_breakpoints(CPUState *cpu){
#define PENTRIES 0x200 #define PENTRIES 0x200
#define PPAGE_SIZE 0x1000 #define PPAGE_SIZE 0x1000
static bool read_memory(uint64_t address, uint64_t* buffer, size_t size, bool read_from_snapshot) { static bool read_memory(uint64_t address,
uint64_t *buffer,
size_t size,
bool read_from_snapshot)
{
if (unlikely(address == INVALID_ADDRESS)) { if (unlikely(address == INVALID_ADDRESS)) {
return false; return false;
} }
if (unlikely(read_from_snapshot)) { if (unlikely(read_from_snapshot)) {
return read_snapshot_memory( return read_snapshot_memory(get_fast_reload_snapshot(), address,
get_fast_reload_snapshot(), (uint8_t *)buffer, size);
address, (uint8_t *)buffer, size);
} }
// NB: This API exposed by exec.h doesn't signal failure, although it can // NB: This API exposed by exec.h doesn't signal failure, although it can
@ -556,24 +626,29 @@ static bool read_memory(uint64_t address, uint64_t* buffer, size_t size, bool re
// we can actually check the return value here. Until then, will clear the // we can actually check the return value here. Until then, will clear the
// buffer contents first. // buffer contents first.
memset(buffer, 0, size); memset(buffer, 0, size);
cpu_physical_memory_rw(address, (uint8_t*)buffer, size, false); cpu_physical_memory_rw(address, (uint8_t *)buffer, size, false);
return true; return true;
} }
__attribute__((always_inline)) inline __attribute__((always_inline)) inline static bool bit(uint64_t value, uint8_t lsb)
static bool bit(uint64_t value, uint8_t lsb) { {
return (value >> lsb) & 1; return (value >> lsb) & 1;
} }
__attribute__((always_inline)) inline __attribute__((always_inline)) inline static uint64_t bits(uint64_t value,
static uint64_t bits(uint64_t value, uint8_t lsb, uint8_t msb) { uint8_t lsb,
uint8_t msb)
{
return (value & ((0xffffffffffffffffull >> (64 - (msb - lsb + 1))) << lsb)) >> lsb; return (value & ((0xffffffffffffffffull >> (64 - (msb - lsb + 1))) << lsb)) >> lsb;
} }
// Helper function to load an entire pagetable table. These are PENTRIES // Helper function to load an entire pagetable table. These are PENTRIES
// 64-bit entries, so entries must point to a sufficiently large buffer. // 64-bit entries, so entries must point to a sufficiently large buffer.
static bool load_table(uint64_t address, uint64_t* entries, bool read_from_snapshot) { static bool load_table(uint64_t address, uint64_t *entries, bool read_from_snapshot)
if (unlikely(!read_memory(address, entries, 512 * sizeof(*entries), read_from_snapshot))) { {
if (unlikely(!read_memory(address, entries, 512 * sizeof(*entries),
read_from_snapshot)))
{
return false; return false;
} }
@ -584,11 +659,12 @@ static bool load_table(uint64_t address, uint64_t* entries, bool read_from_snaps
// returning the same invalid value (0) for both non-present entries and // returning the same invalid value (0) for both non-present entries and
// any other error conditions, since we don't need to handle these cases // any other error conditions, since we don't need to handle these cases
// differently. // differently.
static uint64_t load_entry(uint64_t address, uint64_t index, static uint64_t load_entry(uint64_t address, uint64_t index, bool read_from_snapshot)
bool read_from_snapshot) { {
uint64_t entry = 0; uint64_t entry = 0;
if (unlikely(!read_memory(address + (index * sizeof(entry)), &entry, sizeof(entry), if (unlikely(!read_memory(address + (index * sizeof(entry)), &entry,
read_from_snapshot))) { sizeof(entry), read_from_snapshot)))
{
return 0; return 0;
} }
@ -600,14 +676,20 @@ static uint64_t load_entry(uint64_t address, uint64_t index,
return entry; return entry;
} }
static void print_page(uint64_t address, uint64_t entry, size_t size, bool s, bool w, bool x) { static void print_page(
fprintf(stderr, " %c%c%c %016lx %zx", uint64_t address, uint64_t entry, size_t size, bool s, bool w, bool x)
s ? 's' : 'u', w ? 'w' : 'r', x ? 'x' : '-', {
(bits(entry, 12, 51) << 12) & ~(size - 1), size); fprintf(stderr, " %c%c%c %016lx %zx", s ? 's' : 'u', w ? 'w' : 'r',
x ? 'x' : '-', (bits(entry, 12, 51) << 12) & ~(size - 1), size);
} }
static void print_48_pte(uint64_t address, uint64_t pde_entry, bool read_from_snapshot, static void print_48_pte(uint64_t address,
bool s, bool w, bool x) { uint64_t pde_entry,
bool read_from_snapshot,
bool s,
bool w,
bool x)
{
uint64_t pte_address = bits(pde_entry, 12, 51) << 12; uint64_t pte_address = bits(pde_entry, 12, 51) << 12;
uint64_t pte_table[PENTRIES]; uint64_t pte_table[PENTRIES];
@ -625,14 +707,19 @@ static void print_48_pte(uint64_t address, uint64_t pde_entry, bool read_from_sn
if (!bit(entry, 0)) { if (!bit(entry, 0)) {
// Not present. // Not present.
} else { } else {
print_page(address | i << 12, entry, 0x1000, print_page(address | i << 12, entry, 0x1000, s & !bit(entry, 2),
s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63)); w & bit(entry, 1), x & !bit(entry, 63));
} }
} }
} }
static void print_48_pde(uint64_t address, uint64_t pdpte_entry, bool read_from_snapshot, static void print_48_pde(uint64_t address,
bool s, bool w, bool x) { uint64_t pdpte_entry,
bool read_from_snapshot,
bool s,
bool w,
bool x)
{
uint64_t pde_address = bits(pdpte_entry, 12, 51) << 12; uint64_t pde_address = bits(pdpte_entry, 12, 51) << 12;
uint64_t pde_table[PENTRIES]; uint64_t pde_table[PENTRIES];
@ -650,8 +737,8 @@ static void print_48_pde(uint64_t address, uint64_t pdpte_entry, bool read_from_
if (!bit(entry, 0)) { if (!bit(entry, 0)) {
// Not present. // Not present.
} else if (bit(entry, 7)) { } else if (bit(entry, 7)) {
print_page(address | i << 21, entry, 0x200000, print_page(address | i << 21, entry, 0x200000, s & !bit(entry, 2),
s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63)); w & bit(entry, 1), x & !bit(entry, 63));
} else { } else {
print_48_pte(address | i << 21, entry, read_from_snapshot, print_48_pte(address | i << 21, entry, read_from_snapshot,
s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63)); s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63));
@ -659,8 +746,13 @@ static void print_48_pde(uint64_t address, uint64_t pdpte_entry, bool read_from_
} }
} }
static void print_48_pdpte(uint64_t address, uint64_t pml4_entry, bool read_from_snapshot, static void print_48_pdpte(uint64_t address,
bool s, bool w, bool x) { uint64_t pml4_entry,
bool read_from_snapshot,
bool s,
bool w,
bool x)
{
uint64_t pdpte_address = bits(pml4_entry, 12, 51) << 12; uint64_t pdpte_address = bits(pml4_entry, 12, 51) << 12;
uint64_t pdpte_table[PENTRIES]; uint64_t pdpte_table[PENTRIES];
@ -678,8 +770,8 @@ static void print_48_pdpte(uint64_t address, uint64_t pml4_entry, bool read_from
if (!bit(entry, 0)) { if (!bit(entry, 0)) {
// Not present. // Not present.
} else if (bit(entry, 7)) { } else if (bit(entry, 7)) {
print_page(address | i << 30, entry, 0x40000000, print_page(address | i << 30, entry, 0x40000000, s & !bit(entry, 2),
s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63)); w & bit(entry, 1), x & !bit(entry, 63));
} else { } else {
print_48_pde(address | i << 30, entry, read_from_snapshot, print_48_pde(address | i << 30, entry, read_from_snapshot,
s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63)); s & !bit(entry, 2), w & bit(entry, 1), x & !bit(entry, 63));
@ -687,7 +779,8 @@ static void print_48_pdpte(uint64_t address, uint64_t pml4_entry, bool read_from
} }
} }
static void print_48_pagetables_(uint64_t cr3, bool read_from_snapshot) { static void print_48_pagetables_(uint64_t cr3, bool read_from_snapshot)
{
uint64_t pml4_address = bits(cr3, 12, 51) << 12; uint64_t pml4_address = bits(cr3, 12, 51) << 12;
uint64_t pml4_table[PENTRIES]; uint64_t pml4_table[PENTRIES];
@ -708,13 +801,14 @@ static void print_48_pagetables_(uint64_t cr3, bool read_from_snapshot) {
} }
if (bit(entry, 0)) { if (bit(entry, 0)) {
print_48_pdpte(address, entry, read_from_snapshot, print_48_pdpte(address, entry, read_from_snapshot, !bit(entry, 2),
!bit(entry, 2), bit(entry, 1), !bit(entry, 63)); bit(entry, 1), !bit(entry, 63));
} }
} }
} }
void print_48_pagetables(uint64_t cr3) { void print_48_pagetables(uint64_t cr3)
{
static bool printed = false; static bool printed = false;
if (!printed) { if (!printed) {
fprintf(stderr, "pagetables for cr3 %lx", cr3); fprintf(stderr, "pagetables for cr3 %lx", cr3);
@ -724,7 +818,10 @@ void print_48_pagetables(uint64_t cr3) {
} }
} }
static uint64_t get_48_paging_phys_addr(uint64_t cr3, uint64_t addr, bool read_from_snapshot) { static uint64_t get_48_paging_phys_addr(uint64_t cr3,
uint64_t addr,
bool read_from_snapshot)
{
uint64_t pml4_address = bits(cr3, 12, 51) << 12; uint64_t pml4_address = bits(cr3, 12, 51) << 12;
uint64_t pml4_offset = bits(addr, 39, 47); uint64_t pml4_offset = bits(addr, 39, 47);
uint64_t pml4_entry = load_entry(pml4_address, pml4_offset, read_from_snapshot); uint64_t pml4_entry = load_entry(pml4_address, pml4_offset, read_from_snapshot);
@ -773,9 +870,10 @@ static uint64_t get_48_paging_phys_addr(uint64_t cr3, uint64_t addr, bool read_f
return page_address + page_offset; return page_address + page_offset;
} }
//#define DEBUG_48BIT_WALK // #define DEBUG_48BIT_WALK
bool read_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu){ bool read_virtual_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu)
{
uint8_t tmp_buf[x86_64_PAGE_SIZE]; uint8_t tmp_buf[x86_64_PAGE_SIZE];
hwaddr phys_addr; hwaddr phys_addr;
int asidx; int asidx;
@ -786,31 +884,36 @@ bool read_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUStat
CPUX86State *env = &(X86_CPU(cpu))->env; CPUX86State *env = &(X86_CPU(cpu))->env;
// copy per page // copy per page
while(amount_copied < size){ while (amount_copied < size) {
uint64_t len_to_copy = (size - amount_copied); uint64_t len_to_copy = (size - amount_copied);
if(len_to_copy > x86_64_PAGE_SIZE) if (len_to_copy > x86_64_PAGE_SIZE)
len_to_copy = x86_64_PAGE_SIZE; len_to_copy = x86_64_PAGE_SIZE;
asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED); asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED);
#ifdef DEBUG_48BIT_WALK #ifdef DEBUG_48BIT_WALK
phys_addr_2 = cpu_get_phys_page_attrs_debug(cpu, (address & x86_64_PAGE_MASK), &attrs); phys_addr_2 =
cpu_get_phys_page_attrs_debug(cpu, (address & x86_64_PAGE_MASK), &attrs);
#endif #endif
phys_addr = (hwaddr)get_paging_phys_addr(cpu, env->cr[3], address) & 0xFFFFFFFFFFFFF000ULL;// != 0xFFFFFFFFFFFFFFFFULL) phys_addr = (hwaddr)get_paging_phys_addr(cpu, env->cr[3], address) &
0xFFFFFFFFFFFFF000ULL; // != 0xFFFFFFFFFFFFFFFFULL)
#ifdef DEBUG_48BIT_WALK #ifdef DEBUG_48BIT_WALK
assert(phys_addr == phys_addr_2); assert(phys_addr == phys_addr_2);
#endif #endif
if (phys_addr == INVALID_ADDRESS){ if (phys_addr == INVALID_ADDRESS) {
uint64_t next_page = (address & x86_64_PAGE_MASK) + x86_64_PAGE_SIZE; uint64_t next_page = (address & x86_64_PAGE_MASK) + x86_64_PAGE_SIZE;
uint64_t len_skipped =next_page-address; uint64_t len_skipped = next_page - address;
if(len_skipped > size-amount_copied){ if (len_skipped > size - amount_copied) {
len_skipped = size-amount_copied; len_skipped = size - amount_copied;
} }
nyx_error("Warning, read from unmapped memory:\t%lx, skipping to %lx", address, next_page); nyx_error("Warning, read from unmapped memory:\t%lx, skipping to %lx",
nyx_debug_p(MEM_PREFIX, "Warning, read from unmapped memory:\t%lx, skipping to %lx", address, next_page); address, next_page);
memset( data+amount_copied, ' ', len_skipped); nyx_debug_p(MEM_PREFIX,
"Warning, read from unmapped memory:\t%lx, skipping to %lx",
address, next_page);
memset(data + amount_copied, ' ', len_skipped);
address += len_skipped; address += len_skipped;
amount_copied += len_skipped; amount_copied += len_skipped;
continue; continue;
@ -818,16 +921,19 @@ bool read_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUStat
phys_addr += (address & ~x86_64_PAGE_MASK); phys_addr += (address & ~x86_64_PAGE_MASK);
uint64_t remaining_on_page = x86_64_PAGE_SIZE - (address & ~x86_64_PAGE_MASK); uint64_t remaining_on_page = x86_64_PAGE_SIZE - (address & ~x86_64_PAGE_MASK);
if(len_to_copy > remaining_on_page){ if (len_to_copy > remaining_on_page) {
len_to_copy = remaining_on_page; len_to_copy = remaining_on_page;
} }
MemTxResult txt = address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, tmp_buf, len_to_copy, 0); MemTxResult txt = address_space_rw(cpu_get_address_space(cpu, asidx),
if(txt){ phys_addr, MEMTXATTRS_UNSPECIFIED,
nyx_debug_p(MEM_PREFIX, "Warning, read failed:\t%lx (%lx)", address, phys_addr); tmp_buf, len_to_copy, 0);
if (txt) {
nyx_debug_p(MEM_PREFIX, "Warning, read failed:\t%lx (%lx)", address,
phys_addr);
} }
memcpy(data+amount_copied, tmp_buf, len_to_copy); memcpy(data + amount_copied, tmp_buf, len_to_copy);
address += len_to_copy; address += len_to_copy;
amount_copied += len_to_copy; amount_copied += len_to_copy;
@ -836,59 +942,72 @@ bool read_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUStat
return true; return true;
} }
bool is_addr_mapped_cr3(uint64_t address, CPUState *cpu, uint64_t cr3){ bool is_addr_mapped_cr3(uint64_t address, CPUState *cpu, uint64_t cr3)
{
return (get_paging_phys_addr(cpu, cr3, address) != INVALID_ADDRESS); return (get_paging_phys_addr(cpu, cr3, address) != INVALID_ADDRESS);
} }
bool is_addr_mapped(uint64_t address, CPUState *cpu){ bool is_addr_mapped(uint64_t address, CPUState *cpu)
{
CPUX86State *env = &(X86_CPU(cpu))->env; CPUX86State *env = &(X86_CPU(cpu))->env;
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
return (get_paging_phys_addr(cpu, env->cr[3], address) != INVALID_ADDRESS); return (get_paging_phys_addr(cpu, env->cr[3], address) != INVALID_ADDRESS);
} }
bool is_addr_mapped_cr3_snapshot(uint64_t address, CPUState *cpu, uint64_t cr3){ bool is_addr_mapped_cr3_snapshot(uint64_t address, CPUState *cpu, uint64_t cr3)
{
return (get_paging_phys_addr_snapshot(cpu, cr3, address) != INVALID_ADDRESS); return (get_paging_phys_addr_snapshot(cpu, cr3, address) != INVALID_ADDRESS);
} }
bool dump_page_cr3_snapshot(uint64_t address, uint8_t* data, CPUState *cpu, uint64_t cr3){ bool dump_page_cr3_snapshot(uint64_t address, uint8_t *data, CPUState *cpu, uint64_t cr3)
fast_reload_t* snapshot = get_fast_reload_snapshot(); {
fast_reload_t *snapshot = get_fast_reload_snapshot();
uint64_t phys_addr = get_paging_phys_addr_snapshot(cpu, cr3, address); uint64_t phys_addr = get_paging_phys_addr_snapshot(cpu, cr3, address);
if(phys_addr == INVALID_ADDRESS){ if (phys_addr == INVALID_ADDRESS) {
return false; return false;
} } else {
else{
return read_snapshot_memory(snapshot, phys_addr, data, PPAGE_SIZE); return read_snapshot_memory(snapshot, phys_addr, data, PPAGE_SIZE);
} }
} }
bool dump_page_cr3_ht(uint64_t address, uint8_t* data, CPUState *cpu, uint64_t cr3){ bool dump_page_cr3_ht(uint64_t address, uint8_t *data, CPUState *cpu, uint64_t cr3)
hwaddr phys_addr = (hwaddr) get_paging_phys_addr(cpu, cr3, address); {
hwaddr phys_addr = (hwaddr)get_paging_phys_addr(cpu, cr3, address);
int asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED); int asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED);
if(phys_addr == INVALID_ADDRESS || address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, data, 0x1000, 0)){ if (phys_addr == INVALID_ADDRESS ||
if(phys_addr != INVALID_ADDRESS){ address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr,
nyx_error("%s: Warning, read failed:\t%lx (%lx)\n", __func__, address, phys_addr); MEMTXATTRS_UNSPECIFIED, data, 0x1000, 0))
{
if (phys_addr != INVALID_ADDRESS) {
nyx_error("%s: Warning, read failed:\t%lx (%lx)\n", __func__, address,
phys_addr);
} }
return false; return false;
} }
return true; return true;
} }
bool dump_page_ht(uint64_t address, uint8_t* data, CPUState *cpu){ bool dump_page_ht(uint64_t address, uint8_t *data, CPUState *cpu)
{
CPUX86State *env = &(X86_CPU(cpu))->env; CPUX86State *env = &(X86_CPU(cpu))->env;
kvm_arch_get_registers_fast(cpu); kvm_arch_get_registers_fast(cpu);
hwaddr phys_addr = (hwaddr) get_paging_phys_addr(cpu, env->cr[3], address); hwaddr phys_addr = (hwaddr)get_paging_phys_addr(cpu, env->cr[3], address);
int asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED); int asidx = cpu_asidx_from_attrs(cpu, MEMTXATTRS_UNSPECIFIED);
if(phys_addr == 0xffffffffffffffffULL || address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr, MEMTXATTRS_UNSPECIFIED, data, 0x1000, 0)){ if (phys_addr == 0xffffffffffffffffULL ||
if(phys_addr != 0xffffffffffffffffULL){ address_space_rw(cpu_get_address_space(cpu, asidx), phys_addr,
nyx_error("%s: Warning, read failed:\t%lx (%lx)\n", __func__, address, phys_addr); MEMTXATTRS_UNSPECIFIED, data, 0x1000, 0))
{
if (phys_addr != 0xffffffffffffffffULL) {
nyx_error("%s: Warning, read failed:\t%lx (%lx)\n", __func__, address,
phys_addr);
} }
} }
return true; return true;
} }
uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr3){ uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr3)
{
csh handle; csh handle;
size_t code_size = 256; size_t code_size = 256;
@ -896,22 +1015,24 @@ uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr
/* don't => GET_GLOBAL_STATE()->disassembler_word_width */ /* don't => GET_GLOBAL_STATE()->disassembler_word_width */
if (cs_open(CS_ARCH_X86, get_capstone_mode(GET_GLOBAL_STATE()->disassembler_word_width), &handle) != CS_ERR_OK) if (cs_open(CS_ARCH_X86,
get_capstone_mode(GET_GLOBAL_STATE()->disassembler_word_width),
&handle) != CS_ERR_OK)
assert(false); assert(false);
cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON); cs_option(handle, CS_OPT_DETAIL, CS_OPT_ON);
cs_insn* insn = cs_malloc(handle); cs_insn *insn = cs_malloc(handle);
read_virtual_memory(address, code_ptr, code_size, cpu); read_virtual_memory(address, code_ptr, code_size, cpu);
int count = cs_disasm(handle, code_ptr, code_size, address, 5, &insn); int count = cs_disasm(handle, code_ptr, code_size, address, 5, &insn);
if(count > 0){ if (count > 0) {
for(int i = 0; i < count; i++){ for (int i = 0; i < count; i++) {
nyx_error("=> 0x%"PRIx64":\t%s\t\t%s\n", insn[i].address, insn[i].mnemonic, insn[i].op_str); nyx_error("=> 0x%" PRIx64 ":\t%s\t\t%s\n", insn[i].address,
insn[i].mnemonic, insn[i].op_str);
} }
} } else {
else{
nyx_error("ERROR in %s at %lx (cr3: %lx)\n", __func__, address, cr3); nyx_error("ERROR in %s at %lx (cr3: %lx)\n", __func__, address, cr3);
} }
@ -920,6 +1041,3 @@ uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr
cs_close(&handle); cs_close(&handle);
return 0; return 0;
} }

View File

@ -22,36 +22,51 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#ifndef MEMORY_ACCESS_H #ifndef MEMORY_ACCESS_H
#define MEMORY_ACCESS_H #define MEMORY_ACCESS_H
#include <linux/kvm.h>
#include "qemu-common.h"
#include "sysemu/kvm_int.h" #include "sysemu/kvm_int.h"
#include "qemu-common.h"
#include "nyx/types.h" #include "nyx/types.h"
#include <linux/kvm.h>
#define MEM_SPLIT_START 0x0C0000000 #define MEM_SPLIT_START 0x0C0000000
#define MEM_SPLIT_END 0x100000000 #define MEM_SPLIT_END 0x100000000
/* i386 pc_piix low_mem address translation */ /* i386 pc_piix low_mem address translation */
#define address_to_ram_offset(offset) (offset >= MEM_SPLIT_END ? (offset - MEM_SPLIT_END) + MEM_SPLIT_START : offset) #define address_to_ram_offset(offset) \
#define ram_offset_to_address(offset) (offset >= MEM_SPLIT_START ? (offset - MEM_SPLIT_START) + MEM_SPLIT_END : offset) (offset >= MEM_SPLIT_END ? (offset - MEM_SPLIT_END) + MEM_SPLIT_START : offset)
#define ram_offset_to_address(offset) \
(offset >= MEM_SPLIT_START ? (offset - MEM_SPLIT_START) + MEM_SPLIT_END : offset)
mem_mode_t get_current_mem_mode(CPUState *cpu); mem_mode_t get_current_mem_mode(CPUState *cpu);
uint64_t get_paging_phys_addr(CPUState *cpu, uint64_t cr3, uint64_t addr); uint64_t get_paging_phys_addr(CPUState *cpu, uint64_t cr3, uint64_t addr);
bool read_physical_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu); bool read_physical_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu);
bool write_physical_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu); bool write_physical_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu);
bool remap_payload_slot(uint64_t phys_addr, uint32_t slot, CPUState *cpu); bool remap_payload_slot(uint64_t phys_addr, uint32_t slot, CPUState *cpu);
bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *cpu); bool remap_payload_slot_protected(uint64_t phys_addr, uint32_t slot, CPUState *cpu);
bool remap_payload_buffer(uint64_t virt_guest_addr, CPUState *cpu); bool remap_payload_buffer(uint64_t virt_guest_addr, CPUState *cpu);
bool remap_slots(uint64_t addr, uint32_t slots, CPUState *cpu, int fd, uint64_t shm_size, bool virtual, uint64_t cr3); bool remap_slots(uint64_t addr,
bool remap_slot(uint64_t addr, uint32_t slot, CPUState *cpu, int fd, uint64_t shm_size, bool virtual, uint64_t cr3); uint32_t slots,
CPUState *cpu,
int fd,
uint64_t shm_size,
bool virtual,
uint64_t cr3);
bool remap_slot(uint64_t addr,
uint32_t slot,
CPUState *cpu,
int fd,
uint64_t shm_size,
bool virtual,
uint64_t cr3);
bool read_virtual_memory_cr3(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu, uint64_t cr3); bool read_virtual_memory_cr3(
uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu, uint64_t cr3);
bool read_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu); bool read_virtual_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu);
bool write_virtual_memory(uint64_t address, uint8_t* data, uint32_t size, CPUState *cpu); bool write_virtual_memory(uint64_t address, uint8_t *data, uint32_t size, CPUState *cpu);
void hexdump_virtual_memory(uint64_t address, uint32_t size, CPUState *cpu); void hexdump_virtual_memory(uint64_t address, uint32_t size, CPUState *cpu);
bool is_addr_mapped(uint64_t address, CPUState *cpu); bool is_addr_mapped(uint64_t address, CPUState *cpu);
bool is_addr_mapped_cr3(uint64_t address, CPUState *cpu, uint64_t cr3); bool is_addr_mapped_cr3(uint64_t address, CPUState *cpu, uint64_t cr3);
@ -61,14 +76,14 @@ int remove_breakpoint(CPUState *cpu, uint64_t addr, uint64_t len);
void remove_all_breakpoints(CPUState *cpu); void remove_all_breakpoints(CPUState *cpu);
uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr3); uint64_t disassemble_at_rip(int fd, uint64_t address, CPUState *cpu, uint64_t cr3);
bool dump_page_cr3_snapshot(uint64_t address, uint8_t* data, CPUState *cpu, uint64_t cr3); bool dump_page_cr3_snapshot(uint64_t address, uint8_t *data, CPUState *cpu, uint64_t cr3);
bool dump_page_cr3_ht(uint64_t address, uint8_t* data, CPUState *cpu, uint64_t cr3); bool dump_page_cr3_ht(uint64_t address, uint8_t *data, CPUState *cpu, uint64_t cr3);
bool is_addr_mapped_cr3_snapshot(uint64_t address, CPUState *cpu, uint64_t cr3); bool is_addr_mapped_cr3_snapshot(uint64_t address, CPUState *cpu, uint64_t cr3);
void print_48_pagetables(uint64_t cr3); void print_48_pagetables(uint64_t cr3);
bool dump_page_ht(uint64_t address, uint8_t* data, CPUState *cpu); bool dump_page_ht(uint64_t address, uint8_t *data, CPUState *cpu);
void resize_shared_memory(uint32_t new_size, uint32_t* shm_size, void** shm_ptr, int fd); void resize_shared_memory(uint32_t new_size, uint32_t *shm_size, void **shm_ptr, int fd);
#endif #endif

View File

@ -1,19 +1,19 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <stdio.h> #include "qemu/main-loop.h"
#include <stdint.h> #include "sysemu/kvm.h"
#include "sysemu/sysemu.h"
#include "nested_hypercalls.h"
#include "debug.h"
#include "interface.h"
#include "kvm_nested.h" #include "kvm_nested.h"
#include "memory_access.h" #include "memory_access.h"
#include "debug.h"
#include "nested_hypercalls.h"
#include "interface.h"
#include "state/state.h"
#include "pt.h"
#include "sysemu/sysemu.h"
#include "sysemu/kvm.h"
#include "qemu/main-loop.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "pt.h"
#include "state/state.h"
#include <stdint.h>
#include <stdio.h>
//#define DEBUG_NESTED_HYPERCALLS // #define DEBUG_NESTED_HYPERCALLS
bool hypercalls_enabled = false; bool hypercalls_enabled = false;
@ -27,54 +27,68 @@ int nested_once = 0;
bool nested_setup_snapshot_once = false; bool nested_setup_snapshot_once = false;
void handle_hypercall_kafl_nested_config(struct kvm_run *run,
void handle_hypercall_kafl_nested_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ CPUState *cpu,
uint64_t hypercall_arg)
{
/* magic */ /* magic */
nyx_trace(); nyx_trace();
uint32_t size = 0; uint32_t size = 0;
read_physical_memory(htos_config, (uint8_t*) &size, sizeof(uint32_t), cpu); read_physical_memory(htos_config, (uint8_t *)&size, sizeof(uint32_t), cpu);
void* buffer = malloc(size); void *buffer = malloc(size);
read_physical_memory(htos_config+sizeof(uint32_t), buffer, size, cpu); read_physical_memory(htos_config + sizeof(uint32_t), buffer, size, cpu);
print_configuration(stderr, buffer, size); print_configuration(stderr, buffer, size);
FILE* f = fopen("/tmp/hypertrash_configration", "w"); FILE *f = fopen("/tmp/hypertrash_configration", "w");
print_configuration(f, buffer, size); print_configuration(f, buffer, size);
fclose(f); fclose(f);
free(buffer); free(buffer);
} }
void handle_hypercall_kafl_nested_hprintf(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_nested_hprintf(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
nyx_trace(); nyx_trace();
char hprintf_buffer[0x1000]; char hprintf_buffer[0x1000];
read_physical_memory((uint64_t)run->hypercall.args[0], (uint8_t*)hprintf_buffer, 0x1000, cpu); read_physical_memory((uint64_t)run->hypercall.args[0], (uint8_t *)hprintf_buffer,
0x1000, cpu);
set_hprintf_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer, hprintf_buffer, strnlen(hprintf_buffer, 0x1000)+1); set_hprintf_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer, hprintf_buffer,
strnlen(hprintf_buffer, 0x1000) + 1);
synchronization_lock_hprintf(); synchronization_lock_hprintf();
} }
void handle_hypercall_kafl_nested_prepare(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_nested_prepare(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
nyx_trace(); nyx_trace();
kvm_arch_get_registers(cpu); kvm_arch_get_registers(cpu);
if((uint64_t)run->hypercall.args[0]){ if ((uint64_t)run->hypercall.args[0]) {
nyx_debug_p(CORE_PREFIX, "handle_hypercall_kafl_nested_prepare:\t NUM:\t%lx\t ADDRESS:\t%lx\t CR3:\t%lx", (uint64_t)run->hypercall.args[0], (uint64_t)run->hypercall.args[1], (uint64_t)run->hypercall.args[2]); nyx_debug_p(CORE_PREFIX,
} "handle_hypercall_kafl_nested_prepare:\t NUM:\t%lx\t "
else{ "ADDRESS:\t%lx\t CR3:\t%lx",
(uint64_t)run->hypercall.args[0], (uint64_t)run->hypercall.args[1],
(uint64_t)run->hypercall.args[2]);
} else {
abort(); abort();
} }
size_t buffer_size = (size_t)((uint64_t)run->hypercall.args[0] * sizeof(uint64_t)); size_t buffer_size = (size_t)((uint64_t)run->hypercall.args[0] * sizeof(uint64_t));
uint64_t* buffer = malloc(buffer_size); uint64_t *buffer = malloc(buffer_size);
memset(buffer, 0x0, buffer_size); memset(buffer, 0x0, buffer_size);
read_physical_memory((uint64_t)run->hypercall.args[1], (uint8_t*)buffer, buffer_size, cpu); read_physical_memory((uint64_t)run->hypercall.args[1], (uint8_t *)buffer,
buffer_size, cpu);
htos_cr3 = (uint64_t)run->hypercall.args[0]; htos_cr3 = (uint64_t)run->hypercall.args[0];
for(uint64_t i = 0; i < (uint64_t)run->hypercall.args[0]; i++){ for (uint64_t i = 0; i < (uint64_t)run->hypercall.args[0]; i++) {
if(i == 0){ if (i == 0) {
htos_config = buffer[i]; htos_config = buffer[i];
} }
nyx_debug_p(CORE_PREFIX, "ADDRESS: %lx", buffer[i]); nyx_debug_p(CORE_PREFIX, "ADDRESS: %lx", buffer[i]);
@ -85,39 +99,46 @@ void handle_hypercall_kafl_nested_prepare(struct kvm_run *run, CPUState *cpu, ui
// wipe memory // wipe memory
memset(buffer, 0x00, buffer_size); memset(buffer, 0x00, buffer_size);
write_physical_memory((uint64_t)run->hypercall.args[1], (uint8_t*)buffer, buffer_size, cpu); write_physical_memory((uint64_t)run->hypercall.args[1], (uint8_t *)buffer,
buffer_size, cpu);
free(buffer); free(buffer);
} }
bool acquired = false; bool acquired = false;
void handle_hypercall_kafl_nested_early_release(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_nested_early_release(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
nyx_trace(); nyx_trace();
if(!hypercalls_enabled){ if (!hypercalls_enabled) {
return; return;
} }
bool state = GET_GLOBAL_STATE()->in_reload_mode; bool state = GET_GLOBAL_STATE()->in_reload_mode;
if(!state){ if (!state) {
GET_GLOBAL_STATE()->in_reload_mode = true; GET_GLOBAL_STATE()->in_reload_mode = true;
synchronization_disable_pt(cpu); synchronization_disable_pt(cpu);
GET_GLOBAL_STATE()->in_reload_mode = false; GET_GLOBAL_STATE()->in_reload_mode = false;
} } else {
else{
synchronization_disable_pt(cpu); synchronization_disable_pt(cpu);
} }
} }
void handle_hypercall_kafl_nested_release(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_nested_release(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
nyx_trace(); nyx_trace();
// TODO not implemented - see git history for scraps // TODO not implemented - see git history for scraps
nyx_error("Not implemented.\n"); nyx_error("Not implemented.\n");
abort(); abort();
} }
static inline void set_page_dump_bp_nested(CPUState *cpu, uint64_t cr3, uint64_t addr){ static inline void set_page_dump_bp_nested(CPUState *cpu, uint64_t cr3, uint64_t addr)
{
nyx_trace(); nyx_trace();
kvm_remove_all_breakpoints(cpu); kvm_remove_all_breakpoints(cpu);
@ -128,17 +149,21 @@ static inline void set_page_dump_bp_nested(CPUState *cpu, uint64_t cr3, uint64_t
kvm_vcpu_ioctl(cpu, KVM_VMX_PT_ENABLE_PAGE_DUMP_CR3); kvm_vcpu_ioctl(cpu, KVM_VMX_PT_ENABLE_PAGE_DUMP_CR3);
} }
void handle_hypercall_kafl_nested_acquire(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg){ void handle_hypercall_kafl_nested_acquire(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg)
{
nyx_trace(); nyx_trace();
if (!acquired){ if (!acquired) {
acquired = true; acquired = true;
//create_fast_snapshot(cpu, true); // create_fast_snapshot(cpu, true);
request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state, REQUEST_SAVE_SNAPSHOT_ROOT_NESTED_FIX_RIP); request_fast_vm_reload(GET_GLOBAL_STATE()->reload_state,
REQUEST_SAVE_SNAPSHOT_ROOT_NESTED_FIX_RIP);
for(int i = 0; i < INTEL_PT_MAX_RANGES; i++){ for (int i = 0; i < INTEL_PT_MAX_RANGES; i++) {
if(GET_GLOBAL_STATE()->pt_ip_filter_configured[i]){ if (GET_GLOBAL_STATE()->pt_ip_filter_configured[i]) {
pt_enable_ip_filtering(cpu, i, true, false); pt_enable_ip_filtering(cpu, i, true, false);
} }
} }
@ -163,7 +188,7 @@ void handle_hypercall_kafl_nested_acquire(struct kvm_run *run, CPUState *cpu, ui
pt_set_cr3(cpu, cr3, false); pt_set_cr3(cpu, cr3, false);
GET_GLOBAL_STATE()->parent_cr3 = cr3; GET_GLOBAL_STATE()->parent_cr3 = cr3;
if(GET_GLOBAL_STATE()->dump_page){ if (GET_GLOBAL_STATE()->dump_page) {
set_page_dump_bp_nested(cpu, cr3, GET_GLOBAL_STATE()->dump_page_addr); set_page_dump_bp_nested(cpu, cr3, GET_GLOBAL_STATE()->dump_page_addr);
} }

View File

@ -3,9 +3,21 @@
#include <stdint.h> #include <stdint.h>
/* HyperTrash! */ /* HyperTrash! */
void handle_hypercall_kafl_nested_hprintf(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_nested_hprintf(struct kvm_run *run,
void handle_hypercall_kafl_nested_prepare(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); CPUState *cpu,
void handle_hypercall_kafl_nested_config(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); uint64_t hypercall_arg);
void handle_hypercall_kafl_nested_release(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); void handle_hypercall_kafl_nested_prepare(struct kvm_run *run,
void handle_hypercall_kafl_nested_acquire(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); CPUState *cpu,
void handle_hypercall_kafl_nested_early_release(struct kvm_run *run, CPUState *cpu, uint64_t hypercall_arg); uint64_t hypercall_arg);
void handle_hypercall_kafl_nested_config(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_nested_release(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_nested_acquire(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);
void handle_hypercall_kafl_nested_early_release(struct kvm_run *run,
CPUState *cpu,
uint64_t hypercall_arg);

View File

@ -1,26 +1,27 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <errno.h>
#include <capstone/capstone.h>
#include <capstone/x86.h>
#include <sys/file.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/mman.h>
#include <assert.h>
#include "nyx/page_cache.h" #include "nyx/page_cache.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/memory_access.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "nyx/memory_access.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
#include <assert.h>
#include <capstone/capstone.h>
#include <capstone/x86.h>
#include <errno.h>
#include <stdio.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <unistd.h>
#define PAGE_CACHE_ADDR_LINE_SIZE sizeof(uint64_t) #define PAGE_CACHE_ADDR_LINE_SIZE sizeof(uint64_t)
#define UNMAPPED_PAGE 0xFFFFFFFFFFFFFFFFULL #define UNMAPPED_PAGE 0xFFFFFFFFFFFFFFFFULL
static bool reload_addresses(page_cache_t* self){ static bool reload_addresses(page_cache_t *self)
{
khiter_t k; khiter_t k;
int ret; int ret;
uint64_t addr, offset; uint64_t addr, offset;
@ -28,37 +29,38 @@ static bool reload_addresses(page_cache_t* self){
size_t self_offset = lseek(self->fd_address_file, 0, SEEK_END); size_t self_offset = lseek(self->fd_address_file, 0, SEEK_END);
if(self_offset != self->num_pages*PAGE_CACHE_ADDR_LINE_SIZE){ if (self_offset != self->num_pages * PAGE_CACHE_ADDR_LINE_SIZE) {
/* reload page cache from disk */ /* reload page cache from disk */
lseek(self->fd_address_file, self->num_pages*PAGE_CACHE_ADDR_LINE_SIZE, SEEK_SET); lseek(self->fd_address_file, self->num_pages * PAGE_CACHE_ADDR_LINE_SIZE,
SEEK_SET);
offset = self->num_pages; offset = self->num_pages;
while(read(self->fd_address_file, &value, PAGE_CACHE_ADDR_LINE_SIZE)){ while (read(self->fd_address_file, &value, PAGE_CACHE_ADDR_LINE_SIZE)) {
addr = value & 0xFFFFFFFFFFFFF000ULL; addr = value & 0xFFFFFFFFFFFFF000ULL;
offset++; offset++;
/* put new addresses and offsets into the hash map */ /* put new addresses and offsets into the hash map */
k = kh_get(PC_CACHE, self->lookup, addr); k = kh_get(PC_CACHE, self->lookup, addr);
if(k == kh_end(self->lookup)){ if (k == kh_end(self->lookup)) {
if (value & 0xFFF) {
if(value & 0xFFF){
fprintf(stderr, "Load page: %lx (UNMAPPED)\n", addr); fprintf(stderr, "Load page: %lx (UNMAPPED)\n", addr);
} } else {
else{
k = kh_put(PC_CACHE, self->lookup, addr, &ret); k = kh_put(PC_CACHE, self->lookup, addr, &ret);
kh_value(self->lookup, k) = (offset-1)*PAGE_SIZE; kh_value(self->lookup, k) = (offset - 1) * PAGE_SIZE;
} }
} } else {
else{
/* likely a bug / race condition in page_cache itself! */ /* likely a bug / race condition in page_cache itself! */
fprintf(stderr, "----------> Page duplicate found ...skipping! %lx\n", addr); fprintf(stderr,
//abort(); "----------> Page duplicate found ...skipping! %lx\n", addr);
// abort();
} }
} }
/* reload page dump file */ /* reload page dump file */
munmap(self->page_data, self->num_pages*PAGE_SIZE); munmap(self->page_data, self->num_pages * PAGE_SIZE);
self->num_pages = self_offset/PAGE_CACHE_ADDR_LINE_SIZE; self->num_pages = self_offset / PAGE_CACHE_ADDR_LINE_SIZE;
self->page_data = mmap(NULL, (self->num_pages)*PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, self->fd_page_file, 0); self->page_data = mmap(NULL, (self->num_pages) * PAGE_SIZE,
PROT_READ | PROT_WRITE, MAP_SHARED,
self->fd_page_file, 0);
return true; return true;
} }
@ -66,25 +68,37 @@ static bool reload_addresses(page_cache_t* self){
return false; return false;
} }
static bool append_page(page_cache_t* self, uint64_t page, uint64_t cr3){ static bool append_page(page_cache_t *self, uint64_t page, uint64_t cr3)
{
bool success = true; bool success = true;
if(!self->num_pages){ if (!self->num_pages) {
assert(!ftruncate(self->fd_page_file, (self->num_pages+1)*PAGE_SIZE)); assert(!ftruncate(self->fd_page_file, (self->num_pages + 1) * PAGE_SIZE));
self->page_data = mmap(NULL, (self->num_pages+1)*PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, self->fd_page_file, 0); self->page_data = mmap(NULL, (self->num_pages + 1) * PAGE_SIZE,
} PROT_READ | PROT_WRITE, MAP_SHARED,
else{ self->fd_page_file, 0);
munmap(self->page_data, self->num_pages*PAGE_SIZE); } else {
assert(!ftruncate(self->fd_page_file, (self->num_pages+1)*PAGE_SIZE)); munmap(self->page_data, self->num_pages * PAGE_SIZE);
self->page_data = mmap(NULL, (self->num_pages+1)*PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, self->fd_page_file, 0); assert(!ftruncate(self->fd_page_file, (self->num_pages + 1) * PAGE_SIZE));
self->page_data = mmap(NULL, (self->num_pages + 1) * PAGE_SIZE,
PROT_READ | PROT_WRITE, MAP_SHARED,
self->fd_page_file, 0);
} }
if(!dump_page_cr3_ht(page, self->page_data+(PAGE_SIZE*self->num_pages), self->cpu, GET_GLOBAL_STATE()->pt_c3_filter)){ if (!dump_page_cr3_ht(page, self->page_data + (PAGE_SIZE * self->num_pages),
if(!dump_page_cr3_ht(page, self->page_data+(PAGE_SIZE*self->num_pages), self->cpu, GET_GLOBAL_STATE()->parent_cr3)){ self->cpu, GET_GLOBAL_STATE()->pt_c3_filter))
if(!dump_page_cr3_snapshot(page, self->page_data+(PAGE_SIZE*self->num_pages), self->cpu, GET_GLOBAL_STATE()->parent_cr3)){ {
if (!dump_page_cr3_ht(page, self->page_data + (PAGE_SIZE * self->num_pages),
munmap(self->page_data, (self->num_pages+1)*PAGE_SIZE); self->cpu, GET_GLOBAL_STATE()->parent_cr3))
assert(!ftruncate(self->fd_page_file, (self->num_pages)*PAGE_SIZE)); {
self->page_data = mmap(NULL, (self->num_pages)*PAGE_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, self->fd_page_file, 0); if (!dump_page_cr3_snapshot(page,
self->page_data + (PAGE_SIZE * self->num_pages),
self->cpu, GET_GLOBAL_STATE()->parent_cr3))
{
munmap(self->page_data, (self->num_pages + 1) * PAGE_SIZE);
assert(!ftruncate(self->fd_page_file, (self->num_pages) * PAGE_SIZE));
self->page_data = mmap(NULL, (self->num_pages) * PAGE_SIZE,
PROT_READ | PROT_WRITE, MAP_SHARED,
self->fd_page_file, 0);
success = false; success = false;
return success; return success;
@ -96,69 +110,69 @@ static bool append_page(page_cache_t* self, uint64_t page, uint64_t cr3){
return success; return success;
} }
static void page_cache_lock(page_cache_t* self){ static void page_cache_lock(page_cache_t *self)
{
int ret = 0; int ret = 0;
while (true){ while (true) {
ret = flock(self->fd_lock, LOCK_EX); ret = flock(self->fd_lock, LOCK_EX);
if (ret == 0){ if (ret == 0) {
return; return;
} } else if (ret == EINTR) {
else if (ret == EINTR){
/* try again if acquiring this lock has failed */ /* try again if acquiring this lock has failed */
fprintf(stderr, "%s: interrupted by signal...\n", __func__); fprintf(stderr, "%s: interrupted by signal...\n", __func__);
} } else {
else{
assert(false); assert(false);
} }
} }
} }
static void page_cache_unlock(page_cache_t* self){ static void page_cache_unlock(page_cache_t *self)
{
int ret = 0; int ret = 0;
while (true){ while (true) {
ret = flock(self->fd_lock, LOCK_UN); ret = flock(self->fd_lock, LOCK_UN);
if (ret == 0){ if (ret == 0) {
return; return;
} } else if (ret == EINTR) {
else if (ret == EINTR){
/* try again if releasing this lock has failed */ /* try again if releasing this lock has failed */
fprintf(stderr, "%s: interrupted by signal...\n", __func__); fprintf(stderr, "%s: interrupted by signal...\n", __func__);
} } else {
else{
assert(false); assert(false);
} }
} }
} }
static bool update_page_cache(page_cache_t* self, uint64_t page, khiter_t* k){ static bool update_page_cache(page_cache_t *self, uint64_t page, khiter_t *k)
{
page_cache_lock(self); page_cache_lock(self);
if(reload_addresses(self)){ if (reload_addresses(self)) {
*k = kh_get(PC_CACHE, self->lookup, page); *k = kh_get(PC_CACHE, self->lookup, page);
} }
if(*k == kh_end(self->lookup)){ if (*k == kh_end(self->lookup)) {
int ret; int ret;
uint64_t cr3 = GET_GLOBAL_STATE()->parent_cr3; uint64_t cr3 = GET_GLOBAL_STATE()->parent_cr3;
if(!is_addr_mapped_cr3_snapshot(page, self->cpu, GET_GLOBAL_STATE()->parent_cr3) && !is_addr_mapped_cr3_snapshot(page, self->cpu, GET_GLOBAL_STATE()->pt_c3_filter)){ if (!is_addr_mapped_cr3_snapshot(page, self->cpu,
GET_GLOBAL_STATE()->parent_cr3) &&
!is_addr_mapped_cr3_snapshot(page, self->cpu,
GET_GLOBAL_STATE()->pt_c3_filter))
{
/* TODO! */ /* TODO! */
} }
*k = kh_get(PC_CACHE, self->lookup, page); *k = kh_get(PC_CACHE, self->lookup, page);
if(*k == kh_end(self->lookup) && reload_addresses(self)){ if (*k == kh_end(self->lookup) && reload_addresses(self)) {
/* reload sucessful */ /* reload sucessful */
*k = kh_get(PC_CACHE, self->lookup, page); *k = kh_get(PC_CACHE, self->lookup, page);
} } else {
else{ if (append_page(self, page, cr3)) {
if(append_page(self, page, cr3)){
*k = kh_put(PC_CACHE, self->lookup, page, &ret); *k = kh_put(PC_CACHE, self->lookup, page, &ret);
assert(write(self->fd_address_file, &page, PAGE_CACHE_ADDR_LINE_SIZE) == PAGE_CACHE_ADDR_LINE_SIZE); assert(write(self->fd_address_file, &page,
kh_value(self->lookup, *k) = (self->num_pages-1)*PAGE_SIZE; PAGE_CACHE_ADDR_LINE_SIZE) == PAGE_CACHE_ADDR_LINE_SIZE);
} kh_value(self->lookup, *k) = (self->num_pages - 1) * PAGE_SIZE;
else{ } else {
page_cache_unlock(self); page_cache_unlock(self);
return false; return false;
} }
@ -170,18 +184,19 @@ static bool update_page_cache(page_cache_t* self, uint64_t page, khiter_t* k){
return true; return true;
} }
uint64_t page_cache_fetch(page_cache_t* self, uint64_t page, bool* success, bool test_mode){ uint64_t page_cache_fetch(page_cache_t *self, uint64_t page, bool *success, bool test_mode)
{
page &= 0xFFFFFFFFFFFFF000ULL; page &= 0xFFFFFFFFFFFFF000ULL;
if (self->last_page == page){ if (self->last_page == page) {
*success = true; *success = true;
return self->last_addr; return self->last_addr;
} }
khiter_t k; khiter_t k;
k = kh_get(PC_CACHE, self->lookup, page); k = kh_get(PC_CACHE, self->lookup, page);
if(k == kh_end(self->lookup)){ if (k == kh_end(self->lookup)) {
if(test_mode || update_page_cache(self, page, &k) == false){ if (test_mode || update_page_cache(self, page, &k) == false) {
*success = false; *success = false;
return 0; return 0;
} }
@ -189,11 +204,10 @@ uint64_t page_cache_fetch(page_cache_t* self, uint64_t page, bool* success, bool
self->last_page = page; self->last_page = page;
if(kh_value(self->lookup, k) == UNMAPPED_PAGE){ if (kh_value(self->lookup, k) == UNMAPPED_PAGE) {
self->last_addr = UNMAPPED_PAGE; self->last_addr = UNMAPPED_PAGE;
} } else {
else{ self->last_addr = (uint64_t)self->page_data + kh_value(self->lookup, k);
self->last_addr = (uint64_t)self->page_data+kh_value(self->lookup, k);
} }
*success = true; *success = true;
@ -201,16 +215,18 @@ uint64_t page_cache_fetch(page_cache_t* self, uint64_t page, bool* success, bool
} }
/* FIXME */ /* FIXME */
uint64_t page_cache_fetch2(page_cache_t* self, uint64_t page, bool* success){ uint64_t page_cache_fetch2(page_cache_t *self, uint64_t page, bool *success)
{
return page_cache_fetch(self, page, success, false); return page_cache_fetch(self, page, success, false);
} }
page_cache_t* page_cache_new(CPUState *cpu, const char* cache_file){ page_cache_t *page_cache_new(CPUState *cpu, const char *cache_file)
page_cache_t* self = malloc(sizeof(page_cache_t)); {
page_cache_t *self = malloc(sizeof(page_cache_t));
char* tmp1; char *tmp1;
char* tmp2; char *tmp2;
char* tmp3; char *tmp3;
assert(asprintf(&tmp1, "%s.dump", cache_file) != -1); assert(asprintf(&tmp1, "%s.dump", cache_file) != -1);
assert(asprintf(&tmp2, "%s.addr", cache_file) != -1); assert(asprintf(&tmp2, "%s.addr", cache_file) != -1);
assert(asprintf(&tmp3, "%s.lock", cache_file) != -1); assert(asprintf(&tmp3, "%s.lock", cache_file) != -1);
@ -253,12 +269,14 @@ page_cache_t* page_cache_new(CPUState *cpu, const char* cache_file){
return self; return self;
} }
bool page_cache_disassemble(page_cache_t* self, uint64_t address, cs_insn **insn){ bool page_cache_disassemble(page_cache_t *self, uint64_t address, cs_insn **insn)
{
return true; return true;
} }
cs_insn* page_cache_cs_malloc(page_cache_t* self, disassembler_mode_t mode){ cs_insn *page_cache_cs_malloc(page_cache_t *self, disassembler_mode_t mode)
switch(mode){ {
switch (mode) {
case mode_16: case mode_16:
return cs_malloc(self->handle_16); return cs_malloc(self->handle_16);
case mode_32: case mode_32:
@ -271,19 +289,24 @@ cs_insn* page_cache_cs_malloc(page_cache_t* self, disassembler_mode_t mode){
return NULL; return NULL;
} }
bool page_cache_disassemble_iter(page_cache_t* self, uint64_t* address, cs_insn *insn, uint64_t* failed_page, disassembler_mode_t mode){ bool page_cache_disassemble_iter(page_cache_t *self,
uint64_t *address,
cs_insn *insn,
uint64_t *failed_page,
disassembler_mode_t mode)
{
*failed_page = 0xFFFFFFFFFFFFFFFFULL; *failed_page = 0xFFFFFFFFFFFFFFFFULL;
bool success = true; bool success = true;
size_t code_size = 16; size_t code_size = 16;
uint8_t* code = (uint8_t*)page_cache_fetch(self, *address, &success, false); uint8_t *code = (uint8_t *)page_cache_fetch(self, *address, &success, false);
uint8_t* code_ptr = 0; uint8_t *code_ptr = 0;
csh* current_handle = NULL; csh *current_handle = NULL;
switch(mode){ switch (mode) {
case mode_16: case mode_16:
current_handle = &self->handle_16; current_handle = &self->handle_16;
break; break;
@ -297,33 +320,34 @@ bool page_cache_disassemble_iter(page_cache_t* self, uint64_t* address, cs_insn
assert(false); assert(false);
} }
if (code == (void*)UNMAPPED_PAGE || success == false){ if (code == (void *)UNMAPPED_PAGE || success == false) {
*failed_page = *address; *failed_page = *address;
return false; return false;
} }
if ((*address & 0xFFF) >= (0x1000-16)){ if ((*address & 0xFFF) >= (0x1000 - 16)) {
memcpy((void*)self->disassemble_cache, (void*)((uint64_t)code+(0x1000-16)), 16); memcpy((void *)self->disassemble_cache,
code_ptr = self->disassemble_cache + 0xf-(0xfff-(*address&0xfff)); (void *)((uint64_t)code + (0x1000 - 16)), 16);
code = (uint8_t*)page_cache_fetch(self, *address+0x1000, &success, false); code_ptr = self->disassemble_cache + 0xf - (0xfff - (*address & 0xfff));
code = (uint8_t *)page_cache_fetch(self, *address + 0x1000, &success, false);
if(success == true){ if (success == true) {
memcpy((void*)(self->disassemble_cache+16), (void*)code, 16); memcpy((void *)(self->disassemble_cache + 16), (void *)code, 16);
return cs_disasm_iter(*current_handle, (const uint8_t**) &code_ptr, &code_size, address, insn); return cs_disasm_iter(*current_handle, (const uint8_t **)&code_ptr,
} &code_size, address, insn);
else{ } else {
code_size = (0xfff-(*address&0xfff)); code_size = (0xfff - (*address & 0xfff));
if(!cs_disasm_iter(*current_handle, (const uint8_t**) &code_ptr, &code_size, address, insn)){ if (!cs_disasm_iter(*current_handle, (const uint8_t **)&code_ptr,
*failed_page = (*address+0x1000) & 0xFFFFFFFFFFFFF000ULL; &code_size, address, insn))
{
*failed_page = (*address + 0x1000) & 0xFFFFFFFFFFFFF000ULL;
return false; return false;
} }
return true; return true;
} }
} } else {
else { code_ptr = code + (*address & 0xFFF);
code_ptr = code + (*address&0xFFF); return cs_disasm_iter(*current_handle, (const uint8_t **)&code_ptr,
return cs_disasm_iter(*current_handle, (const uint8_t**) &code_ptr, &code_size, address, insn); &code_size, address, insn);
} }
} }

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include "khash.h"
#include <capstone/capstone.h> #include <capstone/capstone.h>
#include <capstone/x86.h> #include <capstone/x86.h>
#include "khash.h"
#include <libxdc.h> #include <libxdc.h>
#include "qemu-common.h" #include "qemu-common.h"
@ -10,14 +10,14 @@
KHASH_MAP_INIT_INT64(PC_CACHE, uint64_t) KHASH_MAP_INIT_INT64(PC_CACHE, uint64_t)
typedef struct page_cache_s{ typedef struct page_cache_s {
CPUState *cpu; CPUState *cpu;
khash_t(PC_CACHE) *lookup; khash_t(PC_CACHE) * lookup;
int fd_page_file; int fd_page_file;
int fd_address_file; int fd_address_file;
int fd_lock; int fd_lock;
uint8_t disassemble_cache[32]; uint8_t disassemble_cache[32];
void* page_data; void *page_data;
uint32_t num_pages; uint32_t num_pages;
csh handle_16; csh handle_16;
@ -28,12 +28,19 @@ typedef struct page_cache_s{
uint64_t last_addr; uint64_t last_addr;
} page_cache_t; } page_cache_t;
page_cache_t* page_cache_new(CPUState *cpu, const char* cache_file); page_cache_t *page_cache_new(CPUState *cpu, const char *cache_file);
uint64_t page_cache_fetch(page_cache_t* self, uint64_t page, bool* success, bool test_mode); uint64_t page_cache_fetch(page_cache_t *self,
uint64_t page,
bool *success,
bool test_mode);
bool page_cache_disassemble(page_cache_t* self, uint64_t address, cs_insn **insn); bool page_cache_disassemble(page_cache_t *self, uint64_t address, cs_insn **insn);
bool page_cache_disassemble_iter(page_cache_t* self, uint64_t* address, cs_insn *insn, uint64_t* failed_page, disassembler_mode_t mode); bool page_cache_disassemble_iter(page_cache_t *self,
uint64_t *address,
cs_insn *insn,
uint64_t *failed_page,
disassembler_mode_t mode);
cs_insn* page_cache_cs_malloc(page_cache_t* self, disassembler_mode_t mode); cs_insn *page_cache_cs_malloc(page_cache_t *self, disassembler_mode_t mode);
uint64_t page_cache_fetch2(page_cache_t* self, uint64_t page, bool* success); uint64_t page_cache_fetch2(page_cache_t *self, uint64_t page, bool *success);

View File

@ -1,10 +1,12 @@
#include "patcher.h" #include "patcher.h"
#include "nyx/memory_access.h"
#include "nyx/disassembler.h"
#include "debug.h" #include "debug.h"
#include "nyx/disassembler.h"
#include "nyx/memory_access.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
uint8_t cmp_patch_data[] = { 0x38, 0xC0, [2 ... MAX_INSTRUCTION_SIZE]=0x90 }; // CMP AL,AL; NOP, NOP ... uint8_t cmp_patch_data[] = {
0x38, 0xC0, [2 ... MAX_INSTRUCTION_SIZE] = 0x90
}; // CMP AL,AL; NOP, NOP ...
const uint8_t *cmp_patch = &cmp_patch_data[0]; const uint8_t *cmp_patch = &cmp_patch_data[0];
/* /*
@ -14,22 +16,30 @@ static void _patcher_apply_patch(patcher_t *self, size_t index);
static void _patcher_restore_patch(patcher_t *self, size_t index); static void _patcher_restore_patch(patcher_t *self, size_t index);
static void _patcher_save_patch(patcher_t *self, size_t index, uint8_t* data, size_t instruction_size, uint64_t addr); static void _patcher_save_patch(patcher_t *self,
size_t index,
uint8_t *data,
size_t instruction_size,
uint64_t addr);
static size_t _patcher_disassemble_size(patcher_t *self, uint8_t* data, uint64_t addr, x86_insn id); static size_t _patcher_disassemble_size(patcher_t *self,
uint8_t *data,
uint64_t addr,
x86_insn id);
static void _patcher_alloc_patch_infos(patcher_t *self, size_t num_patches); static void _patcher_alloc_patch_infos(patcher_t *self, size_t num_patches);
static void _patcher_free_patch_infos(patcher_t *self); static void _patcher_free_patch_infos(patcher_t *self);
static redqueen_t* _redq_ptr(patcher_t *self); static redqueen_t *_redq_ptr(patcher_t *self);
/* /*
* Public Functions * Public Functions
*/ */
patcher_t* patcher_new(CPUState *cpu){ patcher_t *patcher_new(CPUState *cpu)
{
patcher_t *res = malloc(sizeof(patcher_t)); patcher_t *res = malloc(sizeof(patcher_t));
res->cpu = cpu; res->cpu = cpu;
res->num_patches = 0; res->num_patches = 0;
@ -38,65 +48,77 @@ patcher_t* patcher_new(CPUState *cpu){
return res; return res;
} }
void patcher_free(patcher_t* self){ void patcher_free(patcher_t *self)
{
assert(!self->is_currently_applied); assert(!self->is_currently_applied);
_patcher_free_patch_infos(self); _patcher_free_patch_infos(self);
free(self); free(self);
} }
void patcher_apply_all(patcher_t *self){ void patcher_apply_all(patcher_t *self)
{
assert(!self->is_currently_applied); assert(!self->is_currently_applied);
assert(!_redq_ptr(self)->hooks_applied); assert(!_redq_ptr(self)->hooks_applied);
//assert(patcher_validate_patches(self)); // assert(patcher_validate_patches(self));
for(size_t i=0; i < self->num_patches; i++){ for (size_t i = 0; i < self->num_patches; i++) {
_patcher_apply_patch(self, i); _patcher_apply_patch(self, i);
} }
self->is_currently_applied = true; self->is_currently_applied = true;
} }
void patcher_restore_all(patcher_t *self){ void patcher_restore_all(patcher_t *self)
{
assert(self->is_currently_applied); assert(self->is_currently_applied);
assert(!_redq_ptr(self)->hooks_applied); assert(!_redq_ptr(self)->hooks_applied);
//assert(patcher_validate_patches(self)); // assert(patcher_validate_patches(self));
for(size_t i = 0; i < self->num_patches; i++){ for (size_t i = 0; i < self->num_patches; i++) {
_patcher_restore_patch(self, i); _patcher_restore_patch(self, i);
} }
self->is_currently_applied = false; self->is_currently_applied = false;
} }
void patcher_set_addrs(patcher_t *self, uint64_t* addrs, size_t num_addrs){ void patcher_set_addrs(patcher_t *self, uint64_t *addrs, size_t num_addrs)
{
_patcher_free_patch_infos(self); _patcher_free_patch_infos(self);
_patcher_alloc_patch_infos(self, num_addrs); _patcher_alloc_patch_infos(self, num_addrs);
uint8_t curr_instruction_code[MAX_INSTRUCTION_SIZE]; uint8_t curr_instruction_code[MAX_INSTRUCTION_SIZE];
memset(&curr_instruction_code[0], 0, MAX_INSTRUCTION_SIZE); memset(&curr_instruction_code[0], 0, MAX_INSTRUCTION_SIZE);
for(size_t i=0; i < self->num_patches; i++){ for (size_t i = 0; i < self->num_patches; i++) {
//nyx_debug_p(REDQUEEN_PREFIX, "patching %lx", addrs[i]); // nyx_debug_p(REDQUEEN_PREFIX, "patching %lx", addrs[i]);
if( read_virtual_memory(addrs[i], &curr_instruction_code[0], MAX_INSTRUCTION_SIZE, self->cpu) ) { if (read_virtual_memory(addrs[i], &curr_instruction_code[0],
size_t size =_patcher_disassemble_size(self, &curr_instruction_code[0], addrs[i], X86_INS_CMP); MAX_INSTRUCTION_SIZE, self->cpu))
assert(size != 0); //csopen failed, shouldn't happen {
size_t size = _patcher_disassemble_size(self, &curr_instruction_code[0],
addrs[i], X86_INS_CMP);
assert(size != 0); // csopen failed, shouldn't happen
_patcher_save_patch(self, i, &curr_instruction_code[0], size, addrs[i]); _patcher_save_patch(self, i, &curr_instruction_code[0], size, addrs[i]);
} }
} }
} }
static void print_hexdump(const uint8_t* addr, size_t size){ static void print_hexdump(const uint8_t *addr, size_t size)
for(size_t i = 0; i < size; i++){ {
printf (" %02x", addr[i]); for (size_t i = 0; i < size; i++) {
printf(" %02x", addr[i]);
} }
printf("\n"); printf("\n");
} }
bool patcher_validate_patches(patcher_t *self){ bool patcher_validate_patches(patcher_t *self)
{
bool was_rq = _redq_ptr(self)->hooks_applied; bool was_rq = _redq_ptr(self)->hooks_applied;
if(was_rq) if (was_rq)
redqueen_remove_hooks(_redq_ptr(self)); redqueen_remove_hooks(_redq_ptr(self));
if(!self->patches){return true;} if (!self->patches) {
for(size_t i=0; i<self->num_patches; i++){ return true;
}
for (size_t i = 0; i < self->num_patches; i++) {
uint8_t buf[MAX_INSTRUCTION_SIZE]; uint8_t buf[MAX_INSTRUCTION_SIZE];
read_virtual_memory(self->patches[i].addr, &buf[0], MAX_INSTRUCTION_SIZE, self->cpu); read_virtual_memory(self->patches[i].addr, &buf[0], MAX_INSTRUCTION_SIZE,
const uint8_t* should_value = NULL; self->cpu);
if(self->is_currently_applied){ const uint8_t *should_value = NULL;
if (self->is_currently_applied) {
should_value = cmp_patch; should_value = cmp_patch;
} else { } else {
should_value = &self->patches[i].orig_bytes[0]; should_value = &self->patches[i].orig_bytes[0];
@ -106,12 +128,14 @@ bool patcher_validate_patches(patcher_t *self){
print_hexdump(&buf[0], self->patches[i].size); print_hexdump(&buf[0], self->patches[i].size);
nyx_debug_p(REDQUEEN_PREFIX, "should_be:"); nyx_debug_p(REDQUEEN_PREFIX, "should_be:");
print_hexdump(should_value, self->patches[i].size); print_hexdump(should_value, self->patches[i].size);
if(0 != memcmp(&buf[0], should_value, self->patches[i].size)){ if (0 != memcmp(&buf[0], should_value, self->patches[i].size)) {
nyx_debug_p(REDQUEEN_PREFIX, "validating patches failed self->is_currently_applied = %d", self->is_currently_applied); nyx_debug_p(REDQUEEN_PREFIX,
"validating patches failed self->is_currently_applied = %d",
self->is_currently_applied);
return false; return false;
} }
} }
if(was_rq) if (was_rq)
redqueen_insert_hooks(_redq_ptr(self)); redqueen_insert_hooks(_redq_ptr(self));
return true; return true;
} }
@ -121,15 +145,22 @@ bool patcher_validate_patches(patcher_t *self){
* Private Helper Functions Definitions * Private Helper Functions Definitions
*/ */
static void _patcher_apply_patch(patcher_t *self, size_t index) { static void _patcher_apply_patch(patcher_t *self, size_t index)
{
abort(); // deprecated function -> remove this code later abort(); // deprecated function -> remove this code later
} }
static void _patcher_restore_patch(patcher_t *self, size_t index){ static void _patcher_restore_patch(patcher_t *self, size_t index)
{
abort(); // deprecated function -> remove this code later abort(); // deprecated function -> remove this code later
} }
static void _patcher_save_patch(patcher_t *self, size_t index, uint8_t* data, size_t instruction_size, uint64_t addr) { static void _patcher_save_patch(patcher_t *self,
size_t index,
uint8_t *data,
size_t instruction_size,
uint64_t addr)
{
assert(instruction_size >= 2); assert(instruction_size >= 2);
assert(instruction_size < MAX_INSTRUCTION_SIZE); assert(instruction_size < MAX_INSTRUCTION_SIZE);
patch_info_t *info = &self->patches[index]; patch_info_t *info = &self->patches[index];
@ -139,17 +170,24 @@ static void _patcher_save_patch(patcher_t *self, size_t index, uint8_t* data, si
info->size = instruction_size; info->size = instruction_size;
} }
static size_t _patcher_disassemble_size(patcher_t *self, uint8_t* data, uint64_t addr, x86_insn type){ static size_t _patcher_disassemble_size(patcher_t *self,
uint8_t *data,
uint64_t addr,
x86_insn type)
{
csh handle; csh handle;
if (cs_open(CS_ARCH_X86, get_capstone_mode(GET_GLOBAL_STATE()->disassembler_word_width), &handle) == CS_ERR_OK){ if (cs_open(CS_ARCH_X86,
get_capstone_mode(GET_GLOBAL_STATE()->disassembler_word_width),
&handle) == CS_ERR_OK)
{
cs_insn *insn = cs_malloc(handle); cs_insn *insn = cs_malloc(handle);
uint8_t* cur_offset = data; uint8_t *cur_offset = data;
uint64_t cs_address = addr; uint64_t cs_address = addr;
uint64_t code_size = MAX_INSTRUCTION_SIZE; uint64_t code_size = MAX_INSTRUCTION_SIZE;
cs_disasm_iter(handle, (const uint8_t **) &cur_offset, &code_size, &cs_address, insn); cs_disasm_iter(handle, (const uint8_t **)&cur_offset, &code_size,
&cs_address, insn);
size_t size = insn->size; size_t size = insn->size;
if(type != X86_INS_INVALID){ if (type != X86_INS_INVALID) {
assert(insn->id == type); assert(insn->id == type);
} }
cs_free(insn, 1); cs_free(insn, 1);
@ -159,22 +197,25 @@ static size_t _patcher_disassemble_size(patcher_t *self, uint8_t* data, uint64_t
return 0; return 0;
} }
static void _patcher_alloc_patch_infos(patcher_t *self, size_t num_patches){ static void _patcher_alloc_patch_infos(patcher_t *self, size_t num_patches)
{
assert(self->num_patches == 0); assert(self->num_patches == 0);
assert(self->patches == NULL); assert(self->patches == NULL);
assert(num_patches < 10000); assert(num_patches < 10000);
self->num_patches = num_patches; self->num_patches = num_patches;
self->patches = malloc(sizeof(patch_info_t)*num_patches); self->patches = malloc(sizeof(patch_info_t) * num_patches);
} }
static void _patcher_free_patch_infos(patcher_t *self){ static void _patcher_free_patch_infos(patcher_t *self)
{
assert(!self->is_currently_applied); assert(!self->is_currently_applied);
free(self->patches); free(self->patches);
self->patches = NULL; self->patches = NULL;
self->num_patches = 0; self->num_patches = 0;
} }
static redqueen_t* _redq_ptr(patcher_t *self){ static redqueen_t *_redq_ptr(patcher_t *self)
redqueen_t* res = GET_GLOBAL_STATE()->redqueen_state; //self->cpu->redqueen_state; {
redqueen_t *res = GET_GLOBAL_STATE()->redqueen_state; // self->cpu->redqueen_state;
return res; return res;
} }

View File

@ -1,8 +1,8 @@
#ifndef __GUARD_REDQUEEN_PATCHER_STRUCT__ #ifndef __GUARD_REDQUEEN_PATCHER_STRUCT__
#define __GUARD_REDQUEEN_PATCHER_STRUCT__ #define __GUARD_REDQUEEN_PATCHER_STRUCT__
#include <stdint.h>
#include <stddef.h> #include <stddef.h>
#include <stdint.h>
#include <capstone/capstone.h> #include <capstone/capstone.h>
#include <capstone/x86.h> #include <capstone/x86.h>
@ -15,16 +15,15 @@
* which always evaluates to true. This can be used to remove hash checks that * which always evaluates to true. This can be used to remove hash checks that
* we suspsect can later on be patched. * we suspsect can later on be patched.
*/ */
extern const uint8_t* cmp_patch; extern const uint8_t *cmp_patch;
typedef struct patch_info_s{ typedef struct patch_info_s {
uint64_t addr; uint64_t addr;
size_t size; size_t size;
uint8_t orig_bytes[MAX_INSTRUCTION_SIZE]; uint8_t orig_bytes[MAX_INSTRUCTION_SIZE];
} patch_info_t; } patch_info_t;
typedef struct patcher_s{ typedef struct patcher_s {
CPUState *cpu; CPUState *cpu;
patch_info_t *patches; patch_info_t *patches;
@ -32,7 +31,7 @@ typedef struct patcher_s{
bool is_currently_applied; bool is_currently_applied;
} patcher_t; } patcher_t;
patcher_t* patcher_new(CPUState *cpu); patcher_t *patcher_new(CPUState *cpu);
void patcher_free(patcher_t *self); void patcher_free(patcher_t *self);
@ -40,8 +39,8 @@ void patcher_apply_all(patcher_t *self);
void patcher_restore_all(patcher_t *self); void patcher_restore_all(patcher_t *self);
//Doesn't take ownership of addrs // Doesn't take ownership of addrs
void patcher_set_addrs(patcher_t *self, uint64_t* addrs, size_t num_addrs); void patcher_set_addrs(patcher_t *self, uint64_t *addrs, size_t num_addrs);
bool patcher_validate_patches(patcher_t *self); bool patcher_validate_patches(patcher_t *self);

205
nyx/pt.c
View File

@ -53,56 +53,67 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#define PT_BUFFER_MMAP_ADDR 0x3ffff0000000 #define PT_BUFFER_MMAP_ADDR 0x3ffff0000000
static void pt_set(CPUState *cpu, run_on_cpu_data arg){ static void pt_set(CPUState *cpu, run_on_cpu_data arg)
{
asm volatile("" ::: "memory"); asm volatile("" ::: "memory");
} }
static inline int pt_cmd_hmp_context(CPUState *cpu, uint64_t cmd){ static inline int pt_cmd_hmp_context(CPUState *cpu, uint64_t cmd)
{
cpu->pt_ret = -1; cpu->pt_ret = -1;
if(pt_hypercalls_enabled()){ if (pt_hypercalls_enabled()) {
nyx_debug_p(PT_PREFIX, "Error: HMP commands are ignored if kafl tracing mode is enabled (-kafl)!"); nyx_debug_p(PT_PREFIX, "Error: HMP commands are ignored if kafl tracing "
} "mode is enabled (-kafl)!");
else{ } else {
cpu->pt_cmd = cmd; cpu->pt_cmd = cmd;
run_on_cpu(cpu, pt_set, RUN_ON_CPU_NULL); run_on_cpu(cpu, pt_set, RUN_ON_CPU_NULL);
} }
return cpu->pt_ret; return cpu->pt_ret;
} }
static int pt_cmd(CPUState *cpu, uint64_t cmd, bool hmp_mode){ static int pt_cmd(CPUState *cpu, uint64_t cmd, bool hmp_mode)
if (hmp_mode){ {
if (hmp_mode) {
return pt_cmd_hmp_context(cpu, cmd); return pt_cmd_hmp_context(cpu, cmd);
} } else {
else {
cpu->pt_cmd = cmd; cpu->pt_cmd = cmd;
pt_pre_kvm_run(cpu); pt_pre_kvm_run(cpu);
return cpu->pt_ret; return cpu->pt_ret;
} }
} }
static inline int pt_ioctl(int fd, unsigned long request, unsigned long arg){ static inline int pt_ioctl(int fd, unsigned long request, unsigned long arg)
if (!fd){ {
if (!fd) {
return -EINVAL; return -EINVAL;
} }
return ioctl(fd, request, arg); return ioctl(fd, request, arg);
} }
void pt_dump(CPUState *cpu, int bytes){ void pt_dump(CPUState *cpu, int bytes)
if(!(GET_GLOBAL_STATE()->redqueen_state && GET_GLOBAL_STATE()->redqueen_state->intercept_mode)){ {
if (GET_GLOBAL_STATE()->in_fuzzing_mode && GET_GLOBAL_STATE()->decoder_page_fault == false && GET_GLOBAL_STATE()->decoder && !GET_GLOBAL_STATE()->dump_page){ if (!(GET_GLOBAL_STATE()->redqueen_state &&
GET_GLOBAL_STATE()->redqueen_state->intercept_mode))
{
if (GET_GLOBAL_STATE()->in_fuzzing_mode &&
GET_GLOBAL_STATE()->decoder_page_fault == false &&
GET_GLOBAL_STATE()->decoder && !GET_GLOBAL_STATE()->dump_page)
{
GET_GLOBAL_STATE()->pt_trace_size += bytes; GET_GLOBAL_STATE()->pt_trace_size += bytes;
pt_write_pt_dump_file(cpu->pt_mmap, bytes); pt_write_pt_dump_file(cpu->pt_mmap, bytes);
decoder_result_t result = libxdc_decode(GET_GLOBAL_STATE()->decoder, cpu->pt_mmap, bytes); decoder_result_t result =
switch(result){ libxdc_decode(GET_GLOBAL_STATE()->decoder, cpu->pt_mmap, bytes);
switch (result) {
case decoder_success: case decoder_success:
break; break;
case decoder_success_pt_overflow: case decoder_success_pt_overflow:
cpu->intel_pt_run_trashed = true; cpu->intel_pt_run_trashed = true;
break; break;
case decoder_page_fault: case decoder_page_fault:
//fprintf(stderr, "Page not found => 0x%lx\n", libxdc_get_page_fault_addr(GET_GLOBAL_STATE()->decoder)); // fprintf(stderr, "Page not found => 0x%lx\n", libxdc_get_page_fault_addr(GET_GLOBAL_STATE()->decoder));
GET_GLOBAL_STATE()->decoder_page_fault = true; GET_GLOBAL_STATE()->decoder_page_fault = true;
GET_GLOBAL_STATE()->decoder_page_fault_addr = libxdc_get_page_fault_addr(GET_GLOBAL_STATE()->decoder); GET_GLOBAL_STATE()->decoder_page_fault_addr =
libxdc_get_page_fault_addr(GET_GLOBAL_STATE()->decoder);
break; break;
case decoder_unkown_packet: case decoder_unkown_packet:
fprintf(stderr, "WARNING: libxdc_decode returned unknown_packet\n"); fprintf(stderr, "WARNING: libxdc_decode returned unknown_packet\n");
@ -116,8 +127,9 @@ void pt_dump(CPUState *cpu, int bytes){
} }
int pt_enable(CPUState *cpu, bool hmp_mode){ int pt_enable(CPUState *cpu, bool hmp_mode)
if(!fast_reload_set_bitmap(get_fast_reload_snapshot())){ {
if (!fast_reload_set_bitmap(get_fast_reload_snapshot())) {
coverage_bitmap_reset(); coverage_bitmap_reset();
} }
if (GET_GLOBAL_STATE()->trace_mode) { if (GET_GLOBAL_STATE()->trace_mode) {
@ -128,23 +140,25 @@ int pt_enable(CPUState *cpu, bool hmp_mode){
return pt_cmd(cpu, KVM_VMX_PT_ENABLE, hmp_mode); return pt_cmd(cpu, KVM_VMX_PT_ENABLE, hmp_mode);
} }
int pt_disable(CPUState *cpu, bool hmp_mode){ int pt_disable(CPUState *cpu, bool hmp_mode)
{
int r = pt_cmd(cpu, KVM_VMX_PT_DISABLE, hmp_mode); int r = pt_cmd(cpu, KVM_VMX_PT_DISABLE, hmp_mode);
return r; return r;
} }
int pt_set_cr3(CPUState *cpu, uint64_t val, bool hmp_mode){ int pt_set_cr3(CPUState *cpu, uint64_t val, bool hmp_mode)
{
int r = 0; int r = 0;
if (val == GET_GLOBAL_STATE()->pt_c3_filter){ if (val == GET_GLOBAL_STATE()->pt_c3_filter) {
return 0; // nothing changed return 0; // nothing changed
} }
if (cpu->pt_enabled){ if (cpu->pt_enabled) {
return -EINVAL; return -EINVAL;
} }
if (GET_GLOBAL_STATE()->pt_c3_filter && GET_GLOBAL_STATE()->pt_c3_filter != val){ if (GET_GLOBAL_STATE()->pt_c3_filter && GET_GLOBAL_STATE()->pt_c3_filter != val) {
//nyx_debug_p(PT_PREFIX, "Reconfigure CR3-Filtering!"); // nyx_debug_p(PT_PREFIX, "Reconfigure CR3-Filtering!");
GET_GLOBAL_STATE()->pt_c3_filter = val; GET_GLOBAL_STATE()->pt_c3_filter = val;
r += pt_cmd(cpu, KVM_VMX_PT_CONFIGURE_CR3, hmp_mode); r += pt_cmd(cpu, KVM_VMX_PT_CONFIGURE_CR3, hmp_mode);
r += pt_cmd(cpu, KVM_VMX_PT_ENABLE_CR3, hmp_mode); r += pt_cmd(cpu, KVM_VMX_PT_ENABLE_CR3, hmp_mode);
@ -156,38 +170,49 @@ int pt_set_cr3(CPUState *cpu, uint64_t val, bool hmp_mode){
return r; return r;
} }
int pt_enable_ip_filtering(CPUState *cpu, uint8_t addrn, bool redqueen, bool hmp_mode){ int pt_enable_ip_filtering(CPUState *cpu, uint8_t addrn, bool redqueen, bool hmp_mode)
{
int r = 0; int r = 0;
if(addrn > 3){ if (addrn > 3) {
return -1; return -1;
} }
if (cpu->pt_enabled){ if (cpu->pt_enabled) {
return -EINVAL; return -EINVAL;
} }
if(GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] > GET_GLOBAL_STATE()->pt_ip_filter_b[addrn]){ if (GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] >
nyx_debug_p(PT_PREFIX, "Error (ip_a > ip_b) 0x%lx-0x%lx", GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] , GET_GLOBAL_STATE()->pt_ip_filter_b[addrn]); GET_GLOBAL_STATE()->pt_ip_filter_b[addrn])
{
nyx_debug_p(PT_PREFIX, "Error (ip_a > ip_b) 0x%lx-0x%lx",
GET_GLOBAL_STATE()->pt_ip_filter_a[addrn],
GET_GLOBAL_STATE()->pt_ip_filter_b[addrn]);
return -EINVAL; return -EINVAL;
} }
if(GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn]){ if (GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn]) {
pt_disable_ip_filtering(cpu, addrn, hmp_mode); pt_disable_ip_filtering(cpu, addrn, hmp_mode);
} }
nyx_debug_p(PT_PREFIX, "Configuring new trace region (addr%d, 0x%lx-0x%lx)", addrn, GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] , GET_GLOBAL_STATE()->pt_ip_filter_b[addrn]); nyx_debug_p(PT_PREFIX, "Configuring new trace region (addr%d, 0x%lx-0x%lx)",
addrn, GET_GLOBAL_STATE()->pt_ip_filter_a[addrn],
GET_GLOBAL_STATE()->pt_ip_filter_b[addrn]);
if(GET_GLOBAL_STATE()->pt_ip_filter_configured[addrn] && GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] != 0 && GET_GLOBAL_STATE()->pt_ip_filter_b[addrn] != 0){ if (GET_GLOBAL_STATE()->pt_ip_filter_configured[addrn] &&
r += pt_cmd(cpu, KVM_VMX_PT_CONFIGURE_ADDR0+addrn, hmp_mode); GET_GLOBAL_STATE()->pt_ip_filter_a[addrn] != 0 &&
r += pt_cmd(cpu, KVM_VMX_PT_ENABLE_ADDR0+addrn, hmp_mode); GET_GLOBAL_STATE()->pt_ip_filter_b[addrn] != 0)
{
r += pt_cmd(cpu, KVM_VMX_PT_CONFIGURE_ADDR0 + addrn, hmp_mode);
r += pt_cmd(cpu, KVM_VMX_PT_ENABLE_ADDR0 + addrn, hmp_mode);
GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn] = true; GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn] = true;
} }
return r; return r;
} }
void pt_init_decoder(CPUState *cpu){ void pt_init_decoder(CPUState *cpu)
uint64_t filters[4][2] = {0}; {
uint64_t filters[4][2] = { 0 };
/* TODO time to clean up this code -.- */ /* TODO time to clean up this code -.- */
filters[0][0] = GET_GLOBAL_STATE()->pt_ip_filter_a[0]; filters[0][0] = GET_GLOBAL_STATE()->pt_ip_filter_a[0];
@ -202,24 +227,31 @@ void pt_init_decoder(CPUState *cpu){
assert(GET_GLOBAL_STATE()->decoder == NULL); assert(GET_GLOBAL_STATE()->decoder == NULL);
assert(GET_GLOBAL_STATE()->shared_bitmap_ptr != NULL); assert(GET_GLOBAL_STATE()->shared_bitmap_ptr != NULL);
assert(GET_GLOBAL_STATE()->shared_bitmap_size != 0); assert(GET_GLOBAL_STATE()->shared_bitmap_size != 0);
GET_GLOBAL_STATE()->decoder = libxdc_init(filters, (void* (*)(void*, uint64_t, bool*))page_cache_fetch2, GET_GLOBAL_STATE()->page_cache, GET_GLOBAL_STATE()->shared_bitmap_ptr, GET_GLOBAL_STATE()->shared_bitmap_size); GET_GLOBAL_STATE()->decoder =
libxdc_init(filters, (void *(*)(void *, uint64_t, bool *))page_cache_fetch2,
libxdc_register_bb_callback(GET_GLOBAL_STATE()->decoder, (void (*)(void*, disassembler_mode_t, uint64_t, uint64_t))redqueen_callback, GET_GLOBAL_STATE()->redqueen_state); GET_GLOBAL_STATE()->page_cache,
alt_bitmap_init(
GET_GLOBAL_STATE()->shared_bitmap_ptr, GET_GLOBAL_STATE()->shared_bitmap_ptr,
GET_GLOBAL_STATE()->shared_bitmap_size); GET_GLOBAL_STATE()->shared_bitmap_size);
libxdc_register_bb_callback(GET_GLOBAL_STATE()->decoder,
(void (*)(void *, disassembler_mode_t, uint64_t,
uint64_t))redqueen_callback,
GET_GLOBAL_STATE()->redqueen_state);
alt_bitmap_init(GET_GLOBAL_STATE()->shared_bitmap_ptr,
GET_GLOBAL_STATE()->shared_bitmap_size);
} }
int pt_disable_ip_filtering(CPUState *cpu, uint8_t addrn, bool hmp_mode){ int pt_disable_ip_filtering(CPUState *cpu, uint8_t addrn, bool hmp_mode)
{
int r = 0; int r = 0;
switch(addrn){ switch (addrn) {
case 0: case 0:
case 1: case 1:
case 2: case 2:
case 3: case 3:
r = pt_cmd(cpu, KVM_VMX_PT_DISABLE_ADDR0+addrn, hmp_mode); r = pt_cmd(cpu, KVM_VMX_PT_DISABLE_ADDR0 + addrn, hmp_mode);
if(GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn]){ if (GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn]) {
GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn] = false; GET_GLOBAL_STATE()->pt_ip_filter_enabled[addrn] = false;
} }
break; break;
@ -229,7 +261,8 @@ int pt_disable_ip_filtering(CPUState *cpu, uint8_t addrn, bool hmp_mode){
return r; return r;
} }
void pt_kvm_init(CPUState *cpu){ void pt_kvm_init(CPUState *cpu)
{
cpu->pt_cmd = 0; cpu->pt_cmd = 0;
cpu->pt_enabled = false; cpu->pt_enabled = false;
cpu->pt_fd = 0; cpu->pt_fd = 0;
@ -247,48 +280,51 @@ struct vmx_pt_filter_iprs {
pthread_mutex_t pt_dump_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t pt_dump_mutex = PTHREAD_MUTEX_INITIALIZER;
void pt_pre_kvm_run(CPUState *cpu){ void pt_pre_kvm_run(CPUState *cpu)
{
pthread_mutex_lock(&pt_dump_mutex); pthread_mutex_lock(&pt_dump_mutex);
int ret; int ret;
struct vmx_pt_filter_iprs filter_iprs; struct vmx_pt_filter_iprs filter_iprs;
if(GET_GLOBAL_STATE()->patches_disable_pending){ if (GET_GLOBAL_STATE()->patches_disable_pending) {
//nyx_debug_p(REDQUEEN_PREFIX, "patches disable"); // nyx_debug_p(REDQUEEN_PREFIX, "patches disable");
assert(false); /* remove this branch */ assert(false); /* remove this branch */
GET_GLOBAL_STATE()->patches_disable_pending = false; GET_GLOBAL_STATE()->patches_disable_pending = false;
} }
if(GET_GLOBAL_STATE()->patches_enable_pending){ if (GET_GLOBAL_STATE()->patches_enable_pending) {
//nyx_debug_p(REDQUEEN_PREFIX, "patches enable"); // nyx_debug_p(REDQUEEN_PREFIX, "patches enable");
assert(false); /* remove this branch */ assert(false); /* remove this branch */
GET_GLOBAL_STATE()->patches_enable_pending = false; GET_GLOBAL_STATE()->patches_enable_pending = false;
} }
if(GET_GLOBAL_STATE()->redqueen_enable_pending){ if (GET_GLOBAL_STATE()->redqueen_enable_pending) {
//nyx_debug_p(REDQUEEN_PREFIX, "rq enable"); // nyx_debug_p(REDQUEEN_PREFIX, "rq enable");
if (GET_GLOBAL_STATE()->redqueen_state){ if (GET_GLOBAL_STATE()->redqueen_state) {
enable_rq_intercept_mode(GET_GLOBAL_STATE()->redqueen_state); enable_rq_intercept_mode(GET_GLOBAL_STATE()->redqueen_state);
} }
GET_GLOBAL_STATE()->redqueen_enable_pending = false; GET_GLOBAL_STATE()->redqueen_enable_pending = false;
} }
if(GET_GLOBAL_STATE()->redqueen_disable_pending){ if (GET_GLOBAL_STATE()->redqueen_disable_pending) {
//nyx_debug_p(REDQUEEN_PREFIX, "rq disable"); // nyx_debug_p(REDQUEEN_PREFIX, "rq disable");
if (GET_GLOBAL_STATE()->redqueen_state){ if (GET_GLOBAL_STATE()->redqueen_state) {
disable_rq_intercept_mode(GET_GLOBAL_STATE()->redqueen_state); disable_rq_intercept_mode(GET_GLOBAL_STATE()->redqueen_state);
} }
GET_GLOBAL_STATE()->redqueen_disable_pending = false; GET_GLOBAL_STATE()->redqueen_disable_pending = false;
} }
if(GET_GLOBAL_STATE()->pt_trace_mode || GET_GLOBAL_STATE()->pt_trace_mode_force){ if (GET_GLOBAL_STATE()->pt_trace_mode || GET_GLOBAL_STATE()->pt_trace_mode_force)
{
if (!cpu->pt_fd) { if (!cpu->pt_fd) {
cpu->pt_fd = kvm_vcpu_ioctl(cpu, KVM_VMX_PT_SETUP_FD, (unsigned long)0); cpu->pt_fd = kvm_vcpu_ioctl(cpu, KVM_VMX_PT_SETUP_FD, (unsigned long)0);
assert(cpu->pt_fd != -1); assert(cpu->pt_fd != -1);
ret = ioctl(cpu->pt_fd, KVM_VMX_PT_GET_TOPA_SIZE, (unsigned long)0x0); ret = ioctl(cpu->pt_fd, KVM_VMX_PT_GET_TOPA_SIZE, (unsigned long)0x0);
cpu->pt_mmap = mmap((void*)PT_BUFFER_MMAP_ADDR, ret, PROT_READ|PROT_WRITE, MAP_SHARED, cpu->pt_fd, 0); cpu->pt_mmap = mmap((void *)PT_BUFFER_MMAP_ADDR, ret,
assert(cpu->pt_mmap != (void*)0xFFFFFFFFFFFFFFFF); PROT_READ | PROT_WRITE, MAP_SHARED, cpu->pt_fd, 0);
assert(cpu->pt_mmap != (void *)0xFFFFFFFFFFFFFFFF);
// add an extra page to have enough space for an additional PT_TRACE_END byte // add an extra page to have enough space for an additional PT_TRACE_END byte
assert(mmap(cpu->pt_mmap + ret, 0x1000, PROT_READ | PROT_WRITE, assert(mmap(cpu->pt_mmap + ret, 0x1000, PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_FIXED | MAP_PRIVATE, -1, MAP_ANONYMOUS | MAP_FIXED | MAP_PRIVATE, -1,
@ -296,26 +332,27 @@ void pt_pre_kvm_run(CPUState *cpu){
nyx_debug("=> pt_mmap: %p - %p\n", cpu->pt_mmap, cpu->pt_mmap + ret); nyx_debug("=> pt_mmap: %p - %p\n", cpu->pt_mmap, cpu->pt_mmap + ret);
memset(cpu->pt_mmap+ret, 0x55, 0x1000); memset(cpu->pt_mmap + ret, 0x55, 0x1000);
} }
if (cpu->pt_cmd){ if (cpu->pt_cmd) {
switch(cpu->pt_cmd){ switch (cpu->pt_cmd) {
case KVM_VMX_PT_ENABLE: case KVM_VMX_PT_ENABLE:
if (cpu->pt_fd){ if (cpu->pt_fd) {
/* dump for the very last time before enabling VMX_PT ... just in case */ /* dump for the very last time before enabling VMX_PT ... just in case */
ioctl(cpu->pt_fd, KVM_VMX_PT_CHECK_TOPA_OVERFLOW, (unsigned long)0); ioctl(cpu->pt_fd, KVM_VMX_PT_CHECK_TOPA_OVERFLOW,
(unsigned long)0);
if (!ioctl(cpu->pt_fd, cpu->pt_cmd, 0)){ if (!ioctl(cpu->pt_fd, cpu->pt_cmd, 0)) {
cpu->pt_enabled = true; cpu->pt_enabled = true;
} }
} }
break; break;
case KVM_VMX_PT_DISABLE: case KVM_VMX_PT_DISABLE:
if (cpu->pt_fd){ if (cpu->pt_fd) {
ret = ioctl(cpu->pt_fd, cpu->pt_cmd, 0); ret = ioctl(cpu->pt_fd, cpu->pt_cmd, 0);
if (ret > 0){ if (ret > 0) {
//nyx_debug_p(PT_PREFIX, "KVM_VMX_PT_DISABLE %d", ret); // nyx_debug_p(PT_PREFIX, "KVM_VMX_PT_DISABLE %d", ret);
pt_dump(cpu, ret); pt_dump(cpu, ret);
cpu->pt_enabled = false; cpu->pt_enabled = false;
} }
@ -327,8 +364,12 @@ void pt_pre_kvm_run(CPUState *cpu){
case KVM_VMX_PT_CONFIGURE_ADDR1: case KVM_VMX_PT_CONFIGURE_ADDR1:
case KVM_VMX_PT_CONFIGURE_ADDR2: case KVM_VMX_PT_CONFIGURE_ADDR2:
case KVM_VMX_PT_CONFIGURE_ADDR3: case KVM_VMX_PT_CONFIGURE_ADDR3:
filter_iprs.a = GET_GLOBAL_STATE()->pt_ip_filter_a[(cpu->pt_cmd)-KVM_VMX_PT_CONFIGURE_ADDR0]; filter_iprs.a =
filter_iprs.b = GET_GLOBAL_STATE()->pt_ip_filter_b[(cpu->pt_cmd)-KVM_VMX_PT_CONFIGURE_ADDR0]; GET_GLOBAL_STATE()
->pt_ip_filter_a[(cpu->pt_cmd) - KVM_VMX_PT_CONFIGURE_ADDR0];
filter_iprs.b =
GET_GLOBAL_STATE()
->pt_ip_filter_b[(cpu->pt_cmd) - KVM_VMX_PT_CONFIGURE_ADDR0];
ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)&filter_iprs); ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)&filter_iprs);
break; break;
case KVM_VMX_PT_ENABLE_ADDR0: case KVM_VMX_PT_ENABLE_ADDR0:
@ -338,13 +379,14 @@ void pt_pre_kvm_run(CPUState *cpu){
ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)0); ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)0);
break; break;
case KVM_VMX_PT_CONFIGURE_CR3: case KVM_VMX_PT_CONFIGURE_CR3:
ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, GET_GLOBAL_STATE()->pt_c3_filter); ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd,
GET_GLOBAL_STATE()->pt_c3_filter);
break; break;
case KVM_VMX_PT_ENABLE_CR3: case KVM_VMX_PT_ENABLE_CR3:
ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)0); ret = pt_ioctl(cpu->pt_fd, cpu->pt_cmd, (unsigned long)0);
break; break;
default: default:
if (cpu->pt_fd){ if (cpu->pt_fd) {
ioctl(cpu->pt_fd, cpu->pt_cmd, 0); ioctl(cpu->pt_fd, cpu->pt_cmd, 0);
} }
break; break;
@ -356,17 +398,20 @@ void pt_pre_kvm_run(CPUState *cpu){
pthread_mutex_unlock(&pt_dump_mutex); pthread_mutex_unlock(&pt_dump_mutex);
} }
void pt_handle_overflow(CPUState *cpu){ void pt_handle_overflow(CPUState *cpu)
{
pthread_mutex_lock(&pt_dump_mutex); pthread_mutex_lock(&pt_dump_mutex);
int overflow = ioctl(cpu->pt_fd, KVM_VMX_PT_CHECK_TOPA_OVERFLOW, (unsigned long)0); int overflow = ioctl(cpu->pt_fd, KVM_VMX_PT_CHECK_TOPA_OVERFLOW, (unsigned long)0);
if (overflow > 0){ if (overflow > 0) {
pt_dump(cpu, overflow); pt_dump(cpu, overflow);
} }
pthread_mutex_unlock(&pt_dump_mutex); pthread_mutex_unlock(&pt_dump_mutex);
} }
void pt_post_kvm_run(CPUState *cpu){ void pt_post_kvm_run(CPUState *cpu)
if(GET_GLOBAL_STATE()->pt_trace_mode || GET_GLOBAL_STATE()->pt_trace_mode_force){ {
if (GET_GLOBAL_STATE()->pt_trace_mode || GET_GLOBAL_STATE()->pt_trace_mode_force)
{
pt_handle_overflow(cpu); pt_handle_overflow(cpu);
} }
} }

View File

@ -38,4 +38,3 @@ void pt_handle_overflow(CPUState *cpu);
void pt_dump(CPUState *cpu, int bytes); void pt_dump(CPUState *cpu, int bytes);
#endif #endif

File diff suppressed because it is too large Load Diff

View File

@ -22,26 +22,26 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#pragma once #pragma once
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <linux/kvm.h>
#include <capstone/capstone.h>
#include <capstone/x86.h>
#include "nyx/redqueen_trace.h"
#include "nyx/khash.h" #include "nyx/khash.h"
#include "nyx/page_cache.h" #include "nyx/page_cache.h"
#include "nyx/redqueen_trace.h"
#include <capstone/capstone.h>
#include <capstone/x86.h>
#include <linux/kvm.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
//#define RQ_DEBUG // #define RQ_DEBUG
#define REDQUEEN_MAX_STRCMP_LEN 64 #define REDQUEEN_MAX_STRCMP_LEN 64
#define REDQUEEN_TRAP_LIMIT 16 #define REDQUEEN_TRAP_LIMIT 16
#define REG64_NUM 16 #define REG64_NUM 16
#define REG32_NUM 16 #define REG32_NUM 16
//seems we don't want to include rip, since this index is used to acces the qemu cpu structure or something? // seems we don't want to include rip, since this index is used to acces the qemu cpu structure or something?
#define REG16_NUM 16 #define REG16_NUM 16
#define REG8L_NUM 16 #define REG8L_NUM 16
#define REG8H_NUM 8 #define REG8H_NUM 8
@ -54,20 +54,38 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#define REDQUEEN_SE_INSTRUMENTATION 2 #define REDQUEEN_SE_INSTRUMENTATION 2
#define REDQUEEN_WHITELIST_INSTRUMENTATION 3 #define REDQUEEN_WHITELIST_INSTRUMENTATION 3
enum reg_types{RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15}; enum reg_types {
RAX,
RCX,
RDX,
RBX,
RSP,
RBP,
RSI,
RDI,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15
};
#define CMP_BITMAP_NOP 0x0000000UL #define CMP_BITMAP_NOP 0x0000000UL
#define CMP_BITMAP_RQ_INSTRUCTION 0x1000000UL #define CMP_BITMAP_RQ_INSTRUCTION 0x1000000UL
#define CMP_BITMAP_SE_INSTRUCTION 0x2000000UL #define CMP_BITMAP_SE_INSTRUCTION 0x2000000UL
#define CMP_BITMAP_BLACKLISTED 0x4000000UL #define CMP_BITMAP_BLACKLISTED 0x4000000UL
#define CMP_BITMAP_TRACE_ENABLED 0x8000000UL #define CMP_BITMAP_TRACE_ENABLED 0x8000000UL
#define CMP_BITMAP_SHOULD_HOOK_SE (CMP_BITMAP_SE_INSTRUCTION|CMP_BITMAP_TRACE_ENABLED) #define CMP_BITMAP_SHOULD_HOOK_SE \
(CMP_BITMAP_SE_INSTRUCTION | CMP_BITMAP_TRACE_ENABLED)
#define CMP_BITMAP_SHOULD_HOOK_RQ (CMP_BITMAP_RQ_INSTRUCTION) #define CMP_BITMAP_SHOULD_HOOK_RQ (CMP_BITMAP_RQ_INSTRUCTION)
KHASH_MAP_INIT_INT64(RQ, uint32_t) KHASH_MAP_INIT_INT64(RQ, uint32_t)
typedef struct redqueen_s{ typedef struct redqueen_s {
khash_t(RQ) *lookup; khash_t(RQ) * lookup;
bool intercept_mode; bool intercept_mode;
bool singlestep_enabled; bool singlestep_enabled;
int hooks_applied; int hooks_applied;
@ -76,46 +94,48 @@ typedef struct redqueen_s{
uint64_t next_rip; uint64_t next_rip;
uint64_t *breakpoint_whitelist; uint64_t *breakpoint_whitelist;
uint64_t num_breakpoint_whitelist; uint64_t num_breakpoint_whitelist;
redqueen_trace_t* trace_state; redqueen_trace_t *trace_state;
page_cache_t* page_cache; page_cache_t *page_cache;
} redqueen_t; } redqueen_t;
typedef struct redqueen_workdir_s{ typedef struct redqueen_workdir_s {
char* redqueen_results; char *redqueen_results;
char* symbolic_results; char *symbolic_results;
char* pt_trace_results; char *pt_trace_results;
char* redqueen_patches; char *redqueen_patches;
char* breakpoint_white; char *breakpoint_white;
char* breakpoint_black; char *breakpoint_black;
char* target_code_dump; char *target_code_dump;
} redqueen_workdir_t; } redqueen_workdir_t;
extern redqueen_workdir_t redqueen_workdir; extern redqueen_workdir_t redqueen_workdir;
void setup_redqueen_workdir(char* workdir); void setup_redqueen_workdir(char *workdir);
redqueen_t* new_rq_state(CPUState *cpu, page_cache_t* page_cache); redqueen_t *new_rq_state(CPUState *cpu, page_cache_t *page_cache);
void destroy_rq_state(redqueen_t* self); void destroy_rq_state(redqueen_t *self);
void set_rq_instruction(redqueen_t* self, uint64_t addr); void set_rq_instruction(redqueen_t *self, uint64_t addr);
void set_rq_blacklist(redqueen_t* self, uint64_t addr); void set_rq_blacklist(redqueen_t *self, uint64_t addr);
void handle_hook(redqueen_t* self); void handle_hook(redqueen_t *self);
void handel_se_hook(redqueen_t* self); void handel_se_hook(redqueen_t *self);
void enable_rq_intercept_mode(redqueen_t* self); void enable_rq_intercept_mode(redqueen_t *self);
void disable_rq_intercept_mode(redqueen_t* self); void disable_rq_intercept_mode(redqueen_t *self);
void set_se_instruction(redqueen_t* self, uint64_t addr); void set_se_instruction(redqueen_t *self, uint64_t addr);
void dump_se_registers(redqueen_t* self); void dump_se_registers(redqueen_t *self);
void dump_se_memory_access(redqueen_t* self, cs_insn* insn); void dump_se_memory_access(redqueen_t *self, cs_insn *insn);
void dump_se_return_access(redqueen_t* self, cs_insn* insn); void dump_se_return_access(redqueen_t *self, cs_insn *insn);
void dump_se_memory_access_at(redqueen_t* self, uint64_t instr_addr, uint64_t mem_addr); void dump_se_memory_access_at(redqueen_t *self, uint64_t instr_addr, uint64_t mem_addr);
void redqueen_insert_hooks(redqueen_t* self); void redqueen_insert_hooks(redqueen_t *self);
void redqueen_remove_hooks(redqueen_t* self); void redqueen_remove_hooks(redqueen_t *self);
void redqueen_callback(void* opaque, disassembler_mode_t mode, uint64_t start_addr, uint64_t end_addr);
void redqueen_callback(void *opaque,
disassembler_mode_t mode,
uint64_t start_addr,
uint64_t end_addr);

View File

@ -1,26 +1,28 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "redqueen_patch.h" #include "redqueen_patch.h"
#include "redqueen.h"
#include "patcher.h"
#include "file_helper.h"
#include "debug.h" #include "debug.h"
#include "file_helper.h"
#include "patcher.h"
#include "redqueen.h"
/* /*
* Private Helper Functions Declarations * Private Helper Functions Declarations
*/ */
void _load_and_set_patches(patcher_t* self); void _load_and_set_patches(patcher_t *self);
/* /*
* Public Functions * Public Functions
*/ */
void pt_enable_patches(patcher_t *self){ void pt_enable_patches(patcher_t *self)
{
_load_and_set_patches(self); _load_and_set_patches(self);
patcher_apply_all(self); patcher_apply_all(self);
} }
void pt_disable_patches(patcher_t *self){ void pt_disable_patches(patcher_t *self)
{
patcher_restore_all(self); patcher_restore_all(self);
} }
@ -30,11 +32,12 @@ void pt_disable_patches(patcher_t *self){
*/ */
void _load_and_set_patches(patcher_t* self){ void _load_and_set_patches(patcher_t *self)
{
size_t num_addrs = 0; size_t num_addrs = 0;
uint64_t *addrs = NULL; uint64_t *addrs = NULL;
parse_address_file(redqueen_workdir.redqueen_patches, &num_addrs, &addrs); parse_address_file(redqueen_workdir.redqueen_patches, &num_addrs, &addrs);
if(num_addrs){ if (num_addrs) {
patcher_set_addrs(self, addrs, num_addrs); patcher_set_addrs(self, addrs, num_addrs);
free(addrs); free(addrs);
} }

View File

@ -1,27 +1,27 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h> #include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include "redqueen_trace.h"
#include "redqueen.h" #include "redqueen.h"
#include "redqueen_trace.h"
#include "state/state.h" #include "state/state.h"
/* write full trace of edge transitions rather than sorted list? */ /* write full trace of edge transitions rather than sorted list? */
//#define KAFL_FULL_TRACES // #define KAFL_FULL_TRACES
int trace_fd = 0; int trace_fd = 0;
int redqueen_trace_enabled = false; int redqueen_trace_enabled = false;
uint32_t alt_bitmap_size = 0; uint32_t alt_bitmap_size = 0;
uint8_t* alt_bitmap = NULL; uint8_t *alt_bitmap = NULL;
void alt_bitmap_init(void* ptr, uint32_t size) void alt_bitmap_init(void *ptr, uint32_t size)
{ {
if (redqueen_trace_enabled) { if (redqueen_trace_enabled) {
alt_bitmap = (uint8_t*)ptr; alt_bitmap = (uint8_t *)ptr;
alt_bitmap_size = size; alt_bitmap_size = size;
} }
} }
@ -33,7 +33,8 @@ void alt_bitmap_reset(void)
} }
} }
static inline uint64_t mix_bits(uint64_t v) { static inline uint64_t mix_bits(uint64_t v)
{
v ^= (v >> 31); v ^= (v >> 31);
v *= 0x7fb5d329728ea185; v *= 0x7fb5d329728ea185;
return v; return v;
@ -48,18 +49,20 @@ static void alt_bitmap_add(uint64_t from, uint64_t to)
uint64_t transition_value; uint64_t transition_value;
if (GET_GLOBAL_STATE()->trace_mode) { if (GET_GLOBAL_STATE()->trace_mode) {
if(alt_bitmap) { if (alt_bitmap) {
transition_value = mix_bits(to)^(mix_bits(from)>>1); transition_value = mix_bits(to) ^ (mix_bits(from) >> 1);
alt_bitmap[transition_value & (alt_bitmap_size-1)]++; alt_bitmap[transition_value & (alt_bitmap_size - 1)]++;
} }
} }
} }
static int reset_trace_fd(void) { static int reset_trace_fd(void)
{
if (trace_fd) if (trace_fd)
close(trace_fd); close(trace_fd);
trace_fd = open(redqueen_workdir.pt_trace_results, O_WRONLY | O_CREAT | O_TRUNC, 0644); trace_fd =
open(redqueen_workdir.pt_trace_results, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (trace_fd < 0) { if (trace_fd < 0) {
fprintf(stderr, "Failed to initiate trace output: %s\n", strerror(errno)); fprintf(stderr, "Failed to initiate trace output: %s\n", strerror(errno));
assert(0); assert(0);
@ -67,26 +70,34 @@ static int reset_trace_fd(void) {
return trace_fd; return trace_fd;
} }
void redqueen_trace_init(void) { void redqueen_trace_init(void)
{
redqueen_trace_enabled = true; redqueen_trace_enabled = true;
} }
redqueen_trace_t* redqueen_trace_new(void){ redqueen_trace_t *redqueen_trace_new(void)
redqueen_trace_t* self = malloc(sizeof(redqueen_trace_t)); {
redqueen_trace_t *self = malloc(sizeof(redqueen_trace_t));
self->lookup = kh_init(RQ_TRACE); self->lookup = kh_init(RQ_TRACE);
self->num_ordered_transitions = 0; self->num_ordered_transitions = 0;
self->max_ordered_transitions = INIT_NUM_OF_STORED_TRANSITIONS; self->max_ordered_transitions = INIT_NUM_OF_STORED_TRANSITIONS;
self->ordered_transitions = malloc(INIT_NUM_OF_STORED_TRANSITIONS*sizeof(uint128_t)); self->ordered_transitions =
malloc(INIT_NUM_OF_STORED_TRANSITIONS * sizeof(uint128_t));
return self; return self;
} }
void redqueen_trace_free(redqueen_trace_t* self){ void redqueen_trace_free(redqueen_trace_t *self)
{
kh_destroy(RQ_TRACE, self->lookup); kh_destroy(RQ_TRACE, self->lookup);
free(self->ordered_transitions); free(self->ordered_transitions);
free(self); free(self);
} }
void redqueen_trace_register_transition(redqueen_trace_t* self, disassembler_mode_t mode, uint64_t from, uint64_t to){ void redqueen_trace_register_transition(redqueen_trace_t *self,
disassembler_mode_t mode,
uint64_t from,
uint64_t to)
{
khiter_t k; khiter_t k;
int ret; int ret;
uint64_t exit_ip = 0xffffffffffffffff; uint64_t exit_ip = 0xffffffffffffffff;
@ -98,11 +109,11 @@ void redqueen_trace_register_transition(redqueen_trace_t* self, disassembler_mod
dprintf(trace_fd, "%lx,%lx\n", from, to); dprintf(trace_fd, "%lx,%lx\n", from, to);
return; return;
#endif #endif
uint128_t key = (((uint128_t)from)<<64) | ((uint128_t)to); uint128_t key = (((uint128_t)from) << 64) | ((uint128_t)to);
k = kh_get(RQ_TRACE, self->lookup, key); k = kh_get(RQ_TRACE, self->lookup, key);
if(k != kh_end(self->lookup)){ if (k != kh_end(self->lookup)) {
kh_value(self->lookup, k) += 1; kh_value(self->lookup, k) += 1;
} else{ } else {
k = kh_put(RQ_TRACE, self->lookup, key, &ret); k = kh_put(RQ_TRACE, self->lookup, key, &ret);
kh_value(self->lookup, k) = 1; kh_value(self->lookup, k) = 1;
self->ordered_transitions[self->num_ordered_transitions] = key; self->ordered_transitions[self->num_ordered_transitions] = key;
@ -111,22 +122,25 @@ void redqueen_trace_register_transition(redqueen_trace_t* self, disassembler_mod
} }
} }
static void redqueen_trace_write(void){ static void redqueen_trace_write(void)
{
#ifdef KAFL_FULL_TRACES #ifdef KAFL_FULL_TRACES
return; return;
#endif #endif
redqueen_trace_t *self = GET_GLOBAL_STATE()->redqueen_state->trace_state; redqueen_trace_t *self = GET_GLOBAL_STATE()->redqueen_state->trace_state;
assert(trace_fd >= 0); assert(trace_fd >= 0);
for(size_t i = 0; i < self->num_ordered_transitions; i++){ for (size_t i = 0; i < self->num_ordered_transitions; i++) {
khiter_t k; khiter_t k;
uint128_t key = self->ordered_transitions[i]; uint128_t key = self->ordered_transitions[i];
k = kh_get(RQ_TRACE, self->lookup, key); k = kh_get(RQ_TRACE, self->lookup, key);
assert(k != kh_end(self->lookup)); assert(k != kh_end(self->lookup));
dprintf(trace_fd, "%lx,%lx,%lx\n", (uint64_t)(key>>64), (uint64_t)key, kh_value(self->lookup, k) ); dprintf(trace_fd, "%lx,%lx,%lx\n", (uint64_t)(key >> 64), (uint64_t)key,
kh_value(self->lookup, k));
} }
} }
static void redqueen_state_reset(void){ static void redqueen_state_reset(void)
{
redqueen_trace_t *self = GET_GLOBAL_STATE()->redqueen_state->trace_state; redqueen_trace_t *self = GET_GLOBAL_STATE()->redqueen_state->trace_state;
kh_destroy(RQ_TRACE, self->lookup); kh_destroy(RQ_TRACE, self->lookup);
self->lookup = kh_init(RQ_TRACE); self->lookup = kh_init(RQ_TRACE);
@ -134,14 +148,16 @@ static void redqueen_state_reset(void){
} }
void redqueen_trace_reset(void){ void redqueen_trace_reset(void)
{
if (redqueen_trace_enabled) { if (redqueen_trace_enabled) {
redqueen_state_reset(); redqueen_state_reset();
reset_trace_fd(); reset_trace_fd();
} }
} }
void redqueen_trace_flush(void){ void redqueen_trace_flush(void)
{
if (redqueen_trace_enabled) { if (redqueen_trace_enabled) {
redqueen_trace_write(); redqueen_trace_write();
if (trace_fd) if (trace_fd)
@ -149,32 +165,36 @@ void redqueen_trace_flush(void){
} }
} }
void redqueen_set_trace_mode(void){ void redqueen_set_trace_mode(void)
{
if (redqueen_trace_enabled) { if (redqueen_trace_enabled) {
libxdc_enable_tracing(GET_GLOBAL_STATE()->decoder); libxdc_enable_tracing(GET_GLOBAL_STATE()->decoder);
libxdc_register_edge_callback(GET_GLOBAL_STATE()->decoder, libxdc_register_edge_callback(GET_GLOBAL_STATE()->decoder,
(void (*)(void*, disassembler_mode_t, uint64_t, uint64_t))&redqueen_trace_register_transition, (void (*)(void *, disassembler_mode_t,
uint64_t, uint64_t)) &
redqueen_trace_register_transition,
GET_GLOBAL_STATE()->redqueen_state->trace_state); GET_GLOBAL_STATE()->redqueen_state->trace_state);
} }
} }
void redqueen_unset_trace_mode(void){ void redqueen_unset_trace_mode(void)
{
if (redqueen_trace_enabled) { if (redqueen_trace_enabled) {
libxdc_disable_tracing(GET_GLOBAL_STATE()->decoder); libxdc_disable_tracing(GET_GLOBAL_STATE()->decoder);
} }
} }
#ifdef DEBUG_MAIN #ifdef DEBUG_MAIN
int main(int argc, char** argv){ int main(int argc, char **argv)
{
redqueen_trace_t* rq_obj = redqueen_trace_new(); redqueen_trace_t *rq_obj = redqueen_trace_new();
reset_trace_fd(); reset_trace_fd();
for (uint64_t j = 0; j < 0x5; j++){ for (uint64_t j = 0; j < 0x5; j++) {
redqueen_trace_register_transition(rq_obj, 0xBADF, 0xC0FFEE); redqueen_trace_register_transition(rq_obj, 0xBADF, 0xC0FFEE);
redqueen_trace_register_transition(rq_obj, 0xBADBEEF, 0xC0FFEE); redqueen_trace_register_transition(rq_obj, 0xBADBEEF, 0xC0FFEE);
for (uint64_t i = 0; i < 0x10000; i++){ for (uint64_t i = 0; i < 0x10000; i++) {
redqueen_trace_register_transition(rq_obj, 0xBADBEEF, 0xC0FFEE); redqueen_trace_register_transition(rq_obj, 0xBADBEEF, 0xC0FFEE);
} }
redqueen_trace_write(rq_obj, STDOUT_FILENO); redqueen_trace_write(rq_obj, STDOUT_FILENO);

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include "qemu/osdep.h" #include "qemu/osdep.h"
@ -21,7 +21,8 @@ typedef uint128_t khint128_t;
@return The hash value [khint_t] @return The hash value [khint_t]
*/ */
#define kh_int128_hash_func(key) \ #define kh_int128_hash_func(key) \
(khint32_t)((key) >> 33 ^ (key) ^ (key) << 11) ^ (((key >> 64)) >> 33 ^ ((key >> 64)) ^ ((key >> 64)) << 11) (khint32_t)((key) >> 33 ^ (key) ^ (key) << 11) ^ \
(((key >> 64)) >> 33 ^ ((key >> 64)) ^ ((key >> 64)) << 11)
/*! @function /*! @function
@abstract 64-bit integer comparison function @abstract 64-bit integer comparison function
*/ */
@ -33,26 +34,30 @@ typedef uint128_t khint128_t;
@param khval_t Type of values [type] @param khval_t Type of values [type]
*/ */
#define KHASH_MAP_INIT_INT128(name, khval_t) \ #define KHASH_MAP_INIT_INT128(name, khval_t) \
KHASH_INIT(name, khint128_t, khval_t, 1, kh_int128_hash_func, kh_int128_hash_equal) KHASH_INIT(name, khint128_t, khval_t, 1, kh_int128_hash_func, \
kh_int128_hash_equal)
KHASH_MAP_INIT_INT128(RQ_TRACE, uint64_t) KHASH_MAP_INIT_INT128(RQ_TRACE, uint64_t)
#define INIT_TRACE_IP 0xFFFFFFFFFFFFFFFFULL #define INIT_TRACE_IP 0xFFFFFFFFFFFFFFFFULL
typedef struct redqueen_trace_s{ typedef struct redqueen_trace_s {
khash_t(RQ_TRACE) *lookup; khash_t(RQ_TRACE) * lookup;
size_t num_ordered_transitions; size_t num_ordered_transitions;
size_t max_ordered_transitions; size_t max_ordered_transitions;
uint128_t* ordered_transitions; uint128_t *ordered_transitions;
} redqueen_trace_t; } redqueen_trace_t;
/* libxdc outputs no bitmap in trace mode */ /* libxdc outputs no bitmap in trace mode */
void alt_bitmap_reset(void); void alt_bitmap_reset(void);
void alt_bitmap_init(void* ptr, uint32_t size); void alt_bitmap_init(void *ptr, uint32_t size);
redqueen_trace_t* redqueen_trace_new(void); redqueen_trace_t *redqueen_trace_new(void);
void redqueen_trace_free(redqueen_trace_t* self); void redqueen_trace_free(redqueen_trace_t *self);
void redqueen_trace_register_transition(redqueen_trace_t* self, disassembler_mode_t mode, uint64_t from, uint64_t to); void redqueen_trace_register_transition(redqueen_trace_t *self,
disassembler_mode_t mode,
uint64_t from,
uint64_t to);
void redqueen_trace_init(void); void redqueen_trace_init(void);
void redqueen_set_trace_mode(void); void redqueen_set_trace_mode(void);

View File

@ -11,10 +11,11 @@
#include "nyx/debug.h" #include "nyx/debug.h"
#include "sharedir.h" #include "sharedir.h"
//#define SHAREDIR_DEBUG // #define SHAREDIR_DEBUG
sharedir_t* sharedir_new(void){ sharedir_t *sharedir_new(void)
sharedir_t* self = malloc(sizeof(sharedir_t)); {
sharedir_t *self = malloc(sizeof(sharedir_t));
self->dir = NULL; self->dir = NULL;
self->lookup = kh_init(SHAREDIR_LOOKUP); self->lookup = kh_init(SHAREDIR_LOOKUP);
self->last_file_f = NULL; self->last_file_f = NULL;
@ -22,39 +23,43 @@ sharedir_t* sharedir_new(void){
return self; return self;
} }
void sharedir_set_dir(sharedir_t* self, const char* dir){ void sharedir_set_dir(sharedir_t *self, const char *dir)
{
assert(!self->dir); assert(!self->dir);
assert(asprintf(&self->dir, "%s", dir) != -1); assert(asprintf(&self->dir, "%s", dir) != -1);
} }
static bool file_exits(const char* file){ static bool file_exits(const char *file)
{
struct stat sb; struct stat sb;
return (stat (file, &sb) == 0); return (stat(file, &sb) == 0);
} }
static time_t get_file_mod_time(char *file){ static time_t get_file_mod_time(char *file)
{
struct stat attr; struct stat attr;
stat(file, &attr); stat(file, &attr);
return attr.st_mtime; return attr.st_mtime;
} }
static size_t get_file_size(const char* file){ static size_t get_file_size(const char *file)
{
struct stat st; struct stat st;
stat(file, &st); stat(file, &st);
return st.st_size; return st.st_size;
} }
static char* sharedir_scan(sharedir_t* self, const char* file){ static char *sharedir_scan(sharedir_t *self, const char *file)
{
/* /*
* Agent is not under our control, but lets roughly constrain * Agent is not under our control, but lets roughly constrain
* it to anything stored in or linked from sharedir * it to anything stored in or linked from sharedir
*/ */
chdir(self->dir); chdir(self->dir);
char* real_path = realpath(file, NULL); char *real_path = realpath(file, NULL);
if (file[0] != '/' && !strstr(file, "/../") && if (file[0] != '/' && !strstr(file, "/../") && real_path && file_exits(real_path))
real_path && file_exits(real_path)) { {
return real_path; return real_path;
} }
@ -62,14 +67,15 @@ static char* sharedir_scan(sharedir_t* self, const char* file){
return NULL; return NULL;
} }
static sharedir_file_t* sharedir_get_object(sharedir_t* self, const char* file){ static sharedir_file_t *sharedir_get_object(sharedir_t *self, const char *file)
{
khiter_t k; khiter_t k;
int ret; int ret;
sharedir_file_t* obj = NULL; sharedir_file_t *obj = NULL;
k = kh_get(SHAREDIR_LOOKUP, self->lookup, file); k = kh_get(SHAREDIR_LOOKUP, self->lookup, file);
if(k != kh_end(self->lookup)){ if (k != kh_end(self->lookup)) {
/* file already exists in our hash map */ /* file already exists in our hash map */
obj = kh_value(self->lookup, k); obj = kh_value(self->lookup, k);
@ -83,13 +89,12 @@ static sharedir_file_t* sharedir_get_object(sharedir_t* self, const char* file){
assert(get_file_size(obj->path) == obj->size); assert(get_file_size(obj->path) == obj->size);
return obj; return obj;
} } else {
else{
/* nope ! */ /* nope ! */
char* realpath = sharedir_scan(self, file); char *realpath = sharedir_scan(self, file);
struct stat sb; struct stat sb;
if(realpath != NULL){ if (realpath != NULL) {
if (stat(realpath, &sb) == 0 && S_ISDIR(sb.st_mode)){ if (stat(realpath, &sb) == 0 && S_ISDIR(sb.st_mode)) {
return NULL; // is dir return NULL; // is dir
} }
obj = malloc(sizeof(sharedir_file_t)); obj = malloc(sizeof(sharedir_file_t));
@ -97,11 +102,11 @@ static sharedir_file_t* sharedir_get_object(sharedir_t* self, const char* file){
assert(asprintf(&obj->file, "%s", basename(realpath)) != -1); assert(asprintf(&obj->file, "%s", basename(realpath)) != -1);
obj->path = realpath; obj->path = realpath;
obj->size = get_file_size(obj->path); obj->size = get_file_size(obj->path);
obj->bytes_left = (uint64_t) obj->size; obj->bytes_left = (uint64_t)obj->size;
obj->mod_time = get_file_mod_time(obj->path); obj->mod_time = get_file_mod_time(obj->path);
/* put into hash_list */ /* put into hash_list */
char* new_file = NULL; char *new_file = NULL;
assert(asprintf(&new_file, "%s", file) != -1); assert(asprintf(&new_file, "%s", file) != -1);
k = kh_put(SHAREDIR_LOOKUP, self->lookup, new_file, &ret); k = kh_put(SHAREDIR_LOOKUP, self->lookup, new_file, &ret);
kh_value(self->lookup, k) = obj; kh_value(self->lookup, k) = obj;
@ -114,62 +119,62 @@ static sharedir_file_t* sharedir_get_object(sharedir_t* self, const char* file){
} }
} }
static FILE* get_file_ptr(sharedir_t* self, sharedir_file_t* obj){ static FILE *get_file_ptr(sharedir_t *self, sharedir_file_t *obj)
if(obj == self->last_file_obj_ptr && self->last_file_f){ {
if (obj == self->last_file_obj_ptr && self->last_file_f) {
return self->last_file_f; return self->last_file_f;
} }
if(self->last_file_f){ if (self->last_file_f) {
fclose(self->last_file_f); fclose(self->last_file_f);
} }
FILE* f = fopen(obj->path, "r"); FILE *f = fopen(obj->path, "r");
self->last_file_f = f; self->last_file_f = f;
self->last_file_obj_ptr = obj; self->last_file_obj_ptr = obj;
return f; return f;
} }
uint64_t sharedir_request_file(sharedir_t* self, const char* file, uint8_t* page_buffer){ uint64_t sharedir_request_file(sharedir_t *self, const char *file, uint8_t *page_buffer)
if(!self->dir){ {
fprintf(stderr, "WARNING: New file request received, but no share dir configured! [FILE: %s]\n", file); if (!self->dir) {
fprintf(stderr, "WARNING: New file request received, but no share dir configured! [FILE: %s]\n",
file);
return 0xFFFFFFFFFFFFFFFFUL; return 0xFFFFFFFFFFFFFFFFUL;
} }
FILE* f = NULL; FILE *f = NULL;
sharedir_file_t* obj = sharedir_get_object(self, file); sharedir_file_t *obj = sharedir_get_object(self, file);
if(obj != NULL){ if (obj != NULL) {
#ifdef SHAREDIR_DEBUG #ifdef SHAREDIR_DEBUG
printf("sharedir_get_object->file: %s\n", obj->file); printf("sharedir_get_object->file: %s\n", obj->file);
printf("sharedir_get_object->path: %s\n", obj->path); printf("sharedir_get_object->path: %s\n", obj->path);
printf("sharedir_get_object->size: %ld\n", obj->size); printf("sharedir_get_object->size: %ld\n", obj->size);
printf("sharedir_get_object->bytes_left: %ld\n", obj->bytes_left); printf("sharedir_get_object->bytes_left: %ld\n", obj->bytes_left);
#endif #endif
if(obj->bytes_left >= 0x1000){ if (obj->bytes_left >= 0x1000) {
f = get_file_ptr(self, obj); f = get_file_ptr(self, obj);
fseek(f, obj->size-obj->bytes_left, SEEK_SET); fseek(f, obj->size - obj->bytes_left, SEEK_SET);
assert(fread(page_buffer, 1, 0x1000, f) == 0x1000); assert(fread(page_buffer, 1, 0x1000, f) == 0x1000);
obj->bytes_left -= 0x1000; obj->bytes_left -= 0x1000;
return 0x1000; return 0x1000;
} } else {
else { if (obj->bytes_left != 0) {
if (obj->bytes_left != 0){
f = get_file_ptr(self, obj); f = get_file_ptr(self, obj);
fseek(f, obj->size-obj->bytes_left, SEEK_SET); fseek(f, obj->size - obj->bytes_left, SEEK_SET);
assert(fread(page_buffer, 1, obj->bytes_left, f) == obj->bytes_left); assert(fread(page_buffer, 1, obj->bytes_left, f) == obj->bytes_left);
uint64_t ret_value = obj->bytes_left; uint64_t ret_value = obj->bytes_left;
obj->bytes_left = 0; obj->bytes_left = 0;
return ret_value; return ret_value;
} } else {
else {
obj->bytes_left = (uint_fast64_t)obj->size; obj->bytes_left = (uint_fast64_t)obj->size;
return 0; return 0;
} }
} }
} } else {
else{
nyx_error("Warning: No such file in sharedir: %s\n", file); nyx_error("Warning: No such file in sharedir: %s\n", file);
return 0xFFFFFFFFFFFFFFFFUL; return 0xFFFFFFFFFFFFFFFFUL;
} }

View File

@ -1,26 +1,26 @@
#pragma once #pragma once
#include <stdio.h>
#include <stdint.h>
#include "khash.h" #include "khash.h"
#include <stdint.h>
#include <stdio.h>
typedef struct sharedir_file_s{ typedef struct sharedir_file_s {
char* file; char *file;
char* path; char *path;
size_t size; size_t size;
uint64_t bytes_left; uint64_t bytes_left;
time_t mod_time; time_t mod_time;
} sharedir_file_t; } sharedir_file_t;
KHASH_MAP_INIT_STR(SHAREDIR_LOOKUP, sharedir_file_t*) KHASH_MAP_INIT_STR(SHAREDIR_LOOKUP, sharedir_file_t *)
typedef struct sharedir_s{ typedef struct sharedir_s {
char* dir; char *dir;
khash_t(SHAREDIR_LOOKUP) *lookup; khash_t(SHAREDIR_LOOKUP) * lookup;
FILE* last_file_f; FILE *last_file_f;
sharedir_file_t* last_file_obj_ptr; sharedir_file_t *last_file_obj_ptr;
} sharedir_t; } sharedir_t;
sharedir_t* sharedir_new(void); sharedir_t *sharedir_new(void);
void sharedir_set_dir(sharedir_t* self, const char* dir); void sharedir_set_dir(sharedir_t *self, const char *dir);
uint64_t sharedir_request_file(sharedir_t* self, const char* file, uint8_t* page_buffer); uint64_t sharedir_request_file(sharedir_t *self, const char *file, uint8_t *page_buffer);

View File

@ -1,51 +1,59 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <stdint.h> #include <stdint.h>
#include <sys/types.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/types.h>
#include "nyx/snapshot/block/block_cow.h"
#include "sysemu/block-backend.h" #include "sysemu/block-backend.h"
#include "nyx/state/state.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/snapshot/block/block_cow.h"
#include "nyx/state/state.h"
//#define COW_CACHE_DEBUG // #define COW_CACHE_DEBUG
//#define COW_CACHE_VERBOSE // #define COW_CACHE_VERBOSE
#define CHUNK_SIZE 0x1000 #define CHUNK_SIZE 0x1000
//0x200 // 0x200
#define PAGE_MASK 0xFFFFFFFFFFFFF000 #define PAGE_MASK 0xFFFFFFFFFFFFF000
uint64_t global_cow_primary_size = COW_CACHE_PRIMARY_MINIMUM_SIZE; uint64_t global_cow_primary_size = COW_CACHE_PRIMARY_MINIMUM_SIZE;
bool global_cow_primary_size_adjustable = true; bool global_cow_primary_size_adjustable = true;
void set_global_cow_cache_primary_size(uint64_t new_size){ void set_global_cow_cache_primary_size(uint64_t new_size)
if (global_cow_primary_size_adjustable && new_size > COW_CACHE_PRIMARY_MINIMUM_SIZE && (new_size & 0xFFF) == 0){ {
if (global_cow_primary_size_adjustable &&
new_size > COW_CACHE_PRIMARY_MINIMUM_SIZE && (new_size & 0xFFF) == 0)
{
global_cow_primary_size = new_size; global_cow_primary_size = new_size;
global_cow_primary_size_adjustable = false; global_cow_primary_size_adjustable = false;
} }
} }
static inline uint64_t get_global_cow_cache_primary_size(void){ static inline uint64_t get_global_cow_cache_primary_size(void)
{
return global_cow_primary_size; return global_cow_primary_size;
} }
cow_cache_t* cow_cache_new(const char* filename){ cow_cache_t *cow_cache_new(const char *filename)
{
cow_cache_t* self = malloc(sizeof(cow_cache_t)); cow_cache_t *self = malloc(sizeof(cow_cache_t));
self->lookup_primary = kh_init(COW_CACHE); self->lookup_primary = kh_init(COW_CACHE);
self->lookup_secondary = kh_init(COW_CACHE); self->lookup_secondary = kh_init(COW_CACHE);
self->lookup_secondary_tmp = kh_init(COW_CACHE); self->lookup_secondary_tmp = kh_init(COW_CACHE);
self->cow_primary_size = COW_CACHE_PRIMARY_MINIMUM_SIZE; self->cow_primary_size = COW_CACHE_PRIMARY_MINIMUM_SIZE;
self->data_primary = mmap(NULL, self->cow_primary_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); self->data_primary = mmap(NULL, self->cow_primary_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(self->data_primary != MAP_FAILED); assert(self->data_primary != MAP_FAILED);
self->data_secondary = mmap(NULL, COW_CACHE_SECONDARY_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); self->data_secondary = mmap(NULL, COW_CACHE_SECONDARY_SIZE, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(self->data_secondary != MAP_FAILED); assert(self->data_secondary != MAP_FAILED);
self->data_secondary_tmp = mmap(NULL, COW_CACHE_SECONDARY_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); self->data_secondary_tmp = mmap(NULL, COW_CACHE_SECONDARY_SIZE,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(self->data_secondary_tmp != MAP_FAILED); assert(self->data_secondary_tmp != MAP_FAILED);
self->filename = strdup(basename(filename)); self->filename = strdup(basename(filename));
@ -53,11 +61,13 @@ cow_cache_t* cow_cache_new(const char* filename){
self->offset_secondary = 0; self->offset_secondary = 0;
self->offset_secondary_tmp = 0; self->offset_secondary_tmp = 0;
if(getenv("NYX_DISABLE_BLOCK_COW")){ if (getenv("NYX_DISABLE_BLOCK_COW")) {
fprintf(stderr, "WARNING: Nyx block COW layer disabled for %s (** write operations are not cached **)\n", filename); fprintf(stderr,
"WARNING: Nyx block COW layer disabled for %s (** write operations "
"are not cached **)\n",
filename);
self->enabled = false; self->enabled = false;
} } else {
else{
self->enabled = true; self->enabled = true;
} }
self->enabled_fuzz = false; self->enabled_fuzz = false;
@ -74,14 +84,17 @@ cow_cache_t* cow_cache_new(const char* filename){
return self; return self;
} }
static char* gen_file_name(cow_cache_t* self, const char* filename_prefix, const char* filename_postfix){ static char *gen_file_name(cow_cache_t *self,
char* tmp1; const char *filename_prefix,
char* tmp2; const char *filename_postfix)
{
char *tmp1;
char *tmp2;
assert(asprintf(&tmp2, "%s", self->filename) != -1); assert(asprintf(&tmp2, "%s", self->filename) != -1);
for(int i = 0; i < strlen(tmp2); i++){ for (int i = 0; i < strlen(tmp2); i++) {
if(tmp2[i] == '/'){ if (tmp2[i] == '/') {
tmp2[i] = '_'; tmp2[i] = '_';
} }
} }
@ -92,12 +105,13 @@ static char* gen_file_name(cow_cache_t* self, const char* filename_prefix, const
return tmp1; return tmp1;
} }
void read_primary_buffer(cow_cache_t* self, const char* filename_prefix, bool switch_mode){ void read_primary_buffer(cow_cache_t *self, const char *filename_prefix, bool switch_mode)
{
assert(!self->enabled_fuzz); assert(!self->enabled_fuzz);
global_cow_primary_size_adjustable = false; global_cow_primary_size_adjustable = false;
char* tmp1; char *tmp1;
char* tmp2; char *tmp2;
tmp1 = gen_file_name(self, filename_prefix, "khash"); tmp1 = gen_file_name(self, filename_prefix, "khash");
tmp2 = gen_file_name(self, filename_prefix, "pcow"); tmp2 = gen_file_name(self, filename_prefix, "pcow");
@ -105,38 +119,42 @@ void read_primary_buffer(cow_cache_t* self, const char* filename_prefix, bool sw
kh_destroy(COW_CACHE, self->lookup_primary); kh_destroy(COW_CACHE, self->lookup_primary);
struct stat buffer; struct stat buffer;
assert(stat (tmp2, &buffer) == 0); assert(stat(tmp2, &buffer) == 0);
if (buffer.st_size > get_global_cow_cache_primary_size()){ if (buffer.st_size > get_global_cow_cache_primary_size()) {
fprintf(stderr, "ERROR: in-memory CoW buffer is too small compared to snapshot file (buffer: 0x%lx / file: 0x%lx)\n", get_global_cow_cache_primary_size(), buffer.st_size); fprintf(stderr,
"ERROR: in-memory CoW buffer is too small compared to snapshot file "
"(buffer: 0x%lx / file: 0x%lx)\n",
get_global_cow_cache_primary_size(), buffer.st_size);
exit(1); exit(1);
} }
if(buffer.st_size){ if (buffer.st_size) {
self->lookup_primary = kh_load(COW_CACHE, tmp1); self->lookup_primary = kh_load(COW_CACHE, tmp1);
} } else {
else {
self->lookup_primary = kh_init(COW_CACHE); self->lookup_primary = kh_init(COW_CACHE);
} }
int fd = open(tmp2, O_RDONLY); int fd = open(tmp2, O_RDONLY);
if(switch_mode){ if (switch_mode) {
munmap(self->data_primary, self->cow_primary_size); munmap(self->data_primary, self->cow_primary_size);
self->cow_primary_size = get_global_cow_cache_primary_size(); self->cow_primary_size = get_global_cow_cache_primary_size();
self->data_primary = mmap(0, self->cow_primary_size, PROT_READ, MAP_SHARED, fd, 0); self->data_primary =
mmap(0, self->cow_primary_size, PROT_READ, MAP_SHARED, fd, 0);
assert(self->data_primary); assert(self->data_primary);
} } else {
else{ if (get_global_cow_cache_primary_size() != self->cow_primary_size) {
if(get_global_cow_cache_primary_size() != self->cow_primary_size){
munmap(self->data_primary, self->cow_primary_size); munmap(self->data_primary, self->cow_primary_size);
self->cow_primary_size = get_global_cow_cache_primary_size(); self->cow_primary_size = get_global_cow_cache_primary_size();
self->data_primary = mmap(NULL, self->cow_primary_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); self->data_primary = mmap(NULL, self->cow_primary_size,
PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);
assert(self->data_primary != MAP_FAILED); assert(self->data_primary != MAP_FAILED);
} }
void* ptr = mmap(0, COW_CACHE_PRIMARY_MINIMUM_SIZE, PROT_READ , MAP_SHARED, fd, 0); void *ptr =
mmap(0, COW_CACHE_PRIMARY_MINIMUM_SIZE, PROT_READ, MAP_SHARED, fd, 0);
assert(ptr); assert(ptr);
memcpy(self->data_primary, ptr, buffer.st_size); memcpy(self->data_primary, ptr, buffer.st_size);
munmap(ptr, COW_CACHE_PRIMARY_MINIMUM_SIZE); munmap(ptr, COW_CACHE_PRIMARY_MINIMUM_SIZE);
@ -145,7 +163,7 @@ void read_primary_buffer(cow_cache_t* self, const char* filename_prefix, bool sw
self->offset_primary = buffer.st_size; self->offset_primary = buffer.st_size;
if(switch_mode){ if (switch_mode) {
switch_to_fuzz_mode(self); switch_to_fuzz_mode(self);
} }
@ -153,30 +171,30 @@ void read_primary_buffer(cow_cache_t* self, const char* filename_prefix, bool sw
free(tmp2); free(tmp2);
} }
void dump_primary_buffer(cow_cache_t* self, const char* filename_prefix){ void dump_primary_buffer(cow_cache_t *self, const char *filename_prefix)
{
assert(self->enabled_fuzz); assert(self->enabled_fuzz);
char* tmp1; char *tmp1;
char* tmp2; char *tmp2;
tmp1 = gen_file_name(self, filename_prefix, "khash"); tmp1 = gen_file_name(self, filename_prefix, "khash");
tmp2 = gen_file_name(self, filename_prefix, "pcow"); tmp2 = gen_file_name(self, filename_prefix, "pcow");
if(self->offset_primary){ if (self->offset_primary) {
kh_write(COW_CACHE, self->lookup_primary, tmp1); kh_write(COW_CACHE, self->lookup_primary, tmp1);
} } else {
else{
fclose(fopen(tmp1, "wb")); fclose(fopen(tmp1, "wb"));
} }
FILE *fp = fopen(tmp2, "wb"); FILE *fp = fopen(tmp2, "wb");
if(fp == NULL) { if (fp == NULL) {
fprintf(stderr, "[%s] Could not open file %s.\n", __func__, tmp2); fprintf(stderr, "[%s] Could not open file %s.\n", __func__, tmp2);
assert(false); assert(false);
} }
if(self->offset_primary){ if (self->offset_primary) {
fwrite(self->data_primary, CHUNK_SIZE, self->offset_primary/CHUNK_SIZE, fp); fwrite(self->data_primary, CHUNK_SIZE, self->offset_primary / CHUNK_SIZE, fp);
} }
fclose(fp); fclose(fp);
@ -185,14 +203,14 @@ void dump_primary_buffer(cow_cache_t* self, const char* filename_prefix){
free(tmp2); free(tmp2);
} }
void cow_cache_reset(cow_cache_t* self){ void cow_cache_reset(cow_cache_t *self)
if(!self->enabled_fuzz) {
if (!self->enabled_fuzz)
return; return;
/* TODO */ /* TODO */
assert(self->enabled_fuzz); assert(self->enabled_fuzz);
if(self->enabled_fuzz){ if (self->enabled_fuzz) {
#ifdef DEBUG_COW_LAYER #ifdef DEBUG_COW_LAYER
printf("%s: read_calls =>\t%ld\n", __func__, self->read_calls); printf("%s: read_calls =>\t%ld\n", __func__, self->read_calls);
printf("%s: write_calls =>\t%ld\n", __func__, self->write_calls); printf("%s: write_calls =>\t%ld\n", __func__, self->write_calls);
@ -200,7 +218,7 @@ void cow_cache_reset(cow_cache_t* self){
printf("%s: write_calls_tmp =>\t%ld\n", __func__, self->write_calls_tmp); printf("%s: write_calls_tmp =>\t%ld\n", __func__, self->write_calls_tmp);
#endif #endif
if(!self->enabled_fuzz_tmp){ if (!self->enabled_fuzz_tmp) {
self->offset_secondary = 0; self->offset_secondary = 0;
kh_clear(COW_CACHE, self->lookup_secondary); kh_clear(COW_CACHE, self->lookup_secondary);
@ -208,8 +226,7 @@ void cow_cache_reset(cow_cache_t* self){
self->read_calls = 0; self->read_calls = 0;
self->write_calls = 0; self->write_calls = 0;
#endif #endif
} } else {
else {
self->offset_secondary_tmp = 0; self->offset_secondary_tmp = 0;
kh_clear(COW_CACHE, self->lookup_secondary_tmp); kh_clear(COW_CACHE, self->lookup_secondary_tmp);
@ -223,25 +240,29 @@ void cow_cache_reset(cow_cache_t* self){
} }
void cow_cache_enable_tmp_mode(cow_cache_t* self){ void cow_cache_enable_tmp_mode(cow_cache_t *self)
{
assert(self->enabled_fuzz); assert(self->enabled_fuzz);
self->enabled_fuzz_tmp = true; self->enabled_fuzz_tmp = true;
} }
void cow_cache_disable_tmp_mode(cow_cache_t* self){ void cow_cache_disable_tmp_mode(cow_cache_t *self)
{
assert(self->enabled_fuzz); assert(self->enabled_fuzz);
assert(self->enabled_fuzz_tmp); assert(self->enabled_fuzz_tmp);
cow_cache_reset(self); cow_cache_reset(self);
self->enabled_fuzz_tmp = false; self->enabled_fuzz_tmp = false;
} }
void cow_cache_enable(cow_cache_t* self){ void cow_cache_enable(cow_cache_t *self)
{
cow_cache_reset(self); cow_cache_reset(self);
self->enabled = true; self->enabled = true;
} }
void cow_cache_disable(cow_cache_t* self){ void cow_cache_disable(cow_cache_t *self)
{
cow_cache_reset(self); cow_cache_reset(self);
self->enabled = false; self->enabled = false;
} }
@ -266,89 +287,128 @@ extern int blk_check_byte_request(BlockBackend *blk, int64_t offset, size_t size
extern void blk_aio_complete(BlkAioEmAIOCB *acb); extern void blk_aio_complete(BlkAioEmAIOCB *acb);
/* read from primary buffer */ /* read from primary buffer */
static inline void read_from_primary_buffer(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags, uint64_t offset_addr, uint64_t iov_offset){ static inline void read_from_primary_buffer(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags,
uint64_t offset_addr,
uint64_t iov_offset)
{
khiter_t k; khiter_t k;
k = kh_get(COW_CACHE, self->lookup_primary, offset_addr); k = kh_get(COW_CACHE, self->lookup_primary, offset_addr);
if(k != kh_end(self->lookup_primary)){ if (k != kh_end(self->lookup_primary)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("[PRE ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n", offset_addr, iov_offset, self->offset_primary); printf("[PRE ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA "
#endif "OFFSET: %lx\n",
qemu_iovec_from_buf(qiov, iov_offset, self->data_primary + kh_value(self->lookup_primary, k), CHUNK_SIZE); offset_addr, iov_offset, self->offset_primary);
#endif
qemu_iovec_from_buf(qiov, iov_offset,
self->data_primary + kh_value(self->lookup_primary, k),
CHUNK_SIZE);
} }
return; return;
} }
/* try to read from secondary buffer /* try to read from secondary buffer
* read from primary buffer if the data is not available yet */ * read from primary buffer if the data is not available yet */
static inline void read_from_secondary_buffer(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags, uint64_t offset_addr, uint64_t iov_offset){ static inline void read_from_secondary_buffer(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags,
uint64_t offset_addr,
uint64_t iov_offset)
{
/* read from L2 TMP buffer */ /* read from L2 TMP buffer */
khiter_t k; khiter_t k;
if(self->enabled_fuzz_tmp){ if (self->enabled_fuzz_tmp) {
k = kh_get(COW_CACHE, self->lookup_secondary_tmp, offset_addr); k = kh_get(COW_CACHE, self->lookup_secondary_tmp, offset_addr);
if(k != kh_end(self->lookup_secondary_tmp)){ if (k != kh_end(self->lookup_secondary_tmp)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("[FTMP] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n", offset_addr, iov_offset, self->offset_secondary); printf("[FTMP] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA "
#endif "OFFSET: %lx\n",
qemu_iovec_from_buf(qiov, iov_offset, self->data_secondary_tmp + kh_value(self->lookup_secondary_tmp, k), CHUNK_SIZE); offset_addr, iov_offset, self->offset_secondary);
#endif
qemu_iovec_from_buf(qiov, iov_offset,
self->data_secondary_tmp +
kh_value(self->lookup_secondary_tmp, k),
CHUNK_SIZE);
return; return;
} }
} }
/* read from L2 buffer */ /* read from L2 buffer */
k = kh_get(COW_CACHE, self->lookup_secondary, offset_addr); k = kh_get(COW_CACHE, self->lookup_secondary, offset_addr);
if(k != kh_end(self->lookup_secondary)){ if (k != kh_end(self->lookup_secondary)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("[FUZZ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n", offset_addr, iov_offset, self->offset_secondary); printf("[FUZZ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA "
#endif "OFFSET: %lx\n",
qemu_iovec_from_buf(qiov, iov_offset, self->data_secondary + kh_value(self->lookup_secondary, k), CHUNK_SIZE); offset_addr, iov_offset, self->offset_secondary);
#endif
qemu_iovec_from_buf(qiov, iov_offset,
self->data_secondary + kh_value(self->lookup_secondary, k),
CHUNK_SIZE);
return; return;
} }
/* read from L1 buffer */ /* read from L1 buffer */
k = kh_get(COW_CACHE, self->lookup_primary, offset_addr); k = kh_get(COW_CACHE, self->lookup_primary, offset_addr);
if(k != kh_end(self->lookup_primary)){ if (k != kh_end(self->lookup_primary)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("[PRE ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n", offset_addr, iov_offset, self->offset_primary); printf("[PRE ] READ DIRTY COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA "
#endif "OFFSET: %lx\n",
qemu_iovec_from_buf(qiov, iov_offset, self->data_primary + kh_value(self->lookup_primary, k), CHUNK_SIZE); offset_addr, iov_offset, self->offset_primary);
#endif
qemu_iovec_from_buf(qiov, iov_offset,
self->data_primary + kh_value(self->lookup_primary, k),
CHUNK_SIZE);
} }
} }
/* read data from cow cache */ /* read data from cow cache */
static int cow_cache_read(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags){ static int cow_cache_read(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
#ifdef DEBUG_COW_LAYER #ifdef DEBUG_COW_LAYER
if(self->enabled_fuzz){ if (self->enabled_fuzz) {
if(!self->enabled_fuzz_tmp){ if (!self->enabled_fuzz_tmp) {
self->read_calls++; self->read_calls++;
} } else {
else{
self->read_calls_tmp++; self->read_calls_tmp++;
} }
} }
#endif #endif
blk_co_preadv(blk, offset, bytes, qiov, flags); blk_co_preadv(blk, offset, bytes, qiov, flags);
if ((qiov->size%CHUNK_SIZE)){ if ((qiov->size % CHUNK_SIZE)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
fprintf(stderr, "%s: FAILED %lx!\n", __func__, qiov->size); fprintf(stderr, "%s: FAILED %lx!\n", __func__, qiov->size);
#endif #endif
return 0; return 0;
} }
assert(!(qiov->size%CHUNK_SIZE)); assert(!(qiov->size % CHUNK_SIZE));
uint64_t iov_offset = 0; uint64_t iov_offset = 0;
for(uint64_t offset_addr = offset; offset_addr < (offset+(qiov->size)); offset_addr+= CHUNK_SIZE){ for (uint64_t offset_addr = offset; offset_addr < (offset + (qiov->size));
offset_addr += CHUNK_SIZE)
if(self->enabled_fuzz){ {
read_from_secondary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags, offset_addr, iov_offset); if (self->enabled_fuzz) {
} read_from_secondary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags,
else{ offset_addr, iov_offset);
read_from_primary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags, offset_addr, iov_offset); } else {
read_from_primary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags,
offset_addr, iov_offset);
} }
iov_offset+= CHUNK_SIZE; iov_offset += CHUNK_SIZE;
} }
return 0; return 0;
@ -356,138 +416,174 @@ static int cow_cache_read(cow_cache_t* self, BlockBackend *blk, int64_t offset,
/* write to primary buffer */ /* write to primary buffer */
static inline void write_to_primary_buffer(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags, uint64_t offset_addr, uint64_t iov_offset){ static inline void write_to_primary_buffer(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags,
uint64_t offset_addr,
uint64_t iov_offset)
{
int ret; int ret;
khiter_t k; khiter_t k;
k = kh_get(COW_CACHE, self->lookup_primary, offset_addr); k = kh_get(COW_CACHE, self->lookup_primary, offset_addr);
if(unlikely(k == kh_end(self->lookup_primary))){ if (unlikely(k == kh_end(self->lookup_primary))) {
/* create page */ /* create page */
k = kh_put(COW_CACHE, self->lookup_primary, offset_addr, &ret); k = kh_put(COW_CACHE, self->lookup_primary, offset_addr, &ret);
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("ADD NEW COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n", offset_addr, iov_offset, self->offset_primary); printf("ADD NEW COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx\n",
#endif offset_addr, iov_offset, self->offset_primary);
#endif
kh_value(self->lookup_primary, k) = self->offset_primary; kh_value(self->lookup_primary, k) = self->offset_primary;
self->offset_primary += CHUNK_SIZE; self->offset_primary += CHUNK_SIZE;
#ifdef COW_CACHE_VERBOSE #ifdef COW_CACHE_VERBOSE
printf("COW CACHE IS 0x%lx BYTES (KB: %ld / MB: %ld / GB: %ld) IN SIZE!\n", self->offset, self->offset >> 10, self->offset >> 20, self->offset >> 30); printf("COW CACHE IS 0x%lx BYTES (KB: %ld / MB: %ld / GB: %ld) IN SIZE!\n",
#endif self->offset, self->offset >> 10, self->offset >> 20,
self->offset >> 30);
#endif
/* IN CASE THE BUFFER IS FULL -> ABORT! */ /* IN CASE THE BUFFER IS FULL -> ABORT! */
assert(self->offset_primary < self->cow_primary_size); assert(self->offset_primary < self->cow_primary_size);
} }
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
printf("LOAD COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx (%s)\n", offset_addr, iov_offset, kh_value(self->lookup_primary, k), self->filename); printf("LOAD COW PAGE: ADDR: %lx IOVEC OFFSET: %lx DATA OFFSET: %lx (%s)\n",
#endif offset_addr, iov_offset, kh_value(self->lookup_primary, k), self->filename);
#endif
/* write to cached page */ /* write to cached page */
qemu_iovec_to_buf(qiov, iov_offset, self->data_primary + kh_value(self->lookup_primary, k), CHUNK_SIZE); qemu_iovec_to_buf(qiov, iov_offset,
self->data_primary + kh_value(self->lookup_primary, k),
CHUNK_SIZE);
} }
static inline void write_to_secondary_buffer(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags, uint64_t offset_addr, uint64_t iov_offset){ static inline void write_to_secondary_buffer(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags,
uint64_t offset_addr,
uint64_t iov_offset)
{
int ret; int ret;
if(!self->enabled_fuzz_tmp){ if (!self->enabled_fuzz_tmp) {
/* L2 mode */ /* L2 mode */
/* IN CASE THE BUFFER IS FULL -> ABORT! */ /* IN CASE THE BUFFER IS FULL -> ABORT! */
if(self->offset_secondary >= COW_CACHE_SECONDARY_SIZE){ if (self->offset_secondary >= COW_CACHE_SECONDARY_SIZE) {
GET_GLOBAL_STATE()->cow_cache_full = true; GET_GLOBAL_STATE()->cow_cache_full = true;
abort(); abort();
return; return;
} }
khiter_t k_secondary = kh_get(COW_CACHE, self->lookup_secondary, offset_addr); khiter_t k_secondary = kh_get(COW_CACHE, self->lookup_secondary, offset_addr);
if(unlikely(k_secondary == kh_end(self->lookup_secondary))){ if (unlikely(k_secondary == kh_end(self->lookup_secondary))) {
/* if page is not cached in secondary buffer yet */ /* if page is not cached in secondary buffer yet */
k_secondary = kh_put(COW_CACHE, self->lookup_secondary, offset_addr, &ret); k_secondary = kh_put(COW_CACHE, self->lookup_secondary, offset_addr, &ret);
kh_value(self->lookup_secondary, k_secondary) = self->offset_secondary; kh_value(self->lookup_secondary, k_secondary) = self->offset_secondary;
self->offset_secondary += CHUNK_SIZE; self->offset_secondary += CHUNK_SIZE;
} }
/* write to cache */ /* write to cache */
qemu_iovec_to_buf(qiov, iov_offset, self->data_secondary + kh_value(self->lookup_secondary, k_secondary), CHUNK_SIZE); qemu_iovec_to_buf(qiov, iov_offset,
} self->data_secondary +
else{ kh_value(self->lookup_secondary, k_secondary),
CHUNK_SIZE);
} else {
/* L2 TMP mode */ /* L2 TMP mode */
/* IN CASE THE BUFFER IS FULL -> ABORT! */ /* IN CASE THE BUFFER IS FULL -> ABORT! */
if(self->offset_secondary_tmp >= COW_CACHE_SECONDARY_SIZE){ if (self->offset_secondary_tmp >= COW_CACHE_SECONDARY_SIZE) {
GET_GLOBAL_STATE()->cow_cache_full = true; GET_GLOBAL_STATE()->cow_cache_full = true;
abort(); abort();
return; return;
} }
khiter_t k_secondary_tmp = kh_get(COW_CACHE, self->lookup_secondary_tmp, offset_addr); khiter_t k_secondary_tmp =
if(unlikely(k_secondary_tmp == kh_end(self->lookup_secondary_tmp))){ kh_get(COW_CACHE, self->lookup_secondary_tmp, offset_addr);
if (unlikely(k_secondary_tmp == kh_end(self->lookup_secondary_tmp))) {
/* if page is not cached in secondary tmp buffer yet */ /* if page is not cached in secondary tmp buffer yet */
k_secondary_tmp = kh_put(COW_CACHE, self->lookup_secondary_tmp, offset_addr, &ret); k_secondary_tmp =
kh_value(self->lookup_secondary_tmp, k_secondary_tmp) = self->offset_secondary_tmp; kh_put(COW_CACHE, self->lookup_secondary_tmp, offset_addr, &ret);
kh_value(self->lookup_secondary_tmp, k_secondary_tmp) =
self->offset_secondary_tmp;
self->offset_secondary_tmp += CHUNK_SIZE; self->offset_secondary_tmp += CHUNK_SIZE;
} }
/* write to cache */ /* write to cache */
qemu_iovec_to_buf(qiov, iov_offset, self->data_secondary_tmp + kh_value(self->lookup_secondary_tmp, k_secondary_tmp), CHUNK_SIZE); qemu_iovec_to_buf(qiov, iov_offset,
self->data_secondary_tmp +
kh_value(self->lookup_secondary_tmp, k_secondary_tmp),
CHUNK_SIZE);
} }
} }
/* write data to cow cache */ /* write data to cow cache */
static int cow_cache_write(cow_cache_t* self, BlockBackend *blk, int64_t offset, unsigned int bytes, QEMUIOVector *qiov, BdrvRequestFlags flags){ static int cow_cache_write(cow_cache_t *self,
BlockBackend *blk,
int64_t offset,
unsigned int bytes,
QEMUIOVector *qiov,
BdrvRequestFlags flags)
{
#ifdef DEBUG_COW_LAYER #ifdef DEBUG_COW_LAYER
if(self->enabled_fuzz){ if (self->enabled_fuzz) {
if(!self->enabled_fuzz_tmp){ if (!self->enabled_fuzz_tmp) {
self->write_calls++; self->write_calls++;
} } else {
else{
self->write_calls_tmp++; self->write_calls_tmp++;
} }
} }
#endif #endif
if ((qiov->size%CHUNK_SIZE)){ if ((qiov->size % CHUNK_SIZE)) {
#ifdef COW_CACHE_DEBUG #ifdef COW_CACHE_DEBUG
fprintf(stderr, "%s: FAILED %lx!\n", __func__, qiov->size); fprintf(stderr, "%s: FAILED %lx!\n", __func__, qiov->size);
#endif #endif
return 0; return 0;
} }
if((qiov->size%CHUNK_SIZE) && GET_GLOBAL_STATE()->in_fuzzing_mode){ if ((qiov->size % CHUNK_SIZE) && GET_GLOBAL_STATE()->in_fuzzing_mode) {
GET_GLOBAL_STATE()->cow_cache_full = true; GET_GLOBAL_STATE()->cow_cache_full = true;
fprintf(stderr, "WARNING: %s write in %lx CHUNKSIZE\n", __func__, qiov->size); fprintf(stderr, "WARNING: %s write in %lx CHUNKSIZE\n", __func__, qiov->size);
return 0; return 0;
} } else {
else{ assert(!(qiov->size % CHUNK_SIZE));
assert(!(qiov->size%CHUNK_SIZE));
} }
uint64_t iov_offset = 0; uint64_t iov_offset = 0;
for(uint64_t offset_addr = offset; offset_addr < (offset+(qiov->size)); offset_addr+= CHUNK_SIZE){ for (uint64_t offset_addr = offset; offset_addr < (offset + (qiov->size));
if(self->enabled_fuzz){ offset_addr += CHUNK_SIZE)
write_to_secondary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags, offset_addr, iov_offset); {
} if (self->enabled_fuzz) {
else{ write_to_secondary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags,
write_to_primary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags, offset_addr, iov_offset); offset_addr, iov_offset);
} else {
write_to_primary_buffer(self, blk, offset, CHUNK_SIZE, qiov, flags,
offset_addr, iov_offset);
} }
iov_offset+= CHUNK_SIZE; iov_offset += CHUNK_SIZE;
} }
return 0; return 0;
} }
void switch_to_fuzz_mode(cow_cache_t* self){ void switch_to_fuzz_mode(cow_cache_t *self)
{
self->enabled_fuzz = true; self->enabled_fuzz = true;
assert(!mprotect(self->data_primary, self->cow_primary_size, PROT_READ)); assert(!mprotect(self->data_primary, self->cow_primary_size, PROT_READ));
nyx_debug("switching to secondary CoW buffer\n"); nyx_debug("switching to secondary CoW buffer\n");
} }
void cow_cache_read_entry(void* opaque){ void cow_cache_read_entry(void *opaque)
{
BlkAioEmAIOCB *acb = opaque; BlkAioEmAIOCB *acb = opaque;
BlkRwCo *rwco = &acb->rwco; BlkRwCo *rwco = &acb->rwco;
@ -495,13 +591,15 @@ void cow_cache_read_entry(void* opaque){
printf("%s %lx %lx\n", __func__, rwco->offset, acb->bytes); printf("%s %lx %lx\n", __func__, rwco->offset, acb->bytes);
#endif #endif
rwco->ret = cow_cache_read( *((cow_cache_t**)(rwco->blk)), rwco->blk, rwco->offset, acb->bytes, rwco->qiov, rwco->flags); rwco->ret = cow_cache_read(*((cow_cache_t **)(rwco->blk)), rwco->blk,
rwco->offset, acb->bytes, rwco->qiov, rwco->flags);
blk_aio_complete(acb); blk_aio_complete(acb);
} }
void cow_cache_write_entry(void* opaque){ void cow_cache_write_entry(void *opaque)
{
BlkAioEmAIOCB *acb = opaque; BlkAioEmAIOCB *acb = opaque;
BlkRwCo *rwco = &acb->rwco; BlkRwCo *rwco = &acb->rwco;
@ -509,7 +607,8 @@ void cow_cache_write_entry(void* opaque){
printf("%s\n", __func__); printf("%s\n", __func__);
#endif #endif
rwco->ret = cow_cache_write( *((cow_cache_t**)(rwco->blk)), rwco->blk, rwco->offset, acb->bytes, rwco->qiov, rwco->flags); rwco->ret = cow_cache_write(*((cow_cache_t **)(rwco->blk)), rwco->blk,
rwco->offset, acb->bytes, rwco->qiov, rwco->flags);
blk_aio_complete(acb); blk_aio_complete(acb);
} }

View File

@ -10,7 +10,7 @@
#include "nyx/khash.h" #include "nyx/khash.h"
#include "nyx/redqueen_trace.h" #include "nyx/redqueen_trace.h"
//#define DEBUG_COW_LAYER // #define DEBUG_COW_LAYER
/* Minimum size of CoW buffer that stores data written to /* Minimum size of CoW buffer that stores data written to
* the block device between boot time and root snapshot (3GB) * the block device between boot time and root snapshot (3GB)
@ -27,18 +27,18 @@
KHASH_MAP_INIT_INT64(COW_CACHE, uint64_t) KHASH_MAP_INIT_INT64(COW_CACHE, uint64_t)
typedef struct cow_cache_s{ typedef struct cow_cache_s {
khash_t(COW_CACHE) *lookup_primary; khash_t(COW_CACHE) * lookup_primary;
khash_t(COW_CACHE) *lookup_secondary; khash_t(COW_CACHE) * lookup_secondary;
khash_t(COW_CACHE) *lookup_secondary_tmp; khash_t(COW_CACHE) * lookup_secondary_tmp;
void* data_primary; void *data_primary;
void* data_secondary; void *data_secondary;
void* data_secondary_tmp; void *data_secondary_tmp;
uint64_t cow_primary_size; uint64_t cow_primary_size;
char* filename; char *filename;
uint64_t offset_primary; uint64_t offset_primary;
uint64_t offset_secondary; uint64_t offset_secondary;
uint64_t offset_secondary_tmp; uint64_t offset_secondary_tmp;
@ -55,21 +55,23 @@ typedef struct cow_cache_s{
#endif #endif
} cow_cache_t; } cow_cache_t;
cow_cache_t* cow_cache_new(const char* filename); cow_cache_t *cow_cache_new(const char *filename);
void cow_cache_reset(cow_cache_t* self); void cow_cache_reset(cow_cache_t *self);
void switch_to_fuzz_mode(cow_cache_t* self); void switch_to_fuzz_mode(cow_cache_t *self);
void read_primary_buffer(cow_cache_t* self, const char* filename_prefix, bool switch_mode); void read_primary_buffer(cow_cache_t *self,
void dump_primary_buffer(cow_cache_t* self, const char* filename_prefix); const char *filename_prefix,
bool switch_mode);
void dump_primary_buffer(cow_cache_t *self, const char *filename_prefix);
void cow_cache_read_entry(void* opaque); void cow_cache_read_entry(void *opaque);
void cow_cache_write_entry(void* opaque); void cow_cache_write_entry(void *opaque);
void cow_cache_enable(cow_cache_t* self); void cow_cache_enable(cow_cache_t *self);
void cow_cache_disable(cow_cache_t* self); void cow_cache_disable(cow_cache_t *self);
void cow_cache_enable_tmp_mode(cow_cache_t* self); void cow_cache_enable_tmp_mode(cow_cache_t *self);
void cow_cache_disable_tmp_mode(cow_cache_t* self); void cow_cache_disable_tmp_mode(cow_cache_t *self);
void set_global_cow_cache_primary_size(uint64_t new_size); void set_global_cow_cache_primary_size(uint64_t new_size);

View File

@ -11,22 +11,22 @@
#include "nyx/snapshot/block/nyx_block_snapshot.h" #include "nyx/snapshot/block/nyx_block_snapshot.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
typedef struct fast_reload_cow_entry_s{ typedef struct fast_reload_cow_entry_s {
uint32_t id; uint32_t id;
char idstr[256]; char idstr[256];
} fast_reload_cow_entry_t; } fast_reload_cow_entry_t;
nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snapshot){ nyx_block_t *nyx_block_snapshot_init_from_file(const char *folder, bool pre_snapshot)
{
nyx_block_t* self = malloc(sizeof(nyx_block_t)); nyx_block_t *self = malloc(sizeof(nyx_block_t));
memset(self, 0, sizeof(nyx_block_t)); memset(self, 0, sizeof(nyx_block_t));
BlockBackend *blk; BlockBackend *blk;
fast_reload_cow_entry_t entry; fast_reload_cow_entry_t entry;
char* tmp1; char *tmp1;
char* tmp2; char *tmp2;
assert(asprintf(&tmp1, "%s/fs_cache.meta", folder) != -1); assert(asprintf(&tmp1, "%s/fs_cache.meta", folder) != -1);
assert(asprintf(&tmp2, "%s/fs_drv", folder) != -1); assert(asprintf(&tmp2, "%s/fs_drv", folder) != -1);
@ -34,11 +34,11 @@ nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snap
self->cow_cache_array_size = 0; self->cow_cache_array_size = 0;
FILE* f = fopen (tmp1, "r"); FILE *f = fopen(tmp1, "r");
assert(f != NULL); assert(f != NULL);
for (blk = blk_next(NULL); blk; blk = blk_next(blk)) { for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
if(blk && blk->cow_cache){ if (blk && blk->cow_cache) {
nyx_debug("%p %s\n", blk->cow_cache, blk->cow_cache->filename); nyx_debug("%p %s\n", blk->cow_cache, blk->cow_cache->filename);
self->cow_cache_array_size++; self->cow_cache_array_size++;
} }
@ -51,12 +51,13 @@ nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snap
nyx_debug("%d vs %x\n", temp_cow_cache_array_size, self->cow_cache_array_size); nyx_debug("%d vs %x\n", temp_cow_cache_array_size, self->cow_cache_array_size);
assert(self->cow_cache_array_size == temp_cow_cache_array_size); assert(self->cow_cache_array_size == temp_cow_cache_array_size);
self->cow_cache_array = (cow_cache_t**)malloc(sizeof(cow_cache_t*)*self->cow_cache_array_size); self->cow_cache_array =
(cow_cache_t **)malloc(sizeof(cow_cache_t *) * self->cow_cache_array_size);
uint32_t i = 0; uint32_t i = 0;
uint32_t id = 0; uint32_t id = 0;
for (blk = blk_next(NULL); blk; blk = blk_next(blk)) { for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
if(blk && blk->cow_cache){ if (blk && blk->cow_cache) {
self->cow_cache_array[i++] = blk->cow_cache; self->cow_cache_array[i++] = blk->cow_cache;
assert(fread(&entry, sizeof(fast_reload_cow_entry_t), 1, f) == 1); assert(fread(&entry, sizeof(fast_reload_cow_entry_t), 1, f) == 1);
@ -69,7 +70,7 @@ nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snap
fclose(f); fclose(f);
for(i = 0; i < self->cow_cache_array_size; i++){ for (i = 0; i < self->cow_cache_array_size; i++) {
read_primary_buffer(self->cow_cache_array[i], tmp2, !pre_snapshot); read_primary_buffer(self->cow_cache_array[i], tmp2, !pre_snapshot);
} }
@ -78,75 +79,82 @@ nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snap
return self; return self;
} }
nyx_block_t* nyx_block_snapshot_init(void){ nyx_block_t *nyx_block_snapshot_init(void)
{
nyx_block_t* self = malloc(sizeof(nyx_block_t)); nyx_block_t *self = malloc(sizeof(nyx_block_t));
memset(self, 0, sizeof(nyx_block_t)); memset(self, 0, sizeof(nyx_block_t));
BlockBackend *blk; BlockBackend *blk;
for (blk = blk_next(NULL); blk; blk = blk_next(blk)) { for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
if(blk && blk->cow_cache){ if (blk && blk->cow_cache) {
nyx_debug("%p %s\n", blk->cow_cache, blk->cow_cache->filename); nyx_debug("%p %s\n", blk->cow_cache, blk->cow_cache->filename);
self->cow_cache_array_size++; self->cow_cache_array_size++;
} }
} }
self->cow_cache_array = (cow_cache_t**)malloc(sizeof(cow_cache_t*)*self->cow_cache_array_size); self->cow_cache_array =
(cow_cache_t **)malloc(sizeof(cow_cache_t *) * self->cow_cache_array_size);
uint32_t i = 0; uint32_t i = 0;
for (blk = blk_next(NULL); blk; blk = blk_next(blk)) { for (blk = blk_next(NULL); blk; blk = blk_next(blk)) {
if(blk && blk->cow_cache){ if (blk && blk->cow_cache) {
self->cow_cache_array[i++] = blk->cow_cache; self->cow_cache_array[i++] = blk->cow_cache;
} }
} }
for(i = 0; i < self->cow_cache_array_size; i++){ for (i = 0; i < self->cow_cache_array_size; i++) {
switch_to_fuzz_mode(self->cow_cache_array[i]); switch_to_fuzz_mode(self->cow_cache_array[i]);
} }
return self; return self;
} }
void nyx_block_snapshot_flush(nyx_block_t* self){ void nyx_block_snapshot_flush(nyx_block_t *self)
{
GET_GLOBAL_STATE()->cow_cache_full = false; GET_GLOBAL_STATE()->cow_cache_full = false;
} }
void nyx_block_snapshot_switch_incremental(nyx_block_t* self){ void nyx_block_snapshot_switch_incremental(nyx_block_t *self)
for(uint32_t i = 0; i < self->cow_cache_array_size; i++){ {
for (uint32_t i = 0; i < self->cow_cache_array_size; i++) {
cow_cache_enable_tmp_mode(self->cow_cache_array[i]); cow_cache_enable_tmp_mode(self->cow_cache_array[i]);
} }
nyx_block_snapshot_flush(self); nyx_block_snapshot_flush(self);
} }
void nyx_block_snapshot_disable_incremental(nyx_block_t* self){ void nyx_block_snapshot_disable_incremental(nyx_block_t *self)
for(uint32_t i = 0; i < self->cow_cache_array_size; i++){ {
for (uint32_t i = 0; i < self->cow_cache_array_size; i++) {
cow_cache_disable_tmp_mode(self->cow_cache_array[i]); cow_cache_disable_tmp_mode(self->cow_cache_array[i]);
} }
} }
void nyx_block_snapshot_reset(nyx_block_t* self){ void nyx_block_snapshot_reset(nyx_block_t *self)
for(uint32_t i = 0; i < self->cow_cache_array_size; i++){ {
for (uint32_t i = 0; i < self->cow_cache_array_size; i++) {
cow_cache_reset(self->cow_cache_array[i]); cow_cache_reset(self->cow_cache_array[i]);
} }
} }
void nyx_block_snapshot_serialize(nyx_block_t* self, const char* snapshot_folder){ void nyx_block_snapshot_serialize(nyx_block_t *self, const char *snapshot_folder)
{
fast_reload_cow_entry_t entry; fast_reload_cow_entry_t entry;
char* tmp1; char *tmp1;
char* tmp2; char *tmp2;
assert(asprintf(&tmp1, "%s/fs_cache.meta", snapshot_folder) != -1); assert(asprintf(&tmp1, "%s/fs_cache.meta", snapshot_folder) != -1);
assert(asprintf(&tmp2, "%s/fs_drv", snapshot_folder) != -1); assert(asprintf(&tmp2, "%s/fs_drv", snapshot_folder) != -1);
FILE* f = fopen (tmp1, "w"); FILE *f = fopen(tmp1, "w");
fwrite(&(self->cow_cache_array_size), sizeof(uint32_t), 1, f); fwrite(&(self->cow_cache_array_size), sizeof(uint32_t), 1, f);
for(uint32_t i = 0; i < self->cow_cache_array_size; i++){ for (uint32_t i = 0; i < self->cow_cache_array_size; i++) {
entry.id = i; entry.id = i;
strncpy((char*)&entry.idstr, (const char*)self->cow_cache_array[i]->filename, 255); strncpy((char *)&entry.idstr,
(const char *)self->cow_cache_array[i]->filename, 255);
fwrite(&entry, sizeof(fast_reload_cow_entry_t), 1, f); fwrite(&entry, sizeof(fast_reload_cow_entry_t), 1, f);
dump_primary_buffer(self->cow_cache_array[i], tmp2); dump_primary_buffer(self->cow_cache_array[i], tmp2);

View File

@ -1,21 +1,21 @@
#pragma once #pragma once
#include <stdint.h>
#include "nyx/snapshot/block/block_cow.h" #include "nyx/snapshot/block/block_cow.h"
#include <stdint.h>
typedef struct nyx_block_s{ typedef struct nyx_block_s {
cow_cache_t **cow_cache_array; cow_cache_t **cow_cache_array;
uint32_t cow_cache_array_size; uint32_t cow_cache_array_size;
} nyx_block_t; } nyx_block_t;
nyx_block_t* nyx_block_snapshot_init_from_file(const char* folder, bool pre_snapshot); nyx_block_t *nyx_block_snapshot_init_from_file(const char *folder, bool pre_snapshot);
nyx_block_t* nyx_block_snapshot_init(void); nyx_block_t *nyx_block_snapshot_init(void);
void nyx_block_snapshot_switch_to_incremental(nyx_block_t*); void nyx_block_snapshot_switch_to_incremental(nyx_block_t *);
void nyx_block_snapshot_flush(nyx_block_t* self); void nyx_block_snapshot_flush(nyx_block_t *self);
void nyx_block_snapshot_switch_incremental(nyx_block_t* self); void nyx_block_snapshot_switch_incremental(nyx_block_t *self);
void nyx_block_snapshot_disable_incremental(nyx_block_t* self); void nyx_block_snapshot_disable_incremental(nyx_block_t *self);
void nyx_block_snapshot_reset(nyx_block_t* self); void nyx_block_snapshot_reset(nyx_block_t *self);
void nyx_block_snapshot_serialize(nyx_block_t* self, const char* snapshot_folder); void nyx_block_snapshot_serialize(nyx_block_t *self, const char *snapshot_folder);

View File

@ -34,32 +34,34 @@
extern void enable_fast_snapshot_rtc(void); extern void enable_fast_snapshot_rtc(void);
extern void enable_fast_snapshot_kvm_clock(void); extern void enable_fast_snapshot_kvm_clock(void);
static void enable_fast_snapshot_mode(void){ static void enable_fast_snapshot_mode(void)
{
enable_fast_snapshot_rtc(); enable_fast_snapshot_rtc();
enable_fast_snapshot_kvm_clock(); enable_fast_snapshot_kvm_clock();
} }
extern int kvm_nyx_put_tsc_value(CPUState *cs, uint64_t data); extern int kvm_nyx_put_tsc_value(CPUState *cs, uint64_t data);
static void set_tsc_value(nyx_device_state_t* self, bool tmp_snapshot){ static void set_tsc_value(nyx_device_state_t *self, bool tmp_snapshot)
if(self->incremental_mode){ {
if (self->incremental_mode) {
assert(self->tsc_value_incremental); assert(self->tsc_value_incremental);
assert(kvm_nyx_put_tsc_value(qemu_get_cpu(0), self->tsc_value_incremental) == 0); assert(kvm_nyx_put_tsc_value(qemu_get_cpu(0), self->tsc_value_incremental) ==
} 0);
else{ } else {
assert(self->tsc_value); assert(self->tsc_value);
assert(kvm_nyx_put_tsc_value(qemu_get_cpu(0), self->tsc_value) == 0); assert(kvm_nyx_put_tsc_value(qemu_get_cpu(0), self->tsc_value) == 0);
} }
} }
static void save_tsc_value(nyx_device_state_t* self, bool incremental_mode){ static void save_tsc_value(nyx_device_state_t *self, bool incremental_mode)
{
X86CPU *cpu = X86_CPU(qemu_get_cpu(0)); X86CPU *cpu = X86_CPU(qemu_get_cpu(0));
CPUX86State *env = &cpu->env; CPUX86State *env = &cpu->env;
if(incremental_mode){ if (incremental_mode) {
self->tsc_value_incremental = env->tsc; self->tsc_value_incremental = env->tsc;
} } else {
else{
self->tsc_value = env->tsc; self->tsc_value = env->tsc;
} }
} }
@ -115,12 +117,12 @@ static void fast_qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_o
cpu_synchronize_all_states(); cpu_synchronize_all_states();
QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { QTAILQ_FOREACH (se, &savevm_state.handlers, entry) {
if(strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")){ if (strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")) {
if (!se->ops || if (!se->ops || (in_postcopy && se->ops->save_live_complete_postcopy) ||
(in_postcopy && se->ops->save_live_complete_postcopy) ||
(in_postcopy && !iterable_only) || (in_postcopy && !iterable_only) ||
!se->ops->save_live_complete_precopy) { !se->ops->save_live_complete_precopy)
{
continue; continue;
} }
@ -148,8 +150,8 @@ static void fast_qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_o
vmdesc = qjson_new(); vmdesc = qjson_new();
json_prop_int(vmdesc, "page_size", TARGET_PAGE_SIZE); json_prop_int(vmdesc, "page_size", TARGET_PAGE_SIZE);
json_start_array(vmdesc, "devices"); json_start_array(vmdesc, "devices");
QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { QTAILQ_FOREACH (se, &savevm_state.handlers, entry) {
if(strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")){ if (strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")) {
if ((!se->ops || !se->ops->save_state) && !se->vmsd) { if ((!se->ops || !se->ops->save_state) && !se->vmsd) {
continue; continue;
} }
@ -189,12 +191,13 @@ static void fast_qemu_savevm_state_complete_precopy(QEMUFile *f, bool iterable_o
} }
static int fast_qemu_savevm_state_iterate(QEMUFile *f, bool postcopy) { static int fast_qemu_savevm_state_iterate(QEMUFile *f, bool postcopy)
{
SaveStateEntry *se; SaveStateEntry *se;
int ret = 1; int ret = 1;
QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { QTAILQ_FOREACH (se, &savevm_state.handlers, entry) {
if(strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")){ if (strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")) {
if (!se->ops || !se->ops->save_live_iterate) { if (!se->ops || !se->ops->save_live_iterate) {
continue; continue;
} }
@ -236,12 +239,13 @@ static int fast_qemu_savevm_state_iterate(QEMUFile *f, bool postcopy) {
return ret; return ret;
} }
static void fast_qemu_savevm_state_setup(QEMUFile *f){ static void fast_qemu_savevm_state_setup(QEMUFile *f)
{
SaveStateEntry *se; SaveStateEntry *se;
int ret; int ret;
QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { QTAILQ_FOREACH (se, &savevm_state.handlers, entry) {
if(strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")){ if (strcmp(se->idstr, "ram") && strcmp(se->idstr, "block")) {
if (!se->ops || !se->ops->save_setup) { if (!se->ops || !se->ops->save_setup) {
continue; continue;
} }
@ -263,7 +267,8 @@ static void fast_qemu_savevm_state_setup(QEMUFile *f){
} }
static int fast_qemu_savevm_state(QEMUFile *f, Error **errp) { static int fast_qemu_savevm_state(QEMUFile *f, Error **errp)
{
qemu_savevm_state_header(f); qemu_savevm_state_header(f);
fast_qemu_savevm_state_setup(f); fast_qemu_savevm_state_setup(f);
@ -278,64 +283,79 @@ static int fast_qemu_savevm_state(QEMUFile *f, Error **errp) {
} }
/* QEMUFile RAM Emulation */ /* QEMUFile RAM Emulation */
static ssize_t fast_savevm_writev_buffer(void *opaque, struct iovec *iov, int iovcnt, int64_t pos){ static ssize_t fast_savevm_writev_buffer(void *opaque,
struct iovec *iov,
int iovcnt,
int64_t pos)
{
ssize_t retval = 0; ssize_t retval = 0;
for(uint32_t i = 0; i < iovcnt; i++){ for (uint32_t i = 0; i < iovcnt; i++) {
memcpy((void*)(((struct fast_savevm_opaque_t*)(opaque))->buf + ((struct fast_savevm_opaque_t*)(opaque))->pos), iov[i].iov_base, iov[i].iov_len); memcpy((void *)(((struct fast_savevm_opaque_t *)(opaque))->buf +
((struct fast_savevm_opaque_t*)(opaque))->pos += iov[i].iov_len; ((struct fast_savevm_opaque_t *)(opaque))->pos),
iov[i].iov_base, iov[i].iov_len);
((struct fast_savevm_opaque_t *)(opaque))->pos += iov[i].iov_len;
retval += iov[i].iov_len; retval += iov[i].iov_len;
} }
return retval; return retval;
} }
static int fast_savevm_fclose_save_to_buffer(void *opaque){ static int fast_savevm_fclose_save_to_buffer(void *opaque)
memcpy(((struct fast_savevm_opaque_t*)(opaque))->output_buffer, ((struct fast_savevm_opaque_t*)(opaque))->buf, ((struct fast_savevm_opaque_t*)(opaque))->pos); {
*((struct fast_savevm_opaque_t*)(opaque))->output_buffer_size = ((struct fast_savevm_opaque_t*)(opaque))->pos; memcpy(((struct fast_savevm_opaque_t *)(opaque))->output_buffer,
//printf("DUMPED: %d\n", *((struct fast_savevm_opaque_t*)(opaque))->output_buffer_size); ((struct fast_savevm_opaque_t *)(opaque))->buf,
((struct fast_savevm_opaque_t *)(opaque))->pos);
*((struct fast_savevm_opaque_t *)(opaque))->output_buffer_size =
((struct fast_savevm_opaque_t *)(opaque))->pos;
// printf("DUMPED: %d\n", *((struct fast_savevm_opaque_t*)(opaque))->output_buffer_size);
return 0; return 0;
} }
static int fast_loadvm_fclose(void *opaque){ static int fast_loadvm_fclose(void *opaque)
{
return 0; return 0;
} }
static ssize_t fast_loadvm_get_buffer(void *opaque, uint8_t *buf, int64_t pos, size_t size){ static ssize_t fast_loadvm_get_buffer(void *opaque, uint8_t *buf, int64_t pos, size_t size)
memcpy(buf, (void*)(((struct fast_savevm_opaque_t*)(opaque))->buf + pos), size); {
memcpy(buf, (void *)(((struct fast_savevm_opaque_t *)(opaque))->buf + pos), size);
return size; return size;
} }
static const QEMUFileOps fast_loadvm_ops = { static const QEMUFileOps fast_loadvm_ops = {
.get_buffer = (QEMUFileGetBufferFunc*)fast_loadvm_get_buffer, .get_buffer = (QEMUFileGetBufferFunc *)fast_loadvm_get_buffer,
.close = (QEMUFileCloseFunc*)fast_loadvm_fclose .close = (QEMUFileCloseFunc *)fast_loadvm_fclose
}; };
static const QEMUFileOps fast_savevm_ops_to_buffer = { static const QEMUFileOps fast_savevm_ops_to_buffer = {
.writev_buffer = (QEMUFileWritevBufferFunc*)fast_savevm_writev_buffer, .writev_buffer = (QEMUFileWritevBufferFunc *)fast_savevm_writev_buffer,
.close = (QEMUFileCloseFunc*)fast_savevm_fclose_save_to_buffer .close = (QEMUFileCloseFunc *)fast_savevm_fclose_save_to_buffer
}; };
nyx_device_state_t* nyx_device_state_init_from_snapshot(const char* snapshot_folder, bool pre_snapshot){ nyx_device_state_t *nyx_device_state_init_from_snapshot(const char *snapshot_folder,
nyx_device_state_t* self = malloc(sizeof(nyx_device_state_t)); bool pre_snapshot)
{
nyx_device_state_t *self = malloc(sizeof(nyx_device_state_t));
memset(self, 0, sizeof(nyx_device_state_t)); memset(self, 0, sizeof(nyx_device_state_t));
self->state_buf = malloc(STATE_BUFFER); self->state_buf = malloc(STATE_BUFFER);
self->state_buf_size = 0; self->state_buf_size = 0;
char* qemu_state_file; char *qemu_state_file;
assert(asprintf(&qemu_state_file, "%s/fast_snapshot.qemu_state", snapshot_folder) != -1); assert(asprintf(&qemu_state_file, "%s/fast_snapshot.qemu_state",
snapshot_folder) != -1);
struct fast_savevm_opaque_t fast_savevm_opaque; struct fast_savevm_opaque_t fast_savevm_opaque;
FILE* f; FILE *f;
uint8_t ret = global_state_store(); uint8_t ret = global_state_store();
assert(!ret); assert(!ret);
struct stat buffer; struct stat buffer;
assert(stat (qemu_state_file, &buffer) == 0); assert(stat(qemu_state_file, &buffer) == 0);
void* state_buf2 = malloc(STATE_BUFFER); void *state_buf2 = malloc(STATE_BUFFER);
f = fopen(qemu_state_file, "r"); f = fopen(qemu_state_file, "r");
assert(fread(state_buf2, buffer.st_size, 1, f) == 1); assert(fread(state_buf2, buffer.st_size, 1, f) == 1);
@ -344,18 +364,18 @@ nyx_device_state_t* nyx_device_state_init_from_snapshot(const char* snapshot_fol
fast_savevm_opaque.buf = state_buf2; fast_savevm_opaque.buf = state_buf2;
fast_savevm_opaque.f = NULL; fast_savevm_opaque.f = NULL;
fast_savevm_opaque.pos = 0; fast_savevm_opaque.pos = 0;
QEMUFile* file_dump = qemu_fopen_ops(&fast_savevm_opaque, &fast_loadvm_ops); QEMUFile *file_dump = qemu_fopen_ops(&fast_savevm_opaque, &fast_loadvm_ops);
qemu_devices_reset(); qemu_devices_reset();
qemu_loadvm_state(file_dump); qemu_loadvm_state(file_dump);
if(!pre_snapshot){ if (!pre_snapshot) {
self->qemu_state = state_reallocation_new(file_dump); self->qemu_state = state_reallocation_new(file_dump);
} }
free(state_buf2); free(state_buf2);
if(!pre_snapshot){ if (!pre_snapshot) {
enable_fast_snapshot_mode(); enable_fast_snapshot_mode();
save_tsc_value(self, false); save_tsc_value(self, false);
} }
@ -369,9 +389,9 @@ nyx_device_state_t* nyx_device_state_init_from_snapshot(const char* snapshot_fol
* backed by RAM. state_reallocation_new() then uses this file to build an * backed by RAM. state_reallocation_new() then uses this file to build an
* optimized sequence of snapshot restore operations. * optimized sequence of snapshot restore operations.
*/ */
nyx_device_state_t* nyx_device_state_init(void){ nyx_device_state_t *nyx_device_state_init(void)
{
nyx_device_state_t* self = malloc(sizeof(nyx_device_state_t)); nyx_device_state_t *self = malloc(sizeof(nyx_device_state_t));
memset(self, 0, sizeof(nyx_device_state_t)); memset(self, 0, sizeof(nyx_device_state_t));
self->state_buf = malloc(STATE_BUFFER); self->state_buf = malloc(STATE_BUFFER);
@ -380,7 +400,7 @@ nyx_device_state_t* nyx_device_state_init(void){
Error *local_err = NULL; Error *local_err = NULL;
struct fast_savevm_opaque_t fast_savevm_opaque, fast_loadvm_opaque; struct fast_savevm_opaque_t fast_savevm_opaque, fast_loadvm_opaque;
void* tmp_buf = malloc(1024*1024*16); void *tmp_buf = malloc(1024 * 1024 * 16);
fast_savevm_opaque.output_buffer = self->state_buf; fast_savevm_opaque.output_buffer = self->state_buf;
fast_savevm_opaque.output_buffer_size = &self->state_buf_size; fast_savevm_opaque.output_buffer_size = &self->state_buf_size;
@ -392,13 +412,13 @@ nyx_device_state_t* nyx_device_state_init(void){
uint8_t ret = global_state_store(); uint8_t ret = global_state_store();
assert(!ret); assert(!ret);
QEMUFile* f = qemu_fopen_ops(&fast_savevm_opaque, &fast_savevm_ops_to_buffer); QEMUFile *f = qemu_fopen_ops(&fast_savevm_opaque, &fast_savevm_ops_to_buffer);
ret = fast_qemu_savevm_state(f, &local_err); ret = fast_qemu_savevm_state(f, &local_err);
fast_loadvm_opaque.buf = tmp_buf; fast_loadvm_opaque.buf = tmp_buf;
fast_loadvm_opaque.f = NULL; fast_loadvm_opaque.f = NULL;
fast_loadvm_opaque.pos = 0; fast_loadvm_opaque.pos = 0;
QEMUFile* file_dump = qemu_fopen_ops(&fast_loadvm_opaque, &fast_loadvm_ops); QEMUFile *file_dump = qemu_fopen_ops(&fast_loadvm_opaque, &fast_loadvm_ops);
self->qemu_state = state_reallocation_new(file_dump); self->qemu_state = state_reallocation_new(file_dump);
qemu_fclose(file_dump); qemu_fclose(file_dump);
@ -411,41 +431,49 @@ nyx_device_state_t* nyx_device_state_init(void){
return self; return self;
} }
void nyx_device_state_switch_incremental(nyx_device_state_t* self){ void nyx_device_state_switch_incremental(nyx_device_state_t *self)
{
self->incremental_mode = true; self->incremental_mode = true;
fdl_fast_create_tmp(self->qemu_state); fdl_fast_create_tmp(self->qemu_state);
fdl_fast_enable_tmp(self->qemu_state); fdl_fast_enable_tmp(self->qemu_state);
} }
void nyx_device_state_disable_incremental(nyx_device_state_t* self){ void nyx_device_state_disable_incremental(nyx_device_state_t *self)
{
fdl_fast_disable_tmp(self->qemu_state); fdl_fast_disable_tmp(self->qemu_state);
self->incremental_mode = false; self->incremental_mode = false;
} }
void nyx_device_state_restore(nyx_device_state_t* self){ void nyx_device_state_restore(nyx_device_state_t *self)
{
fdl_fast_reload(self->qemu_state); fdl_fast_reload(self->qemu_state);
call_fast_change_handlers(); call_fast_change_handlers();
} }
void nyx_device_state_post_restore(nyx_device_state_t* self){ void nyx_device_state_post_restore(nyx_device_state_t *self)
{
set_tsc_value(self, self->incremental_mode); set_tsc_value(self, self->incremental_mode);
} }
void nyx_device_state_save_tsc(nyx_device_state_t* self){ void nyx_device_state_save_tsc(nyx_device_state_t *self)
{
save_tsc_value(self, false); save_tsc_value(self, false);
} }
void nyx_device_state_save_tsc_incremental(nyx_device_state_t* self){ void nyx_device_state_save_tsc_incremental(nyx_device_state_t *self)
{
save_tsc_value(self, true); save_tsc_value(self, true);
} }
void nyx_device_state_serialize(nyx_device_state_t* self, const char* snapshot_folder){ void nyx_device_state_serialize(nyx_device_state_t *self, const char *snapshot_folder)
char* tmp; {
char *tmp;
assert(asprintf(&tmp, "%s/fast_snapshot.qemu_state", snapshot_folder) != -1); assert(asprintf(&tmp, "%s/fast_snapshot.qemu_state", snapshot_folder) != -1);
FILE* f_qemu_state = fopen(tmp, "w+b"); FILE *f_qemu_state = fopen(tmp, "w+b");
assert(fwrite(self->state_buf, 1, self->state_buf_size, f_qemu_state) == self->state_buf_size); assert(fwrite(self->state_buf, 1, self->state_buf_size, f_qemu_state) ==
self->state_buf_size);
fclose(f_qemu_state); fclose(f_qemu_state);
} }

View File

@ -1,33 +1,34 @@
#pragma once #pragma once
#include <stdint.h>
#include <stdbool.h>
#include "nyx/snapshot/devices/state_reallocation.h" #include "nyx/snapshot/devices/state_reallocation.h"
#include <stdbool.h>
#include <stdint.h>
typedef struct nyx_device_state_s{ typedef struct nyx_device_state_s {
state_reallocation_t* qemu_state; state_reallocation_t *qemu_state;
uint64_t tsc_value; uint64_t tsc_value;
uint64_t tsc_value_incremental; uint64_t tsc_value_incremental;
bool incremental_mode; bool incremental_mode;
void* state_buf; /* QEMU's serialized state */ void *state_buf; /* QEMU's serialized state */
uint32_t state_buf_size; uint32_t state_buf_size;
} nyx_device_state_t; } nyx_device_state_t;
nyx_device_state_t* nyx_device_state_init(void); nyx_device_state_t *nyx_device_state_init(void);
nyx_device_state_t* nyx_device_state_init_from_snapshot(const char* snapshot_folder, bool pre_snapshot); nyx_device_state_t *nyx_device_state_init_from_snapshot(const char *snapshot_folder,
bool pre_snapshot);
void nyx_device_state_restore(nyx_device_state_t* self); void nyx_device_state_restore(nyx_device_state_t *self);
void nyx_device_state_post_restore(nyx_device_state_t* self); void nyx_device_state_post_restore(nyx_device_state_t *self);
void nyx_device_state_switch_incremental(nyx_device_state_t* self); void nyx_device_state_switch_incremental(nyx_device_state_t *self);
void nyx_device_state_disable_incremental(nyx_device_state_t* self); void nyx_device_state_disable_incremental(nyx_device_state_t *self);
void nyx_device_state_save_tsc(nyx_device_state_t* self); void nyx_device_state_save_tsc(nyx_device_state_t *self);
void nyx_device_state_save_tsc_incremental(nyx_device_state_t* self); void nyx_device_state_save_tsc_incremental(nyx_device_state_t *self);
void nyx_device_state_serialize(nyx_device_state_t* self, const char* snapshot_folder); void nyx_device_state_serialize(nyx_device_state_t *self, const char *snapshot_folder);

View File

@ -33,7 +33,7 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#include "nyx/snapshot/devices/nyx_device_state.h" #include "nyx/snapshot/devices/nyx_device_state.h"
#include "nyx/snapshot/devices/state_reallocation.h" #include "nyx/snapshot/devices/state_reallocation.h"
//#define VERBOSE_DEBUG // #define VERBOSE_DEBUG
#define QEMU_VM_SUBSECTION 0x05 #define QEMU_VM_SUBSECTION 0x05
@ -74,7 +74,7 @@ typedef struct SaveState {
uint32_t target_page_bits; uint32_t target_page_bits;
} SaveState; } SaveState;
extern void* vmstate_configuration; extern void *vmstate_configuration;
extern SaveState savevm_state; extern SaveState savevm_state;
extern int vmstate_n_elems(void *opaque, VMStateField *field); extern int vmstate_n_elems(void *opaque, VMStateField *field);
@ -82,10 +82,10 @@ extern int vmstate_size(void *opaque, VMStateField *field);
extern void vmstate_handle_alloc(void *ptr, VMStateField *field, void *opaque); extern void vmstate_handle_alloc(void *ptr, VMStateField *field, void *opaque);
extern int vmstate_load(QEMUFile *f, SaveStateEntry *se); extern int vmstate_load(QEMUFile *f, SaveStateEntry *se);
static void fast_timer_get(void* data, size_t size, void* opaque) static void fast_timer_get(void *data, size_t size, void *opaque)
{ {
QEMUTimer *ts = (QEMUTimer*) opaque; QEMUTimer *ts = (QEMUTimer *)opaque;
uint64_t expire_time = *((uint64_t*)data); uint64_t expire_time = *((uint64_t *)data);
if (expire_time != -1) { if (expire_time != -1) {
timer_mod_ns(ts, expire_time); timer_mod_ns(ts, expire_time);
} else { } else {
@ -97,17 +97,17 @@ static SaveStateEntry *fdl_find_se(const char *idstr, int instance_id)
{ {
SaveStateEntry *se; SaveStateEntry *se;
QTAILQ_FOREACH(se, &savevm_state.handlers, entry) { QTAILQ_FOREACH (se, &savevm_state.handlers, entry) {
if (!strcmp(se->idstr, idstr) && if (!strcmp(se->idstr, idstr) &&
(instance_id == se->instance_id || (instance_id == se->instance_id || instance_id == se->alias_id))
instance_id == se->alias_id)){ {
return se; return se;
} }
/* Migrating from an older version? */ /* Migrating from an older version? */
if (strstr(se->idstr, idstr) && se->compat) { if (strstr(se->idstr, idstr) && se->compat) {
if (!strcmp(se->compat->idstr, idstr) && if (!strcmp(se->compat->idstr, idstr) &&
(instance_id == se->compat->instance_id || (instance_id == se->compat->instance_id || instance_id == se->alias_id))
instance_id == se->alias_id)){ {
return se; return se;
} }
} }
@ -115,10 +115,16 @@ static SaveStateEntry *fdl_find_se(const char *idstr, int instance_id)
return NULL; return NULL;
} }
static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const VMStateDescription *vmsd, void *opaque, int version_id, uintptr_t* opaque_ptr); static int fdl_vmstate_load_state(state_reallocation_t *self,
QEMUFile *f,
const VMStateDescription *vmsd,
void *opaque,
int version_id,
uintptr_t *opaque_ptr);
static inline VMStateDescription* fdl_vmstate_get_subsection(VMStateDescription **sub, char *idstr) static inline VMStateDescription *fdl_vmstate_get_subsection(VMStateDescription **sub,
char *idstr)
{ {
while (sub && *sub && (*sub)->needed) { while (sub && *sub && (*sub)->needed) {
if (strcmp(idstr, (*sub)->name) == 0) { if (strcmp(idstr, (*sub)->name) == 0) {
@ -129,7 +135,10 @@ static inline VMStateDescription* fdl_vmstate_get_subsection(VMStateDescription
return NULL; return NULL;
} }
static int fdl_vmstate_subsection_load(state_reallocation_t* self, QEMUFile *f, const VMStateDescription *vmsd, void *opaque) static int fdl_vmstate_subsection_load(state_reallocation_t *self,
QEMUFile *f,
const VMStateDescription *vmsd,
void *opaque)
{ {
while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) { while (qemu_peek_byte(f, 0) == QEMU_VM_SUBSECTION) {
char idstr[256], *idstr_ret; char idstr[256], *idstr_ret;
@ -153,7 +162,8 @@ static int fdl_vmstate_subsection_load(state_reallocation_t* self, QEMUFile *f,
/* it doesn't have a valid subsection name */ /* it doesn't have a valid subsection name */
return 0; return 0;
} }
sub_vmsd = fdl_vmstate_get_subsection((VMStateDescription **)vmsd->subsections, idstr); sub_vmsd = fdl_vmstate_get_subsection((VMStateDescription **)vmsd->subsections,
idstr);
if (sub_vmsd == NULL) { if (sub_vmsd == NULL) {
return -ENOENT; return -ENOENT;
} }
@ -172,27 +182,27 @@ static int fdl_vmstate_subsection_load(state_reallocation_t* self, QEMUFile *f,
} }
uint32_t post_counter = 0; uint32_t post_counter = 0;
void* post_fptr_array[256]; void *post_fptr_array[256];
uint32_t post_version_id_array[256]; uint32_t post_version_id_array[256];
void* post_opaque_array[256]; void *post_opaque_array[256];
static void add_post_fptr(state_reallocation_t *self,
void *fptr,
uint32_t version_id,
static void add_post_fptr(state_reallocation_t* self, void* fptr, uint32_t version_id, void* opaque, const char* name){ void *opaque,
const char *name)
if(!self){ {
if (!self) {
return; return;
} }
if(!strcmp("I440FX", name)){ if (!strcmp("I440FX", name)) {
return; return;
} }
if (1) {
if(1){
/* /*
if( !strcmp("cpu_common", name) || if( !strcmp("cpu_common", name) ||
!strcmp("cpu/nested_state", name) || !strcmp("cpu/nested_state", name) ||
@ -247,46 +257,51 @@ static void add_post_fptr(state_reallocation_t* self, void* fptr, uint32_t versi
--> globalstate --> globalstate
*/ */
//fprintf(stderr, "--> %s\n", name); // fprintf(stderr, "--> %s\n", name);
self->fptr[self->fast_state_fptr_pos] = fptr; self->fptr[self->fast_state_fptr_pos] = fptr;
self->opaque[self->fast_state_fptr_pos] = opaque; self->opaque[self->fast_state_fptr_pos] = opaque;
self->version[self->fast_state_fptr_pos] = version_id; self->version[self->fast_state_fptr_pos] = version_id;
self->fast_state_fptr_pos++; self->fast_state_fptr_pos++;
if(self->fast_state_fptr_pos >= self->fast_state_fptr_size){ if (self->fast_state_fptr_pos >= self->fast_state_fptr_size) {
nyx_debug("RESIZE %s\n", __func__); nyx_debug("RESIZE %s\n", __func__);
self->fast_state_fptr_size += REALLOC_SIZE; self->fast_state_fptr_size += REALLOC_SIZE;
self->fptr = realloc(self->fptr, self->fast_state_fptr_size * sizeof(void*)); self->fptr =
self->opaque = realloc(self->opaque, self->fast_state_fptr_size * sizeof(void*)); realloc(self->fptr, self->fast_state_fptr_size * sizeof(void *));
self->version = realloc(self->version, self->fast_state_fptr_size * sizeof(uint32_t)); self->opaque =
realloc(self->opaque, self->fast_state_fptr_size * sizeof(void *));
self->version =
realloc(self->version, self->fast_state_fptr_size * sizeof(uint32_t));
} }
} }
} }
extern void fast_get_pci_config_device(void* data, size_t size, void* opaque); extern void fast_get_pci_config_device(void *data, size_t size, void *opaque);
void fast_get_pci_irq_state(void* data, size_t size, void* opaque); void fast_get_pci_irq_state(void *data, size_t size, void *opaque);
//void fast_virtio_device_get(void* data, size_t size, void* opaque); // void fast_virtio_device_get(void* data, size_t size, void* opaque);
int virtio_device_get(QEMUFile *f, void *opaque, size_t size, const VMStateField *field); int virtio_device_get(QEMUFile *f, void *opaque, size_t size, const VMStateField *field);
static int fast_loadvm_fclose(void *opaque){ static int fast_loadvm_fclose(void *opaque)
{
return 0; return 0;
} }
static ssize_t fast_loadvm_get_buffer(void *opaque, uint8_t *buf, int64_t pos, size_t size){ static ssize_t fast_loadvm_get_buffer(void *opaque, uint8_t *buf, int64_t pos, size_t size)
assert(pos < ((struct fast_savevm_opaque_t*)(opaque))->buflen); {
memcpy(buf, (void*)(((struct fast_savevm_opaque_t*)(opaque))->buf + pos), size); assert(pos < ((struct fast_savevm_opaque_t *)(opaque))->buflen);
memcpy(buf, (void *)(((struct fast_savevm_opaque_t *)(opaque))->buf + pos), size);
return size; return size;
} }
static const QEMUFileOps fast_loadvm_ops = { static const QEMUFileOps fast_loadvm_ops = {
.get_buffer = (QEMUFileGetBufferFunc*)fast_loadvm_get_buffer, .get_buffer = (QEMUFileGetBufferFunc *)fast_loadvm_get_buffer,
.close = (QEMUFileCloseFunc*)fast_loadvm_fclose .close = (QEMUFileCloseFunc *)fast_loadvm_fclose
}; };
/* use opaque data to bootstrap virtio restore from QEMUFile */ /* use opaque data to bootstrap virtio restore from QEMUFile */
static void fast_virtio_device_get(void* data, size_t size, void* opaque) static void fast_virtio_device_get(void *data, size_t size, void *opaque)
{ {
struct fast_savevm_opaque_t fast_loadvm_opaque = { struct fast_savevm_opaque_t fast_loadvm_opaque = {
.buf = data, .buf = data,
@ -294,50 +309,55 @@ static void fast_virtio_device_get(void* data, size_t size, void* opaque)
.f = NULL, .f = NULL,
.pos = 0, .pos = 0,
}; };
QEMUFile* f = qemu_fopen_ops(&fast_loadvm_opaque, &fast_loadvm_ops); QEMUFile *f = qemu_fopen_ops(&fast_loadvm_opaque, &fast_loadvm_ops);
virtio_device_get(f, opaque, size, NULL); virtio_device_get(f, opaque, size, NULL);
} }
static void add_get(state_reallocation_t* self, void* fptr, void* opaque, size_t size, void* field, QEMUFile* f, const char* name){ static void add_get(state_reallocation_t *self,
if(!self){ void *fptr,
void *opaque,
size_t size,
void *field,
QEMUFile *f,
const char *name)
{
if (!self) {
return; return;
} }
void (*handler)(void* , size_t, void*) = NULL; void (*handler)(void *, size_t, void *) = NULL;
uint8_t* data = NULL; uint8_t *data = NULL;
if(!strcmp(name, "timer")){ if (!strcmp(name, "timer")) {
nyx_debug("SKPPING: %ld\n", size*-1); nyx_debug("SKPPING: %ld\n", size * -1);
qemu_file_skip(f, size * -1); qemu_file_skip(f, size * -1);
handler = fast_timer_get; handler = fast_timer_get;
data = malloc(sizeof(uint64_t)); data = malloc(sizeof(uint64_t));
*((uint64_t*)data) = qemu_get_be64(f); *((uint64_t *)data) = qemu_get_be64(f);
} }
else if(!strcmp(name, "pci irq state")){ else if (!strcmp(name, "pci irq state"))
{
qemu_file_skip(f, size * -1); qemu_file_skip(f, size * -1);
handler = fast_get_pci_irq_state; handler = fast_get_pci_irq_state;
data = malloc(sizeof(uint8_t)*size); data = malloc(sizeof(uint8_t) * size);
((uint32_t*)data)[0] = qemu_get_be32(f); ((uint32_t *)data)[0] = qemu_get_be32(f);
((uint32_t*)data)[1] = qemu_get_be32(f); ((uint32_t *)data)[1] = qemu_get_be32(f);
((uint32_t*)data)[2] = qemu_get_be32(f); ((uint32_t *)data)[2] = qemu_get_be32(f);
((uint32_t*)data)[3] = qemu_get_be32(f); ((uint32_t *)data)[3] = qemu_get_be32(f);
} } else if (!strcmp(name, "pci config")) {
else if(!strcmp(name, "pci config")){
qemu_file_skip(f, size * -1); qemu_file_skip(f, size * -1);
handler = fast_get_pci_config_device; handler = fast_get_pci_config_device;
data = malloc(sizeof(uint8_t)*size); data = malloc(sizeof(uint8_t) * size);
qemu_get_buffer(f, (uint8_t*)data, size); qemu_get_buffer(f, (uint8_t *)data, size);
} } else if (!strcmp(name, "virtio")) {
else if(!strcmp(name, "virtio")){
qemu_file_skip(f, size * -1); qemu_file_skip(f, size * -1);
handler = fast_virtio_device_get; handler = fast_virtio_device_get;
data = malloc(sizeof(uint8_t)*size); data = malloc(sizeof(uint8_t) * size);
qemu_get_buffer(f, (uint8_t*)data, size); qemu_get_buffer(f, (uint8_t *)data, size);
} } else {
else{
fprintf(stderr, "WARNING: NOT IMPLEMENTED FAST GET ROUTINE for %s\n", name); fprintf(stderr, "WARNING: NOT IMPLEMENTED FAST GET ROUTINE for %s\n", name);
abort(); abort();
return; return;
@ -352,158 +372,173 @@ static void add_get(state_reallocation_t* self, void* fptr, void* opaque, size_t
self->fast_state_get_fptr_pos++; self->fast_state_get_fptr_pos++;
if(self->fast_state_get_fptr_pos >= self->fast_state_get_fptr_size){ if (self->fast_state_get_fptr_pos >= self->fast_state_get_fptr_size) {
nyx_debug("RESIZE %s\n", __func__); nyx_debug("RESIZE %s\n", __func__);
self->fast_state_get_fptr_size += REALLOC_SIZE; self->fast_state_get_fptr_size += REALLOC_SIZE;
self->get_fptr = realloc(self->get_fptr, self->fast_state_get_fptr_size * sizeof(void*)); self->get_fptr =
self->get_opaque = realloc(self->get_opaque, self->fast_state_get_fptr_size * sizeof(void*)); realloc(self->get_fptr, self->fast_state_get_fptr_size * sizeof(void *));
self->get_size = realloc(self->get_size, self->fast_state_get_fptr_size * sizeof(size_t)); self->get_opaque = realloc(self->get_opaque,
self->get_data = realloc(self->get_data, self->fast_state_get_fptr_size * sizeof(void*)); self->fast_state_get_fptr_size * sizeof(void *));
self->get_size =
realloc(self->get_size, self->fast_state_get_fptr_size * sizeof(size_t));
self->get_data =
realloc(self->get_data, self->fast_state_get_fptr_size * sizeof(void *));
} }
} }
static void add_mblock(state_reallocation_t* self, char* foo, const char* bar, size_t offset, uint64_t start, uint64_t size){ static void add_mblock(state_reallocation_t *self,
char *foo,
if(!self){ const char *bar,
size_t offset,
uint64_t start,
uint64_t size)
{
if (!self) {
return; return;
} }
if(self->fast_state_pos && (uint64_t)(self->ptr[self->fast_state_pos-1]+self->size[self->fast_state_pos-1]) == start){ if (self->fast_state_pos &&
void* new = (void*)(self->pre_alloc_block+self->pre_alloc_block_offset); (uint64_t)(self->ptr[self->fast_state_pos - 1] +
self->size[self->fast_state_pos - 1]) == start)
{
void *new = (void *)(self->pre_alloc_block + self->pre_alloc_block_offset);
self->pre_alloc_block_offset += size; self->pre_alloc_block_offset += size;
memcpy(new, (void*)start, size); memcpy(new, (void *)start, size);
self->size[self->fast_state_pos-1] = size + self->size[self->fast_state_pos-1]; self->size[self->fast_state_pos - 1] =
} size + self->size[self->fast_state_pos - 1];
else{ } else {
self->ptr[self->fast_state_pos] = (void*)start; self->ptr[self->fast_state_pos] = (void *)start;
self->copy[self->fast_state_pos] = (void*)(self->pre_alloc_block+self->pre_alloc_block_offset); self->copy[self->fast_state_pos] =
(void *)(self->pre_alloc_block + self->pre_alloc_block_offset);
self->pre_alloc_block_offset += size; self->pre_alloc_block_offset += size;
memcpy(self->copy[self->fast_state_pos], (void*)start, size); memcpy(self->copy[self->fast_state_pos], (void *)start, size);
self->size[self->fast_state_pos] = size; self->size[self->fast_state_pos] = size;
self->fast_state_pos++; self->fast_state_pos++;
if(self->fast_state_pos >= self->fast_state_size){ if (self->fast_state_pos >= self->fast_state_size) {
self->fast_state_size += REALLOC_SIZE; self->fast_state_size += REALLOC_SIZE;
self->ptr = realloc(self->ptr, self->fast_state_size * sizeof(void*)); self->ptr = realloc(self->ptr, self->fast_state_size * sizeof(void *));
self->copy = realloc(self->copy, self->fast_state_size * sizeof(void*)); self->copy = realloc(self->copy, self->fast_state_size * sizeof(void *));
self->size = realloc(self->size, self->fast_state_size * sizeof(size_t)); self->size = realloc(self->size, self->fast_state_size * sizeof(size_t));
} }
} }
} }
static inline int get_handler(state_reallocation_t* self, QEMUFile* f, void* curr_elem, size_t size, VMStateField *field, char* vmsd_name){ static inline int get_handler(state_reallocation_t *self,
QEMUFile *f,
void *curr_elem,
size_t size,
VMStateField *field,
char *vmsd_name)
{
int ret; int ret;
//printf("%s\n", vmsd_name); // printf("%s\n", vmsd_name);
ret = field->info->get(f, curr_elem, size, field); ret = field->info->get(f, curr_elem, size, field);
if (!strcmp(field->info->name, "bool")){ if (!strcmp(field->info->name, "bool")) {
assert(size == 1); assert(size == 1);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 1); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 1);
else if(!strcmp(field->info->name, "int8")){ } else if (!strcmp(field->info->name, "int8")) {
assert(size == 1); assert(size == 1);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 1); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 1);
else if(!strcmp(field->info->name, "int16")){ } else if (!strcmp(field->info->name, "int16")) {
assert(size == 2); assert(size == 2);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 2); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 2);
else if(!strcmp(field->info->name, "int32")){ } else if (!strcmp(field->info->name, "int32")) {
assert(size == 4); assert(size == 4);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 4); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 4);
else if(!strcmp(field->info->name, "int32 equal")){ } else if (!strcmp(field->info->name, "int32 equal")) {
assert(size == 4); assert(size == 4);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 4); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 4);
else if(!strcmp(field->info->name, "int32 le")){ } else if (!strcmp(field->info->name, "int32 le")) {
assert(size == 4); assert(size == 4);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 4); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 4);
else if(!strcmp(field->info->name, "int64")){ } else if (!strcmp(field->info->name, "int64")) {
assert(size == 8); assert(size == 8);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 8); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 8);
else if(!strcmp(field->info->name, "uint8")){ } else if (!strcmp(field->info->name, "uint8")) {
assert(size == 1); assert(size == 1);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 1); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 1);
else if(!strcmp(field->info->name, "uint16")){ } else if (!strcmp(field->info->name, "uint16")) {
assert(size == 2); assert(size == 2);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 2); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 2);
else if(!strcmp(field->info->name, "uint32")){ } else if (!strcmp(field->info->name, "uint32")) {
assert(size == 4); assert(size == 4);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 4); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 4);
else if(!strcmp(field->info->name, "uint32 equal")){ } else if (!strcmp(field->info->name, "uint32 equal")) {
assert(size == 4); assert(size == 4);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 4); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 4);
else if(!strcmp(field->info->name, "uint64")){ } else if (!strcmp(field->info->name, "uint64")) {
assert(size == 8); assert(size == 8);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 8); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 8);
else if(!strcmp(field->info->name, "int64 equal")){ } else if (!strcmp(field->info->name, "int64 equal")) {
assert(size == 8); assert(size == 8);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 8); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 8);
else if(!strcmp(field->info->name, "uint8 equal")){ } else if (!strcmp(field->info->name, "uint8 equal")) {
assert(size == 1); assert(size == 1);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 1); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 1);
else if(!strcmp(field->info->name, "uint16 equal")){ } else if (!strcmp(field->info->name, "uint16 equal")) {
assert(size == 16); assert(size == 16);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 2); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 2);
else if(!strcmp(field->info->name, "float64")){ } else if (!strcmp(field->info->name, "float64")) {
assert(size == 64); assert(size == 64);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 8); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 8);
else if(!strcmp(field->info->name, "CPU_Double_U")){ } else if (!strcmp(field->info->name, "CPU_Double_U")) {
assert(0); assert(0);
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, 8); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} 8);
else if(!strcmp(field->info->name, "buffer")){ } else if (!strcmp(field->info->name, "buffer")) {
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, size); add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
} size);
else if(!strcmp(field->info->name, "unused_buffer")){ } else if (!strcmp(field->info->name, "unused_buffer")) {
/* save nothing */ /* save nothing */
} } else if (!strcmp(field->info->name, "tmp")) {
else if(!strcmp(field->info->name, "tmp")){ add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem,
add_mblock(self, vmsd_name, field->name, field->offset, (uint64_t)curr_elem, size); size);
/* save nothing */ /* save nothing */
} } else if (!strcmp(field->info->name, "bitmap")) {
else if(!strcmp(field->info->name, "bitmap")){
assert(0); assert(0);
} } else if (!strcmp(field->info->name, "qtailq")) {
else if(!strcmp(field->info->name, "qtailq")){
assert(0); assert(0);
} } else if (!strcmp(field->info->name, "timer")) {
else if(!strcmp(field->info->name, "timer")){ add_get(self, (void *)field->info->get, curr_elem, size, (void *)field, f,
add_get(self, (void*) field->info->get, curr_elem, size, (void*) field, f, field->info->name); field->info->name);
} } else if (!strcmp(field->info->name, "fpreg")) {
else if(!strcmp(field->info->name, "fpreg")){
nyx_debug("type: %s (size: %lx)\n", field->info->name, size); nyx_debug("type: %s (size: %lx)\n", field->info->name, size);
assert(0); assert(0);
add_get(self, (void*) field->info->get, curr_elem, size, (void*) field, f, field->info->name); add_get(self, (void *)field->info->get, curr_elem, size, (void *)field, f,
} field->info->name);
else if(!strcmp(field->info->name, "pci config")){ } else if (!strcmp(field->info->name, "pci config")) {
add_get(self, (void*) field->info->get, curr_elem, size, (void*) field, f, field->info->name); add_get(self, (void *)field->info->get, curr_elem, size, (void *)field, f,
} field->info->name);
else if(!strcmp(field->info->name, "pci irq state")){ } else if (!strcmp(field->info->name, "pci irq state")) {
add_get(self, (void*) field->info->get, curr_elem, size, (void*) field, f, field->info->name); add_get(self, (void *)field->info->get, curr_elem, size, (void *)field, f,
} field->info->name);
else if(!strcmp(field->info->name, "virtio")){ } else if (!strcmp(field->info->name, "virtio")) {
add_get(self, (void*) field->info->get, curr_elem, size, (void*) field, f, field->info->name); add_get(self, (void *)field->info->get, curr_elem, size, (void *)field, f,
} field->info->name);
else{ } else {
fprintf(stderr, "[QEMU-PT] %s: WARNING no handler for %s, type %s, size %lx!\n", fprintf(stderr,
"[QEMU-PT] %s: WARNING no handler for %s, type %s, size %lx!\n",
__func__, vmsd_name, field->info->name, size); __func__, vmsd_name, field->info->name, size);
assert(0); assert(0);
} }
@ -511,7 +546,12 @@ static inline int get_handler(state_reallocation_t* self, QEMUFile* f, void* cur
} }
/* TODO: modify opaque_ptr */ /* TODO: modify opaque_ptr */
static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const VMStateDescription *vmsd, void *opaque, int version_id, uintptr_t* opaque_ptr) static int fdl_vmstate_load_state(state_reallocation_t *self,
QEMUFile *f,
const VMStateDescription *vmsd,
void *opaque,
int version_id,
uintptr_t *opaque_ptr)
{ {
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("---------------------------------\nVMSD: %p\t%s\n", opaque, vmsd->name); printf("---------------------------------\nVMSD: %p\t%s\n", opaque, vmsd->name);
@ -530,8 +570,7 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
printf("OLD LOAD\n"); printf("OLD LOAD\n");
#endif #endif
if (vmsd->load_state_old && if (vmsd->load_state_old && version_id >= vmsd->minimum_version_id_old) {
version_id >= vmsd->minimum_version_id_old) {
fprintf(stderr, "OLDSTATE\n"); fprintf(stderr, "OLDSTATE\n");
assert(0); assert(0);
ret = vmsd->load_state_old(f, opaque, version_id); ret = vmsd->load_state_old(f, opaque, version_id);
@ -544,18 +583,17 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
printf("\tPRELOAD Function\n"); printf("\tPRELOAD Function\n");
#endif #endif
/* TODO ADD PRE FPTR FOR SERIAL */ /* TODO ADD PRE FPTR FOR SERIAL */
//fprintf(stderr, "PRELOAD RUN: %s\n", vmsd->name); // fprintf(stderr, "PRELOAD RUN: %s\n", vmsd->name);
//add_pre_fptr(self, vmsd->pre_load, opaque, vmsd->name); // add_pre_fptr(self, vmsd->pre_load, opaque, vmsd->name);
add_post_fptr(self, vmsd->pre_load, 1337, opaque, vmsd->name); add_post_fptr(self, vmsd->pre_load, 1337, opaque, vmsd->name);
} }
while (field->name) { while (field->name) {
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("Field: %s %s %s\n", __func__, vmsd->name, field->name); printf("Field: %s %s %s\n", __func__, vmsd->name, field->name);
#endif #endif
if ((field->field_exists && if ((field->field_exists && field->field_exists(opaque, version_id)) ||
field->field_exists(opaque, version_id)) || (!field->field_exists && field->version_id <= version_id))
(!field->field_exists && {
field->version_id <= version_id)) {
void *first_elem = opaque + field->offset; void *first_elem = opaque + field->offset;
int i, n_elems = vmstate_n_elems(opaque, field); int i, n_elems = vmstate_n_elems(opaque, field);
int size = vmstate_size(opaque, field); int size = vmstate_size(opaque, field);
@ -563,7 +601,7 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("-----------------> vmstate_handle_alloc\n"); printf("-----------------> vmstate_handle_alloc\n");
#endif #endif
//fprintf(stderr, "-----------------> vmstate_handle_alloc\n"); // fprintf(stderr, "-----------------> vmstate_handle_alloc\n");
vmstate_handle_alloc(first_elem, field, opaque); vmstate_handle_alloc(first_elem, field, opaque);
if (field->flags & VMS_POINTER) { if (field->flags & VMS_POINTER) {
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
@ -576,22 +614,26 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
} }
for (i = 0; i < n_elems; i++) { for (i = 0; i < n_elems; i++) {
uint64_t* tmp_opaque_ptr = 0; uint64_t *tmp_opaque_ptr = 0;
total_size += size; total_size += size;
void *curr_elem = first_elem + size * i; void *curr_elem = first_elem + size * i;
if (field->flags & VMS_ARRAY_OF_POINTER) { if (field->flags & VMS_ARRAY_OF_POINTER) {
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("Field-Offset 1 0x%lx-0x%lx\n", (uint64_t)(field->offset + (opaque)), (uint64_t)(field->offset+(size*n_elems) + (opaque))); printf("Field-Offset 1 0x%lx-0x%lx\n",
printf("=VMS_ARRAY_OF_POINTER 1= %lx %x\n", *((uint64_t*)curr_elem), size); (uint64_t)(field->offset + (opaque)),
//hexDump((void*)field->name, curr_elem, size); (uint64_t)(field->offset + (size * n_elems) + (opaque)));
printf("=VMS_ARRAY_OF_POINTER 1= %lx %x\n",
*((uint64_t *)curr_elem), size);
// hexDump((void*)field->name, curr_elem, size);
#endif #endif
tmp_opaque_ptr = curr_elem; tmp_opaque_ptr = curr_elem;
curr_elem = *(void **)curr_elem; curr_elem = *(void **)curr_elem;
add_mblock(self, (char*)vmsd->name, (const char*)field->name, field->offset, (uint64_t)(curr_elem), (uint64_t)(size)); add_mblock(self, (char *)vmsd->name, (const char *)field->name,
field->offset, (uint64_t)(curr_elem), (uint64_t)(size));
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
//hexDump((void*)field->name, curr_elem, size); // hexDump((void*)field->name, curr_elem, size);
#endif #endif
} }
@ -599,34 +641,40 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
// if null pointer check placeholder and do not follow // if null pointer check placeholder and do not follow
assert(field->flags & VMS_ARRAY_OF_POINTER); assert(field->flags & VMS_ARRAY_OF_POINTER);
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("Field-Offset 2 0x%lx-0x%lx\n", (uint64_t)(field->offset + (opaque)), (uint64_t)(field->offset+(size*n_elems) + (opaque))); printf("Field-Offset 2 0x%lx-0x%lx\n",
printf("=VMS_ARRAY_OF_POINTER 2= %lx %x\n", *((uint64_t*)curr_elem), size); (uint64_t)(field->offset + (opaque)),
//hexDump((void*)field->name, curr_elem, size); (uint64_t)(field->offset + (size * n_elems) + (opaque)));
printf("=VMS_ARRAY_OF_POINTER 2= %lx %x\n",
*((uint64_t *)curr_elem), size);
// hexDump((void*)field->name, curr_elem, size);
#endif #endif
nyx_debug("*** vmstate_info_nullptr.get ***\n"); nyx_debug("*** vmstate_info_nullptr.get ***\n");
ret = vmstate_info_nullptr.get(f, curr_elem, size, NULL); ret = vmstate_info_nullptr.get(f, curr_elem, size, NULL);
add_mblock(self, (char*)vmsd->name, (const char*)field->name, field->offset, (uint64_t)(curr_elem), (uint64_t)(size)); add_mblock(self, (char *)vmsd->name, (const char *)field->name,
field->offset, (uint64_t)(curr_elem), (uint64_t)(size));
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
//hexDump((void*)field->name, curr_elem, size); // hexDump((void*)field->name, curr_elem, size);
#endif #endif
} else if (field->flags & VMS_STRUCT) { } else if (field->flags & VMS_STRUCT) {
//printf("Field-Offset 0x%lx-0x%lx\n", field->offset + (opaque-base_opaque), field->offset+(size*n_elems) + (opaque-base_opaque)); // printf("Field-Offset 0x%lx-0x%lx\n", field->offset + (opaque-base_opaque),
// field->offset+(size*n_elems) + (opaque-base_opaque));
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
printf("=VMS_STRUCT= %lx %x\n", *((uint64_t*)curr_elem), size); printf("=VMS_STRUCT= %lx %x\n", *((uint64_t *)curr_elem), size);
//hexDump((void*)field->name, curr_elem, size); // hexDump((void*)field->name, curr_elem, size);
#endif #endif
/* FIXME */ /* FIXME */
ret = fdl_vmstate_load_state(self, f, field->vmsd, curr_elem, field->vmsd->version_id, tmp_opaque_ptr); ret = fdl_vmstate_load_state(self, f, field->vmsd, curr_elem,
field->vmsd->version_id,
tmp_opaque_ptr);
#ifdef VERBOSE_DEBUG #ifdef VERBOSE_DEBUG
//hexDump((void*)field->name, curr_elem, size); // hexDump((void*)field->name, curr_elem, size);
#endif #endif
} else { } else {
ret = get_handler(self, f, curr_elem, size, field,
(char *)vmsd->name);
ret = get_handler(self, f, curr_elem, size, field, (char*)vmsd->name);
} }
if (ret >= 0) { if (ret >= 0) {
ret = qemu_file_get_error(f); ret = qemu_file_get_error(f);
@ -639,9 +687,8 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
} else if (field->flags & VMS_MUST_EXIST) { } else if (field->flags & VMS_MUST_EXIST) {
nyx_debug("Input validation failed: %s/%s", vmsd->name, field->name); nyx_debug("Input validation failed: %s/%s", vmsd->name, field->name);
return -1; return -1;
} } else {
else { // printf("Field does not exist...\n");
//printf("Field does not exist...\n");
} }
field++; field++;
} }
@ -667,17 +714,24 @@ static int fdl_vmstate_load_state(state_reallocation_t* self, QEMUFile *f, const
} }
static int fdl_vmstate_load(state_reallocation_t* self, QEMUFile *f, SaveStateEntry *se, int version_id) static int fdl_vmstate_load(state_reallocation_t *self,
QEMUFile *f,
SaveStateEntry *se,
int version_id)
{ {
if (!se->vmsd) { /* Old style */ if (!se->vmsd) { /* Old style */
return se->ops->load_state(f, se->opaque, version_id); return se->ops->load_state(f, se->opaque, version_id);
} }
uintptr_t *t = (uintptr_t *)&(se->opaque); uintptr_t *t = (uintptr_t *)&(se->opaque);
return fdl_vmstate_load_state(self, f, se->vmsd, se->opaque, version_id, (uintptr_t *)t); return fdl_vmstate_load_state(self, f, se->vmsd, se->opaque, version_id,
(uintptr_t *)t);
} }
static int fdl_enumerate_section(state_reallocation_t* self, QEMUFile *f, MigrationIncomingState *mis){ static int fdl_enumerate_section(state_reallocation_t *self,
QEMUFile *f,
MigrationIncomingState *mis)
{
uint32_t instance_id, version_id, section_id; uint32_t instance_id, version_id, section_id;
SaveStateEntry *se; SaveStateEntry *se;
@ -702,14 +756,16 @@ static int fdl_enumerate_section(state_reallocation_t* self, QEMUFile *f, Migrat
/* Validate version */ /* Validate version */
if (version_id > se->version_id) { if (version_id > se->version_id) {
printf("savevm: unsupported version %d for '%s' v%d", version_id, idstr, se->version_id); printf("savevm: unsupported version %d for '%s' v%d", version_id, idstr,
se->version_id);
return -EINVAL; return -EINVAL;
} }
se->load_version_id = version_id; se->load_version_id = version_id;
se->load_section_id = section_id; se->load_section_id = section_id;
if(se->vmsd && ((strcmp("tiMer", (const char*)(VMStateDescription *)(se->vmsd)->name)) if (se->vmsd &&
((strcmp("tiMer", (const char *)(VMStateDescription *)(se->vmsd)->name))
/* /*
&& (strcmp("cpu_common", (VMStateDescription *)(se->vmsd)->name)) && (strcmp("cpu_common", (VMStateDescription *)(se->vmsd)->name))
&& (strcmp("cpu", (VMStateDescription *)(se->vmsd)->name)) && (strcmp("cpu", (VMStateDescription *)(se->vmsd)->name))
@ -751,16 +807,17 @@ static int fdl_enumerate_section(state_reallocation_t* self, QEMUFile *f, Migrat
*/ */
)){ ))
{
ret = fdl_vmstate_load(self, f, se, version_id); ret = fdl_vmstate_load(self, f, se, version_id);
} } else {
else{ nyx_debug("---------------------------------\nVMSD2: %p\n", (void *)se->vmsd);
nyx_debug("---------------------------------\nVMSD2: %p\n", (void*)se->vmsd);
ret = vmstate_load(f, se); ret = vmstate_load(f, se);
} }
if (ret < 0) { if (ret < 0) {
printf("error while loading state for instance 0x%x of device '%s'", instance_id, idstr); printf("error while loading state for instance 0x%x of device '%s'",
instance_id, idstr);
return ret; return ret;
} }
@ -770,10 +827,11 @@ static int fdl_enumerate_section(state_reallocation_t* self, QEMUFile *f, Migrat
return 0; return 0;
} }
static void fdl_enumerate_global_states(state_reallocation_t* self, QEMUFile *f){ static void fdl_enumerate_global_states(state_reallocation_t *self, QEMUFile *f)
((struct QEMUFile_tmp*)f)->pos = 0; {
((struct QEMUFile_tmp*)f)->buf_index = 0; ((struct QEMUFile_tmp *)f)->pos = 0;
((struct QEMUFile_tmp*)f)->buf_size = 0; ((struct QEMUFile_tmp *)f)->buf_index = 0;
((struct QEMUFile_tmp *)f)->buf_size = 0;
uint8_t section_type; uint8_t section_type;
@ -784,7 +842,8 @@ static void fdl_enumerate_global_states(state_reallocation_t* self, QEMUFile *f)
qemu_get_byte(f); qemu_get_byte(f);
/* migration state */ /* migration state */
vmstate_load_state(f, (VMStateDescription*) &vmstate_configuration, (void*)&savevm_state, 0); vmstate_load_state(f, (VMStateDescription *)&vmstate_configuration,
(void *)&savevm_state, 0);
while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) { while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {
switch (section_type) { switch (section_type) {
@ -795,37 +854,40 @@ static void fdl_enumerate_global_states(state_reallocation_t* self, QEMUFile *f)
default: default:
/* oops */ /* oops */
nyx_error("==> ERROR: unkown section_type: %x\n", section_type); nyx_error("==> ERROR: unkown section_type: %x\n", section_type);
//abort(); // abort();
break; break;
} }
} }
} }
state_reallocation_t* state_reallocation_new(QEMUFile *f){ state_reallocation_t *state_reallocation_new(QEMUFile *f)
state_reallocation_t* self = malloc(sizeof(state_reallocation_t)); {
state_reallocation_t *self = malloc(sizeof(state_reallocation_t));
self->fast_state_pos = 0; self->fast_state_pos = 0;
self->fast_state_size = REALLOC_SIZE; self->fast_state_size = REALLOC_SIZE;
self->ptr = malloc(sizeof(void*) * REALLOC_SIZE); self->ptr = malloc(sizeof(void *) * REALLOC_SIZE);
self->copy = malloc(sizeof(void*) * REALLOC_SIZE); self->copy = malloc(sizeof(void *) * REALLOC_SIZE);
self->size = malloc(sizeof(size_t) * REALLOC_SIZE); self->size = malloc(sizeof(size_t) * REALLOC_SIZE);
self->fast_state_fptr_pos = 0; self->fast_state_fptr_pos = 0;
self->fast_state_fptr_size = REALLOC_SIZE; self->fast_state_fptr_size = REALLOC_SIZE;
self->fptr = malloc(sizeof(void*) * REALLOC_SIZE); self->fptr = malloc(sizeof(void *) * REALLOC_SIZE);
self->opaque = malloc(sizeof(void*) * REALLOC_SIZE); self->opaque = malloc(sizeof(void *) * REALLOC_SIZE);
self->version = malloc(sizeof(uint32_t) * REALLOC_SIZE); self->version = malloc(sizeof(uint32_t) * REALLOC_SIZE);
self->fast_state_get_fptr_pos = 0; self->fast_state_get_fptr_pos = 0;
self->fast_state_get_fptr_size = REALLOC_SIZE; self->fast_state_get_fptr_size = REALLOC_SIZE;
self->get_fptr = malloc(sizeof(void*) * REALLOC_SIZE); self->get_fptr = malloc(sizeof(void *) * REALLOC_SIZE);
self->get_opaque = malloc(sizeof(void*) * REALLOC_SIZE); self->get_opaque = malloc(sizeof(void *) * REALLOC_SIZE);
self->get_size = malloc(sizeof(size_t) * REALLOC_SIZE); self->get_size = malloc(sizeof(size_t) * REALLOC_SIZE);
self->get_data = malloc(sizeof(void*) * REALLOC_SIZE); self->get_data = malloc(sizeof(void *) * REALLOC_SIZE);
self->pre_alloc_block = (uint32_t*)mmap(NULL, PRE_ALLOC_BLOCK_SIZE, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); self->pre_alloc_block = (uint32_t *)mmap(NULL, PRE_ALLOC_BLOCK_SIZE,
assert(self->pre_alloc_block != (void *) -1); PROT_READ | PROT_WRITE,
MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
assert(self->pre_alloc_block != (void *)-1);
self->pre_alloc_block_offset = 0; self->pre_alloc_block_offset = 0;
self->tmp_snapshot.enabled = false; self->tmp_snapshot.enabled = false;
@ -834,70 +896,72 @@ state_reallocation_t* state_reallocation_new(QEMUFile *f){
// actually enumerate the devices here // actually enumerate the devices here
fdl_enumerate_global_states(self, f); fdl_enumerate_global_states(self, f);
self->tmp_snapshot.copy = malloc(sizeof(void*) * self->fast_state_pos); self->tmp_snapshot.copy = malloc(sizeof(void *) * self->fast_state_pos);
self->tmp_snapshot.fast_state_size = self->fast_state_pos; self->tmp_snapshot.fast_state_size = self->fast_state_pos;
for(uint32_t i = 0; i < self->fast_state_pos; i++){ for (uint32_t i = 0; i < self->fast_state_pos; i++) {
self->tmp_snapshot.copy[i] = malloc(self->size[i]); self->tmp_snapshot.copy[i] = malloc(self->size[i]);
} }
return self; return self;
} }
void fdl_fast_reload(state_reallocation_t* self){ void fdl_fast_reload(state_reallocation_t *self)
{
for(uint32_t i = 0; i < self->fast_state_fptr_pos; i++){ for (uint32_t i = 0; i < self->fast_state_fptr_pos; i++) {
if((self->version[i]) == 1337){ if ((self->version[i]) == 1337) {
((int (*)(void *opaque))self->fptr[i])(self->opaque[i]); ((int (*)(void *opaque))self->fptr[i])(self->opaque[i]);
} }
} }
if(!self->tmp_snapshot.enabled){ if (!self->tmp_snapshot.enabled) {
for(uint32_t i = 0; i < self->fast_state_pos; i++){ for (uint32_t i = 0; i < self->fast_state_pos; i++) {
memcpy(self->ptr[i], self->copy[i], self->size[i]); memcpy(self->ptr[i], self->copy[i], self->size[i]);
} }
} } else {
else{ for (uint32_t i = 0; i < self->fast_state_pos; i++) {
for(uint32_t i = 0; i < self->fast_state_pos; i++){
memcpy(self->ptr[i], self->tmp_snapshot.copy[i], self->size[i]); memcpy(self->ptr[i], self->tmp_snapshot.copy[i], self->size[i]);
} }
} }
for(uint32_t i = 0; i < self->fast_state_fptr_pos; i++){ for (uint32_t i = 0; i < self->fast_state_fptr_pos; i++) {
if((self->version[i]) != 1337){ if ((self->version[i]) != 1337) {
((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i], self->version[i]); ((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i],
self->version[i]);
} }
} }
} }
void fdl_fast_create_tmp(state_reallocation_t* self){ void fdl_fast_create_tmp(state_reallocation_t *self)
for(uint32_t i = 0; i < self->fast_state_fptr_pos; i++){ {
if((self->version[i]) == 1337){ for (uint32_t i = 0; i < self->fast_state_fptr_pos; i++) {
if ((self->version[i]) == 1337) {
((int (*)(void *opaque))self->fptr[i])(self->opaque[i]); ((int (*)(void *opaque))self->fptr[i])(self->opaque[i]);
} } else {
else{
//((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i], self->version[i]); //((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i], self->version[i]);
} }
} }
for(uint32_t i = 0; i < self->fast_state_pos; i++){ for (uint32_t i = 0; i < self->fast_state_pos; i++) {
memcpy(self->tmp_snapshot.copy[i], self->ptr[i], self->size[i]); memcpy(self->tmp_snapshot.copy[i], self->ptr[i], self->size[i]);
} }
for(uint32_t i = 0; i < self->fast_state_fptr_pos; i++){ for (uint32_t i = 0; i < self->fast_state_fptr_pos; i++) {
if((self->version[i]) == 1337){ if ((self->version[i]) == 1337) {
//((int (*)(void *opaque))self->fptr[i])(self->opaque[i]); //((int (*)(void *opaque))self->fptr[i])(self->opaque[i]);
} } else {
else{ ((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i],
((int (*)(void *opaque, int version_id))self->fptr[i])(self->opaque[i], self->version[i]); self->version[i]);
} }
} }
} }
void fdl_fast_enable_tmp(state_reallocation_t* self){ void fdl_fast_enable_tmp(state_reallocation_t *self)
{
self->tmp_snapshot.enabled = true; self->tmp_snapshot.enabled = true;
} }
void fdl_fast_disable_tmp(state_reallocation_t* self){ void fdl_fast_disable_tmp(state_reallocation_t *self)
{
self->tmp_snapshot.enabled = false; self->tmp_snapshot.enabled = false;
} }

View File

@ -21,8 +21,8 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#pragma once #pragma once
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "monitor/monitor.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "monitor/monitor.h"
#include "nyx/khash.h" #include "nyx/khash.h"
#define IO_BUF_SIZE 32768 #define IO_BUF_SIZE 32768
@ -41,26 +41,26 @@ struct QEMUFile_tmp {
uint8_t buf[IO_BUF_SIZE]; uint8_t buf[IO_BUF_SIZE];
}; };
struct fast_savevm_opaque_t{ struct fast_savevm_opaque_t {
FILE* f; FILE *f;
uint8_t* buf; uint8_t *buf;
size_t buflen; size_t buflen;
uint64_t pos; uint64_t pos;
void* output_buffer; void *output_buffer;
uint32_t* output_buffer_size; uint32_t *output_buffer_size;
}; };
#define REALLOC_SIZE 0x8000 #define REALLOC_SIZE 0x8000
#define PRE_ALLOC_BLOCK_SIZE 0x8000000 /* 128 MB */ #define PRE_ALLOC_BLOCK_SIZE 0x8000000 /* 128 MB */
typedef struct state_reallocation_tmp_s{ typedef struct state_reallocation_tmp_s {
void **copy; void **copy;
uint32_t fast_state_size; uint32_t fast_state_size;
bool enabled; bool enabled;
} state_reallocation_tmp_t; } state_reallocation_tmp_t;
typedef struct state_reallocation_s{ typedef struct state_reallocation_s {
void **ptr; void **ptr;
void **copy; void **copy;
size_t *size; size_t *size;
@ -86,17 +86,17 @@ typedef struct state_reallocation_s{
uint32_t fast_state_get_fptr_pos; uint32_t fast_state_get_fptr_pos;
/* prevents heap fragmentation and additional 2GB mem usage */ /* prevents heap fragmentation and additional 2GB mem usage */
void* pre_alloc_block; void *pre_alloc_block;
uint32_t pre_alloc_block_offset; uint32_t pre_alloc_block_offset;
state_reallocation_tmp_t tmp_snapshot; state_reallocation_tmp_t tmp_snapshot;
} state_reallocation_t; } state_reallocation_t;
state_reallocation_t* state_reallocation_new(QEMUFile *f); state_reallocation_t *state_reallocation_new(QEMUFile *f);
void fdl_fast_reload(state_reallocation_t* self); void fdl_fast_reload(state_reallocation_t *self);
void fdl_fast_create_tmp(state_reallocation_t* self); void fdl_fast_create_tmp(state_reallocation_t *self);
void fdl_fast_enable_tmp(state_reallocation_t* self); void fdl_fast_enable_tmp(state_reallocation_t *self);
void fdl_fast_disable_tmp(state_reallocation_t* self); void fdl_fast_disable_tmp(state_reallocation_t *self);

View File

@ -1,23 +1,24 @@
#include <assert.h>
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "nyx/snapshot/devices/vm_change_state_handlers.h" #include "nyx/snapshot/devices/vm_change_state_handlers.h"
#include <assert.h>
VMChangeStateHandler* change_kvm_clock_handler = NULL; VMChangeStateHandler *change_kvm_clock_handler = NULL;
VMChangeStateHandler* change_kvm_pit_handler = NULL; VMChangeStateHandler *change_kvm_pit_handler = NULL;
VMChangeStateHandler* change_cpu_handler = NULL; VMChangeStateHandler *change_cpu_handler = NULL;
void* change_kvm_clock_opaque = NULL; void *change_kvm_clock_opaque = NULL;
void* change_kvm_pit_opaque = NULL; void *change_kvm_pit_opaque = NULL;
void* change_cpu_opaque = NULL; void *change_cpu_opaque = NULL;
VMChangeStateHandler* change_ide_core_handler = NULL; VMChangeStateHandler *change_ide_core_handler = NULL;
uint8_t change_ide_core_opaque_num = 0; uint8_t change_ide_core_opaque_num = 0;
void* change_ide_core_opaque[32] = {NULL}; void *change_ide_core_opaque[32] = { NULL };
void call_fast_change_handlers(void){ void call_fast_change_handlers(void)
{
assert(change_kvm_clock_handler && change_kvm_pit_handler && change_cpu_handler); assert(change_kvm_clock_handler && change_kvm_pit_handler && change_cpu_handler);
change_kvm_clock_handler(change_kvm_clock_opaque, 1, RUN_STATE_RUNNING); change_kvm_clock_handler(change_kvm_clock_opaque, 1, RUN_STATE_RUNNING);
@ -27,15 +28,16 @@ void call_fast_change_handlers(void){
return; return;
/* TODO: check if necessary */ /* TODO: check if necessary */
if(change_ide_core_handler){ if (change_ide_core_handler) {
for(uint8_t i = 0; i < change_ide_core_opaque_num; i++){ for (uint8_t i = 0; i < change_ide_core_opaque_num; i++) {
change_ide_core_handler(change_ide_core_opaque[i], 1, RUN_STATE_RUNNING); change_ide_core_handler(change_ide_core_opaque[i], 1, RUN_STATE_RUNNING);
} }
} }
} }
void add_fast_reload_change_handler(VMChangeStateHandler *cb, void *opaque, int id){ void add_fast_reload_change_handler(VMChangeStateHandler *cb, void *opaque, int id)
switch(id){ {
switch (id) {
case RELOAD_HANDLER_KVM_CLOCK: case RELOAD_HANDLER_KVM_CLOCK:
change_kvm_clock_handler = cb; change_kvm_clock_handler = cb;
change_kvm_clock_opaque = opaque; change_kvm_clock_opaque = opaque;

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include <stdlib.h>
#include <stdint.h>
#include "sysemu/runstate.h" #include "sysemu/runstate.h"
#include <stdint.h>
#include <stdlib.h>
#define RELOAD_HANDLER_KVM_CLOCK 0 #define RELOAD_HANDLER_KVM_CLOCK 0
#define RELOAD_HANDLER_KVM_PIT 1 #define RELOAD_HANDLER_KVM_PIT 1

View File

@ -1,24 +1,25 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "sysemu/cpus.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/cpus.h"
#include "sysemu/sysemu.h"
#include "qemu/bitmap.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qemu/bitmap.h"
#include "qemu/rcu_queue.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/snapshot/helper.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/snapshot/helper.h"
//#define DEBUG_NYX_SNAPSHOT_HELPER // #define DEBUG_NYX_SNAPSHOT_HELPER
uint64_t get_ram_size(void){ uint64_t get_ram_size(void)
{
RAMBlock *block; RAMBlock *block;
uint64_t guest_ram_size = 0; uint64_t guest_ram_size = 0;
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
guest_ram_size += block->used_length; guest_ram_size += block->used_length;
#ifdef DEBUG_NYX_SNAPSHOT_HELPER #ifdef DEBUG_NYX_SNAPSHOT_HELPER
printf("Block: %s (%lx)\n", block->idstr, block->used_length); printf("Block: %s (%lx)\n", block->idstr, block->used_length);

View File

@ -6,8 +6,8 @@
#define PAGE_SIZE qemu_real_host_page_size #define PAGE_SIZE qemu_real_host_page_size
#endif #endif
#define BITMAP_SIZE(x) ((x/PAGE_SIZE)/8) #define BITMAP_SIZE(x) ((x / PAGE_SIZE) / 8)
#define DIRTY_STACK_SIZE(x) ((x/PAGE_SIZE)*sizeof(uint64_t)) #define DIRTY_STACK_SIZE(x) ((x / PAGE_SIZE) * sizeof(uint64_t))
uint64_t get_ram_size(void); uint64_t get_ram_size(void);

View File

@ -1,61 +1,72 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qemu/rcu_queue.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/snapshot/memory/backend/nyx_debug.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/snapshot/memory/backend/nyx_debug.h"
/* init operation */ /* init operation */
void nyx_snapshot_debug_pre_init(void){ void nyx_snapshot_debug_pre_init(void)
{
/* TODO */ /* TODO */
} }
/* init operation */ /* init operation */
void nyx_snapshot_debug_init(fast_reload_t* self){ void nyx_snapshot_debug_init(fast_reload_t *self)
{
/* TODO */ /* TODO */
} }
/* enable operation */ /* enable operation */
void nyx_snapshot_debug_enable(fast_reload_t* self){ void nyx_snapshot_debug_enable(fast_reload_t *self)
{
/* TODO */ /* TODO */
} }
/* restore operation */ /* restore operation */
uint32_t nyx_snapshot_debug_restore(shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, bool verbose){ uint32_t nyx_snapshot_debug_restore(shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist,
bool verbose)
{
uint32_t num_dirty_pages = 0; uint32_t num_dirty_pages = 0;
void* current_region = NULL; void *current_region = NULL;
int counter = 0; int counter = 0;
for(uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++){ for (uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++) {
if (shadow_memory_state->incremental_enabled) {
if(shadow_memory_state->incremental_enabled){ current_region =
current_region = shadow_memory_state->ram_regions[i].incremental_region_ptr; shadow_memory_state->ram_regions[i].incremental_region_ptr;
} } else {
else{
current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr; current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr;
} }
for(uint64_t addr = 0; addr < shadow_memory_state->ram_regions[i].size; addr+=0x1000){ for (uint64_t addr = 0; addr < shadow_memory_state->ram_regions[i].size;
addr += 0x1000)
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + addr; {
void* snapshot_addr = current_region + addr; void *host_addr =
shadow_memory_state->ram_regions[i].host_region_ptr + addr;
void *snapshot_addr = current_region + addr;
uint64_t physical_addr = addr + shadow_memory_state->ram_regions[i].base; uint64_t physical_addr = addr + shadow_memory_state->ram_regions[i].base;
/* check first if the page is dirty (this is super slow, but quite useful for debugging) */ /* check first if the page is dirty (this is super slow, but quite useful for debugging) */
if(memcmp(host_addr, snapshot_addr, TARGET_PAGE_SIZE)){ if (memcmp(host_addr, snapshot_addr, TARGET_PAGE_SIZE)) {
/* check if page is not on the block list */ /* check if page is not on the block list */
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == false){ if (snapshot_page_blocklist_check_phys_addr(blocklist,
//fprintf(stderr, "(2) DIRTY: 0x%lx (NUM: %d - OFFSET: 0x%lx)\n", physical_addr, i, addr); physical_addr) == false)
{
// fprintf(stderr, "(2) DIRTY: 0x%lx (NUM: %d - OFFSET: 0x%lx)\n", physical_addr, i, addr);
if(verbose){ if (verbose) {
printf("%s -> (phys: 0x%lx) %p <-- %p [%d]\n", __func__, physical_addr, host_addr, snapshot_addr, shadow_memory_state->incremental_enabled); printf("%s -> (phys: 0x%lx) %p <-- %p [%d]\n", __func__,
physical_addr, host_addr, snapshot_addr,
shadow_memory_state->incremental_enabled);
counter++; counter++;
} }
@ -66,39 +77,51 @@ uint32_t nyx_snapshot_debug_restore(shadow_memory_t* shadow_memory_state, snapsh
} }
} }
if(verbose){ if (verbose) {
printf("TOTAL: %d\n", counter); printf("TOTAL: %d\n", counter);
} }
return num_dirty_pages; return num_dirty_pages;
} }
void nyx_snapshot_debug_save_root_pages(shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, bool verbose){ void nyx_snapshot_debug_save_root_pages(shadow_memory_t *shadow_memory_state,
void* current_region = NULL; snapshot_page_blocklist_t *blocklist,
bool verbose)
{
void *current_region = NULL;
for(uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++){ for (uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++) {
if (shadow_memory_state->incremental_enabled) {
if(shadow_memory_state->incremental_enabled){ current_region =
current_region = shadow_memory_state->ram_regions[i].incremental_region_ptr; shadow_memory_state->ram_regions[i].incremental_region_ptr;
} } else {
else{
current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr; current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr;
} }
for(uint64_t addr = 0; addr < shadow_memory_state->ram_regions[i].size; addr+=0x1000){ for (uint64_t addr = 0; addr < shadow_memory_state->ram_regions[i].size;
addr += 0x1000)
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + addr; {
void* snapshot_addr = current_region + addr; void *host_addr =
shadow_memory_state->ram_regions[i].host_region_ptr + addr;
void *snapshot_addr = current_region + addr;
uint64_t physical_addr = addr + shadow_memory_state->ram_regions[i].base; uint64_t physical_addr = addr + shadow_memory_state->ram_regions[i].base;
void* incremental_addr = shadow_memory_state->ram_regions[i].incremental_region_ptr + addr; void *incremental_addr =
shadow_memory_state->ram_regions[i].incremental_region_ptr + addr;
/* check first if the page is dirty (this is super slow, but quite useful for debugging) */ /* check first if the page is dirty (this is super slow, but quite useful for debugging) */
if(memcmp(host_addr, snapshot_addr, TARGET_PAGE_SIZE)){ if (memcmp(host_addr, snapshot_addr, TARGET_PAGE_SIZE)) {
/* check if page is not on the block list */ /* check if page is not on the block list */
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == false){ if (snapshot_page_blocklist_check_phys_addr(blocklist,
//fprintf(stderr, "(2) DIRTY: 0x%lx (NUM: %d - OFFSET: 0x%lx)\n", physical_addr, i, addr); physical_addr) == false)
{
// fprintf(stderr, "(2) DIRTY: 0x%lx (NUM: %d - OFFSET: 0x%lx)\n", physical_addr, i, addr);
if(verbose && !shadow_memory_is_root_page_tracked(shadow_memory_state, addr, i)){ if (verbose &&
printf("%s -> %p <-- %p [%d]\n", __func__, host_addr, snapshot_addr, shadow_memory_state->incremental_enabled); !shadow_memory_is_root_page_tracked(shadow_memory_state,
addr, i))
{
printf("%s -> %p <-- %p [%d]\n", __func__, host_addr,
snapshot_addr,
shadow_memory_state->incremental_enabled);
} }
shadow_memory_track_dirty_root_pages(shadow_memory_state, addr, i); shadow_memory_track_dirty_root_pages(shadow_memory_state, addr, i);
@ -110,6 +133,7 @@ void nyx_snapshot_debug_save_root_pages(shadow_memory_t* shadow_memory_state, sn
} }
/* set operation */ /* set operation */
void nyx_snapshot_debug_set(fast_reload_t* self){ void nyx_snapshot_debug_set(fast_reload_t *self)
{
/* TODO */ /* TODO */
} }

View File

@ -1,11 +1,15 @@
#pragma once #pragma once
#include <stdint.h>
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include <stdint.h>
void nyx_snapshot_debug_pre_init(void); void nyx_snapshot_debug_pre_init(void);
void nyx_snapshot_debug_init(fast_reload_t* self); void nyx_snapshot_debug_init(fast_reload_t *self);
void nyx_snapshot_debug_enable(fast_reload_t* self); void nyx_snapshot_debug_enable(fast_reload_t *self);
uint32_t nyx_snapshot_debug_restore(shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, bool verbose); uint32_t nyx_snapshot_debug_restore(shadow_memory_t *shadow_memory_state,
void nyx_snapshot_debug_set(fast_reload_t* self); snapshot_page_blocklist_t *blocklist,
void nyx_snapshot_debug_save_root_pages(shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, bool verbose); bool verbose);
void nyx_snapshot_debug_set(fast_reload_t *self);
void nyx_snapshot_debug_save_root_pages(shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist,
bool verbose);

View File

@ -2,8 +2,8 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include "nyx/snapshot/memory/backend/nyx_dirty_ring.h"
#include "nyx/snapshot/helper.h" #include "nyx/snapshot/helper.h"
#include "nyx/snapshot/memory/backend/nyx_dirty_ring.h"
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
#include "sysemu/kvm_int.h" #include "sysemu/kvm_int.h"
@ -26,36 +26,42 @@ uint32_t kvm_dirty_gfns_index = 0;
uint32_t kvm_dirty_gfns_index_mask = 0; uint32_t kvm_dirty_gfns_index_mask = 0;
static int vm_enable_dirty_ring(int vm_fd, uint32_t ring_size){ static int vm_enable_dirty_ring(int vm_fd, uint32_t ring_size)
{
struct kvm_enable_cap cap = { 0 }; struct kvm_enable_cap cap = { 0 };
cap.cap = KVM_CAP_DIRTY_LOG_RING; cap.cap = KVM_CAP_DIRTY_LOG_RING;
cap.args[0] = ring_size; cap.args[0] = ring_size;
int ret = ioctl(vm_fd, KVM_ENABLE_CAP, &cap); int ret = ioctl(vm_fd, KVM_ENABLE_CAP, &cap);
if(ret != 0){ if (ret != 0) {
printf("[QEMU-Nyx] Error: KVM_ENABLE_CAP ioctl failed\n"); printf("[QEMU-Nyx] Error: KVM_ENABLE_CAP ioctl failed\n");
} }
return ring_size; return ring_size;
} }
static int check_dirty_ring_size(int kvm_fd, int vm_fd){ static int check_dirty_ring_size(int kvm_fd, int vm_fd)
{
int ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING); int ret = ioctl(kvm_fd, KVM_CHECK_EXTENSION, KVM_CAP_DIRTY_LOG_RING);
if(ret < 0 ){ if (ret < 0) {
printf("[QEMU-Nyx] Error: KVM_CAP_DIRTY_LOG_RING failed (dirty ring not supported?)\n"); printf("[QEMU-Nyx] Error: KVM_CAP_DIRTY_LOG_RING failed (dirty ring not "
"supported?)\n");
exit(1); exit(1);
} }
printf("[QEMU-Nyx] Max Dirty Ring Size -> %d (Entries: %d)\n", ret, ret/(int)sizeof(struct kvm_dirty_gfn)); printf("[QEMU-Nyx] Max Dirty Ring Size -> %d (Entries: %d)\n", ret,
ret / (int)sizeof(struct kvm_dirty_gfn));
uint64_t dirty_ring_max_size = ret; //kvm_dirty_ring_size * sizeof(struct kvm_dirty_gfn); uint64_t dirty_ring_max_size =
ret; // kvm_dirty_ring_size * sizeof(struct kvm_dirty_gfn);
/* DIRTY RING -> 1MB in size results in 256M trackable memory */ /* DIRTY RING -> 1MB in size results in 256M trackable memory */
ret = vm_enable_dirty_ring(vm_fd, dirty_ring_max_size); ret = vm_enable_dirty_ring(vm_fd, dirty_ring_max_size);
if(ret < 0 ){ if (ret < 0) {
printf("[QEMU-Nyx] Error: Enabling dirty ring (size: %ld) failed\n", dirty_ring_max_size); printf("[QEMU-Nyx] Error: Enabling dirty ring (size: %ld) failed\n",
dirty_ring_max_size);
exit(1); exit(1);
} }
@ -63,11 +69,14 @@ static int check_dirty_ring_size(int kvm_fd, int vm_fd){
return ret; return ret;
} }
static void allocate_dirty_ring(int kvm_vcpu, int vm_fd){ static void allocate_dirty_ring(int kvm_vcpu, int vm_fd)
{
assert(dirty_ring_size); assert(dirty_ring_size);
if (dirty_ring_size) { if (dirty_ring_size) {
kvm_dirty_gfns = mmap(NULL, dirty_ring_size, PROT_READ | PROT_WRITE, MAP_SHARED, kvm_vcpu, PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET); kvm_dirty_gfns = mmap(NULL, dirty_ring_size, PROT_READ | PROT_WRITE,
MAP_SHARED, kvm_vcpu,
PAGE_SIZE * KVM_DIRTY_LOG_PAGE_OFFSET);
if (kvm_dirty_gfns == MAP_FAILED) { if (kvm_dirty_gfns == MAP_FAILED) {
printf("[QEMU-Nyx] Error: Dirty ring mmap failed!\n"); printf("[QEMU-Nyx] Error: Dirty ring mmap failed!\n");
exit(1); exit(1);
@ -80,51 +89,61 @@ static void allocate_dirty_ring(int kvm_vcpu, int vm_fd){
} }
/* pre_init operation */ /* pre_init operation */
void nyx_dirty_ring_early_init(int kvm_fd, int vm_fd){ void nyx_dirty_ring_early_init(int kvm_fd, int vm_fd)
{
dirty_ring_size = check_dirty_ring_size(kvm_fd, vm_fd); dirty_ring_size = check_dirty_ring_size(kvm_fd, vm_fd);
} }
void nyx_dirty_ring_pre_init(int kvm_fd, int vm_fd){ void nyx_dirty_ring_pre_init(int kvm_fd, int vm_fd)
{
allocate_dirty_ring(kvm_fd, vm_fd); allocate_dirty_ring(kvm_fd, vm_fd);
kvm_dirty_gfns_index = 0; kvm_dirty_gfns_index = 0;
kvm_dirty_gfns_index_mask = ((dirty_ring_max_size_global/sizeof(struct kvm_dirty_gfn)) - 1); kvm_dirty_gfns_index_mask =
((dirty_ring_max_size_global / sizeof(struct kvm_dirty_gfn)) - 1);
} }
static inline void dirty_ring_collect(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, uint64_t slot, uint64_t gfn){ static inline void dirty_ring_collect(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist,
uint64_t slot,
uint64_t gfn)
{
/* sanity check */ /* sanity check */
assert((slot&0xFFFF0000) == 0); assert((slot & 0xFFFF0000) == 0);
slot_t* kvm_region_slot = &self->kvm_region_slots[slot&0xFFFF]; slot_t *kvm_region_slot = &self->kvm_region_slots[slot & 0xFFFF];
if(test_and_set_bit(gfn, (void*)kvm_region_slot->bitmap) == false){
if (test_and_set_bit(gfn, (void *)kvm_region_slot->bitmap) == false) {
kvm_region_slot->stack[kvm_region_slot->stack_ptr] = gfn; kvm_region_slot->stack[kvm_region_slot->stack_ptr] = gfn;
kvm_region_slot->stack_ptr++; kvm_region_slot->stack_ptr++;
} }
} }
static void dirty_ring_flush_and_collect(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist, int vm_fd){ static void dirty_ring_flush_and_collect(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist,
int vm_fd)
{
struct kvm_dirty_gfn *entry = NULL; struct kvm_dirty_gfn *entry = NULL;
int cleared = 0; int cleared = 0;
while(true){ while (true) {
entry = &kvm_dirty_gfns[kvm_dirty_gfns_index & kvm_dirty_gfns_index_mask]; entry = &kvm_dirty_gfns[kvm_dirty_gfns_index & kvm_dirty_gfns_index_mask];
if((entry->flags & 0x3) == 0){ if ((entry->flags & 0x3) == 0) {
break; break;
} }
if((entry->flags & 0x1) == 1){ if ((entry->flags & 0x1) == 1) {
dirty_ring_collect(self, shadow_memory_state, blocklist, entry->slot, entry->offset); dirty_ring_collect(self, shadow_memory_state, blocklist, entry->slot,
entry->offset);
cleared++; cleared++;
entry->flags |= 0x2; // reset dirty entry entry->flags |= 0x2; // reset dirty entry
} } else {
else{ printf("[QEMU-Nyx] [%p] kvm_dirty_gfn -> flags: %d slot: %d offset: %lx "
printf("[QEMU-Nyx] [%p] kvm_dirty_gfn -> flags: %d slot: %d offset: %lx {ERROR}\n", entry, entry->flags, entry->slot, entry->offset); "{ERROR}\n",
entry, entry->flags, entry->slot, entry->offset);
fflush(stdout); fflush(stdout);
exit(1); exit(1);
} }
@ -136,24 +155,25 @@ static void dirty_ring_flush_and_collect(nyx_dirty_ring_t* self, shadow_memory_t
assert(ret == cleared); assert(ret == cleared);
} }
static void dirty_ring_flush(int vm_fd){ static void dirty_ring_flush(int vm_fd)
{
struct kvm_dirty_gfn *entry = NULL; struct kvm_dirty_gfn *entry = NULL;
int cleared = 0; int cleared = 0;
while(true){ while (true) {
entry = &kvm_dirty_gfns[kvm_dirty_gfns_index & kvm_dirty_gfns_index_mask]; entry = &kvm_dirty_gfns[kvm_dirty_gfns_index & kvm_dirty_gfns_index_mask];
if((entry->flags & 0x3) == 0){ if ((entry->flags & 0x3) == 0) {
break; break;
} }
if((entry->flags & 0x1) == 1){ if ((entry->flags & 0x1) == 1) {
cleared++; cleared++;
entry->flags |= 0x2; // reset dirty entry entry->flags |= 0x2; // reset dirty entry
} } else {
else{ printf("[QEMU-Nyx] [%p] kvm_dirty_gfn -> flags: %d slot: %d offset: %lx "
printf("[QEMU-Nyx] [%p] kvm_dirty_gfn -> flags: %d slot: %d offset: %lx {ERROR}\n", entry, entry->flags, entry->slot, entry->offset); "{ERROR}\n",
entry, entry->flags, entry->slot, entry->offset);
fflush(stdout); fflush(stdout);
exit(1); exit(1);
} }
@ -166,8 +186,9 @@ static void dirty_ring_flush(int vm_fd){
} }
/* init operation */ /* init operation */
nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){ nyx_dirty_ring_t *nyx_dirty_ring_init(shadow_memory_t *shadow_memory)
nyx_dirty_ring_t* self = malloc(sizeof(nyx_dirty_ring_t)); {
nyx_dirty_ring_t *self = malloc(sizeof(nyx_dirty_ring_t));
memset(self, 0, sizeof(nyx_dirty_ring_t)); memset(self, 0, sizeof(nyx_dirty_ring_t));
assert(kvm_state); assert(kvm_state);
@ -179,7 +200,7 @@ nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){
for (int i = 0; i < kvm_get_max_memslots(); i++) { for (int i = 0; i < kvm_get_max_memslots(); i++) {
mem = &kml->slots[i]; mem = &kml->slots[i];
if(mem->start_addr == 0 && mem->memory_size == 0){ if (mem->start_addr == 0 && mem->memory_size == 0) {
break; break;
} }
@ -192,11 +213,11 @@ nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){
for (int i = 0; i < kvm_get_max_memslots(); i++) { for (int i = 0; i < kvm_get_max_memslots(); i++) {
mem = &kml->slots[i]; mem = &kml->slots[i];
if(mem->start_addr == 0 && mem->memory_size == 0){ if (mem->start_addr == 0 && mem->memory_size == 0) {
break; break;
} }
self->kvm_region_slots[i].enabled = (mem->flags&KVM_MEM_READONLY) == 0; self->kvm_region_slots[i].enabled = (mem->flags & KVM_MEM_READONLY) == 0;
self->kvm_region_slots[i].bitmap = malloc(BITMAP_SIZE(mem->memory_size)); self->kvm_region_slots[i].bitmap = malloc(BITMAP_SIZE(mem->memory_size));
self->kvm_region_slots[i].stack = malloc(DIRTY_STACK_SIZE(mem->memory_size)); self->kvm_region_slots[i].stack = malloc(DIRTY_STACK_SIZE(mem->memory_size));
@ -207,15 +228,21 @@ nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){
self->kvm_region_slots[i].stack_ptr = 0; self->kvm_region_slots[i].stack_ptr = 0;
if(self->kvm_region_slots[i].enabled){ if (self->kvm_region_slots[i].enabled) {
bool ram_region_found = false; bool ram_region_found = false;
for(int j = 0; j < shadow_memory->ram_regions_num; j++){ for (int j = 0; j < shadow_memory->ram_regions_num; j++) {
if (FAST_IN_RANGE(mem->start_addr, shadow_memory->ram_regions[j].base,
if(FAST_IN_RANGE(mem->start_addr, shadow_memory->ram_regions[j].base, (shadow_memory->ram_regions[j].base+shadow_memory->ram_regions[j].size))){ (shadow_memory->ram_regions[j].base +
assert(FAST_IN_RANGE((mem->start_addr+mem->memory_size-1), shadow_memory->ram_regions[j].base, (shadow_memory->ram_regions[j].base+shadow_memory->ram_regions[j].size))); shadow_memory->ram_regions[j].size)))
{
assert(FAST_IN_RANGE((mem->start_addr + mem->memory_size - 1),
shadow_memory->ram_regions[j].base,
(shadow_memory->ram_regions[j].base +
shadow_memory->ram_regions[j].size)));
self->kvm_region_slots[i].region_id = j; self->kvm_region_slots[i].region_id = j;
self->kvm_region_slots[i].region_offset = mem->start_addr - shadow_memory->ram_regions[j].base; self->kvm_region_slots[i].region_offset =
mem->start_addr - shadow_memory->ram_regions[j].base;
ram_region_found = true; ram_region_found = true;
break; break;
} }
@ -225,16 +252,17 @@ nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){
} }
#ifdef DEBUG__PRINT_DIRTY_RING #ifdef DEBUG__PRINT_DIRTY_RING
for(int i = 0; i < self->kvm_region_slots_num; i++){ for (int i = 0; i < self->kvm_region_slots_num; i++) {
printf("[%d].enabled = %d\n", i, self->kvm_region_slots[i].enabled); printf("[%d].enabled = %d\n", i, self->kvm_region_slots[i].enabled);
printf("[%d].bitmap = %p\n", i, self->kvm_region_slots[i].bitmap); printf("[%d].bitmap = %p\n", i, self->kvm_region_slots[i].bitmap);
printf("[%d].stack = %p\n", i, self->kvm_region_slots[i].stack); printf("[%d].stack = %p\n", i, self->kvm_region_slots[i].stack);
printf("[%d].stack_ptr = %ld\n", i, self->kvm_region_slots[i].stack_ptr); printf("[%d].stack_ptr = %ld\n", i, self->kvm_region_slots[i].stack_ptr);
if(self->kvm_region_slots[i].enabled){ if (self->kvm_region_slots[i].enabled) {
printf("[%d].region_id = %d\n", i, self->kvm_region_slots[i].region_id); printf("[%d].region_id = %d\n", i,
printf("[%d].region_offset = 0x%lx\n", i, self->kvm_region_slots[i].region_offset); self->kvm_region_slots[i].region_id);
} printf("[%d].region_offset = 0x%lx\n", i,
else{ self->kvm_region_slots[i].region_offset);
} else {
printf("[%d].region_id = -\n", i); printf("[%d].region_id = -\n", i);
printf("[%d].region_offset = -\n", i); printf("[%d].region_offset = -\n", i);
} }
@ -245,40 +273,55 @@ nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory){
return self; return self;
} }
static uint32_t restore_memory(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ static uint32_t restore_memory(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
uint32_t num_dirty_pages = 0; uint32_t num_dirty_pages = 0;
void* host_addr = NULL; void *host_addr = NULL;
void* snapshot_addr = NULL; void *snapshot_addr = NULL;
uint64_t physical_addr = 0; uint64_t physical_addr = 0;
uint64_t gfn = 0; uint64_t gfn = 0;
uint64_t entry_offset_addr = 0; uint64_t entry_offset_addr = 0;
for(uint8_t j = 0; j < self->kvm_region_slots_num; j++){ for (uint8_t j = 0; j < self->kvm_region_slots_num; j++) {
slot_t* kvm_region_slot = &self->kvm_region_slots[j]; slot_t *kvm_region_slot = &self->kvm_region_slots[j];
if(kvm_region_slot->enabled && kvm_region_slot->stack_ptr){ if (kvm_region_slot->enabled && kvm_region_slot->stack_ptr) {
for(uint64_t i = 0; i < kvm_region_slot->stack_ptr; i++){ for (uint64_t i = 0; i < kvm_region_slot->stack_ptr; i++) {
gfn = kvm_region_slot->stack[i]; gfn = kvm_region_slot->stack[i];
entry_offset_addr = kvm_region_slot->region_offset + (gfn<<12); entry_offset_addr = kvm_region_slot->region_offset + (gfn << 12);
physical_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].base + entry_offset_addr; physical_addr =
shadow_memory_state->ram_regions[kvm_region_slot->region_id].base +
entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist,
physical_addr) == true)
{
continue; continue;
} }
host_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].host_region_ptr + entry_offset_addr; host_addr =
shadow_memory_state->ram_regions[kvm_region_slot->region_id]
.host_region_ptr +
entry_offset_addr;
if(shadow_memory_state->incremental_enabled){ if (shadow_memory_state->incremental_enabled) {
snapshot_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].incremental_region_ptr + entry_offset_addr; snapshot_addr =
} shadow_memory_state->ram_regions[kvm_region_slot->region_id]
else{ .incremental_region_ptr +
snapshot_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].snapshot_region_ptr + entry_offset_addr; entry_offset_addr;
} else {
snapshot_addr =
shadow_memory_state->ram_regions[kvm_region_slot->region_id]
.snapshot_region_ptr +
entry_offset_addr;
} }
memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE); memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE);
clear_bit(gfn, (void*)kvm_region_slot->bitmap); clear_bit(gfn, (void *)kvm_region_slot->bitmap);
num_dirty_pages++; num_dirty_pages++;
} }
kvm_region_slot->stack_ptr = 0; kvm_region_slot->stack_ptr = 0;
@ -287,55 +330,82 @@ static uint32_t restore_memory(nyx_dirty_ring_t* self, shadow_memory_t* shadow_m
return num_dirty_pages; return num_dirty_pages;
} }
static void save_root_pages(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ static void save_root_pages(nyx_dirty_ring_t *self,
void* host_addr = NULL; shadow_memory_t *shadow_memory_state,
void* incremental_addr = NULL; snapshot_page_blocklist_t *blocklist)
{
void *host_addr = NULL;
void *incremental_addr = NULL;
uint64_t physical_addr = 0; uint64_t physical_addr = 0;
uint64_t gfn = 0; uint64_t gfn = 0;
uint64_t entry_offset_addr = 0; uint64_t entry_offset_addr = 0;
for(uint8_t j = 0; j < self->kvm_region_slots_num; j++){ for (uint8_t j = 0; j < self->kvm_region_slots_num; j++) {
slot_t* kvm_region_slot = &self->kvm_region_slots[j]; slot_t *kvm_region_slot = &self->kvm_region_slots[j];
if(kvm_region_slot->enabled && kvm_region_slot->stack_ptr){ if (kvm_region_slot->enabled && kvm_region_slot->stack_ptr) {
for(uint64_t i = 0; i < kvm_region_slot->stack_ptr; i++){ for (uint64_t i = 0; i < kvm_region_slot->stack_ptr; i++) {
gfn = kvm_region_slot->stack[i]; gfn = kvm_region_slot->stack[i];
entry_offset_addr = kvm_region_slot->region_offset + (gfn<<12); entry_offset_addr = kvm_region_slot->region_offset + (gfn << 12);
physical_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].base + entry_offset_addr; physical_addr =
shadow_memory_state->ram_regions[kvm_region_slot->region_id].base +
entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist,
physical_addr) == true)
{
continue; continue;
} }
host_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].host_region_ptr + entry_offset_addr; host_addr =
incremental_addr = shadow_memory_state->ram_regions[kvm_region_slot->region_id].incremental_region_ptr + entry_offset_addr; shadow_memory_state->ram_regions[kvm_region_slot->region_id]
.host_region_ptr +
entry_offset_addr;
incremental_addr =
shadow_memory_state->ram_regions[kvm_region_slot->region_id]
.incremental_region_ptr +
entry_offset_addr;
shadow_memory_track_dirty_root_pages(shadow_memory_state, entry_offset_addr, kvm_region_slot->region_id); shadow_memory_track_dirty_root_pages(shadow_memory_state,
entry_offset_addr,
kvm_region_slot->region_id);
memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE); memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE);
clear_bit(gfn, (void*)kvm_region_slot->bitmap); clear_bit(gfn, (void *)kvm_region_slot->bitmap);
} }
kvm_region_slot->stack_ptr = 0; kvm_region_slot->stack_ptr = 0;
} }
} }
} }
uint32_t nyx_snapshot_nyx_dirty_ring_restore(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ uint32_t nyx_snapshot_nyx_dirty_ring_restore(nyx_dirty_ring_t *self,
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist, kvm_get_vm_fd(kvm_state)); shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist,
kvm_get_vm_fd(kvm_state));
return restore_memory(self, shadow_memory_state, blocklist); return restore_memory(self, shadow_memory_state, blocklist);
} }
void nyx_snapshot_nyx_dirty_ring_save_root_pages(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ void nyx_snapshot_nyx_dirty_ring_save_root_pages(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist, kvm_get_vm_fd(kvm_state)); snapshot_page_blocklist_t *blocklist)
{
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist,
kvm_get_vm_fd(kvm_state));
save_root_pages(self, shadow_memory_state, blocklist); save_root_pages(self, shadow_memory_state, blocklist);
} }
void nyx_snapshot_nyx_dirty_ring_flush(void){ void nyx_snapshot_nyx_dirty_ring_flush(void)
{
dirty_ring_flush(kvm_get_vm_fd(kvm_state)); dirty_ring_flush(kvm_get_vm_fd(kvm_state));
} }
void nyx_snapshot_nyx_dirty_ring_flush_and_collect(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ void nyx_snapshot_nyx_dirty_ring_flush_and_collect(nyx_dirty_ring_t *self,
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist, kvm_get_vm_fd(kvm_state)); shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
dirty_ring_flush_and_collect(self, shadow_memory_state, blocklist,
kvm_get_vm_fd(kvm_state));
} }

View File

@ -1,8 +1,8 @@
#pragma once #pragma once
#include <stdint.h>
#include "nyx/snapshot/memory/block_list.h" #include "nyx/snapshot/memory/block_list.h"
#include "nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/memory/shadow_memory.h"
#include <stdint.h>
struct kvm_dirty_gfn { struct kvm_dirty_gfn {
uint32_t flags; uint32_t flags;
@ -10,21 +10,21 @@ struct kvm_dirty_gfn {
uint64_t offset; uint64_t offset;
}; };
typedef struct slot_s{ typedef struct slot_s {
bool enabled; /* set if slot is not marked as read-only */ bool enabled; /* set if slot is not marked as read-only */
uint8_t region_id; /* shadow_memory region id */ uint8_t region_id; /* shadow_memory region id */
uint64_t region_offset; /* shadow_memory region offset*/ uint64_t region_offset; /* shadow_memory region offset*/
void* bitmap; void *bitmap;
uint64_t bitmap_size; // remove me later uint64_t bitmap_size; // remove me later
uint64_t* stack; uint64_t *stack;
uint64_t stack_ptr; uint64_t stack_ptr;
} slot_t; } slot_t;
typedef struct nyx_dirty_ring_s{ typedef struct nyx_dirty_ring_s {
slot_t* kvm_region_slots; slot_t *kvm_region_slots;
uint8_t kvm_region_slots_num; uint8_t kvm_region_slots_num;
} nyx_dirty_ring_t; } nyx_dirty_ring_t;
@ -35,12 +35,18 @@ void nyx_dirty_ring_early_init(int kvm_fd, int vm_fd);
/* must be called right after KVM_CREATE_VCPU */ /* must be called right after KVM_CREATE_VCPU */
void nyx_dirty_ring_pre_init(int kvm_fd, int vm_fd); void nyx_dirty_ring_pre_init(int kvm_fd, int vm_fd);
nyx_dirty_ring_t* nyx_dirty_ring_init(shadow_memory_t* shadow_memory); nyx_dirty_ring_t *nyx_dirty_ring_init(shadow_memory_t *shadow_memory);
uint32_t nyx_snapshot_nyx_dirty_ring_restore(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); uint32_t nyx_snapshot_nyx_dirty_ring_restore(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);
void nyx_snapshot_nyx_dirty_ring_save_root_pages(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); void nyx_snapshot_nyx_dirty_ring_save_root_pages(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);
void nyx_snapshot_nyx_dirty_ring_flush(void); void nyx_snapshot_nyx_dirty_ring_flush(void);
void nyx_snapshot_nyx_dirty_ring_flush_and_collect(nyx_dirty_ring_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); void nyx_snapshot_nyx_dirty_ring_flush_and_collect(nyx_dirty_ring_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);

View File

@ -1,10 +1,10 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qemu/rcu_queue.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
@ -16,27 +16,27 @@
#include "nyx/snapshot/memory/nyx_fdl_user.h" #include "nyx/snapshot/memory/nyx_fdl_user.h"
/* debug option for the FDL constructor */ /* debug option for the FDL constructor */
//#define DEBUG_VMX_FDL_ALLOC // #define DEBUG_VMX_FDL_ALLOC
/* additional output to debug the FDL restore operation */ /* additional output to debug the FDL restore operation */
//#define SHOW_NUM_DIRTY_PAGES // #define SHOW_NUM_DIRTY_PAGES
/* option to include restore of VRAM memory */ /* option to include restore of VRAM memory */
//#define RESET_VRAM // #define RESET_VRAM
//#define DEBUG_FDL_VRAM // #define DEBUG_FDL_VRAM
nyx_fdl_t* nyx_fdl_init(shadow_memory_t* shadow_memory){
nyx_fdl_t *nyx_fdl_init(shadow_memory_t *shadow_memory)
{
static bool fdl_created = false; static bool fdl_created = false;
/* not sure if we're able to create another FDL instance -> probably not */ /* not sure if we're able to create another FDL instance -> probably not */
assert(fdl_created == false); assert(fdl_created == false);
fdl_created = true; fdl_created = true;
nyx_fdl_t* self = malloc(sizeof(nyx_fdl_t)); nyx_fdl_t *self = malloc(sizeof(nyx_fdl_t));
memset(self, 0, sizeof(nyx_fdl_t)); memset(self, 0, sizeof(nyx_fdl_t));
int ret; int ret;
CPUState* cpu = qemu_get_cpu(0); CPUState *cpu = qemu_get_cpu(0);
kvm_cpu_synchronize_state(cpu); kvm_cpu_synchronize_state(cpu);
struct fdl_conf configuration; struct fdl_conf configuration;
@ -46,9 +46,11 @@ nyx_fdl_t* nyx_fdl_init(shadow_memory_t* shadow_memory){
configuration.num = 0; configuration.num = 0;
for(uint8_t i = 0; i < shadow_memory->ram_regions_num; i++){ for (uint8_t i = 0; i < shadow_memory->ram_regions_num; i++) {
configuration.areas[configuration.num].base_address = shadow_memory->ram_regions[i].base; configuration.areas[configuration.num].base_address =
configuration.areas[configuration.num].size = shadow_memory->ram_regions[i].size; shadow_memory->ram_regions[i].base;
configuration.areas[configuration.num].size =
shadow_memory->ram_regions[i].size;
configuration.num++; configuration.num++;
} }
@ -58,19 +60,24 @@ nyx_fdl_t* nyx_fdl_init(shadow_memory_t* shadow_memory){
#ifdef DEBUG_VMX_FDL_ALLOC #ifdef DEBUG_VMX_FDL_ALLOC
printf("KVM_VMX_FDL_SET: %d\n", ret); printf("KVM_VMX_FDL_SET: %d\n", ret);
printf("configuration.mmap_size = 0x%lx\n", configuration.mmap_size); printf("configuration.mmap_size = 0x%lx\n", configuration.mmap_size);
for(uint8_t i = 0; i < configuration.num; i++){ for (uint8_t i = 0; i < configuration.num; i++) {
printf("configuration.areas[%d].mmap_bitmap_offset = 0x%lx\n", i, configuration.areas[i].mmap_bitmap_offset); printf("configuration.areas[%d].mmap_bitmap_offset = 0x%lx\n", i,
printf("configuration.areas[%d].mmap_stack_offset = 0x%lx\n", i, configuration.areas[i].mmap_stack_offset); configuration.areas[i].mmap_bitmap_offset);
printf("configuration.areas[%d].mmap_stack_offset = 0x%lx\n", i,
configuration.areas[i].mmap_stack_offset);
} }
#endif #endif
self->vmx_fdl_mmap = mmap(NULL, configuration.mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, self->vmx_fdl_fd, 0); self->vmx_fdl_mmap = mmap(NULL, configuration.mmap_size, PROT_READ | PROT_WRITE,
MAP_SHARED, self->vmx_fdl_fd, 0);
assert(self->vmx_fdl_mmap != (void*)0xFFFFFFFFFFFFFFFF); assert(self->vmx_fdl_mmap != (void *)0xFFFFFFFFFFFFFFFF);
for(uint8_t i = 0; i < configuration.num; i++){ for (uint8_t i = 0; i < configuration.num; i++) {
self->entry[i].stack = self->vmx_fdl_mmap + configuration.areas[i].mmap_stack_offset; self->entry[i].stack =
self->entry[i].bitmap = self->vmx_fdl_mmap + configuration.areas[i].mmap_bitmap_offset; self->vmx_fdl_mmap + configuration.areas[i].mmap_stack_offset;
self->entry[i].bitmap =
self->vmx_fdl_mmap + configuration.areas[i].mmap_bitmap_offset;
#ifdef DEBUG_VMX_FDL_ALLOC #ifdef DEBUG_VMX_FDL_ALLOC
printf("fdl_stacks[%d] -> %p\n", i, self->entry[i].stack); printf("fdl_stacks[%d] -> %p\n", i, self->entry[i].stack);
@ -86,7 +93,7 @@ nyx_fdl_t* nyx_fdl_init(shadow_memory_t* shadow_memory){
#ifdef DEBUG_VMX_FDL_ALLOC #ifdef DEBUG_VMX_FDL_ALLOC
printf("result: %d\n", result.num); printf("result: %d\n", result.num);
for(uint8_t i = 0; i < result.num; i++){ for (uint8_t i = 0; i < result.num; i++) {
printf("result.values[%d]: %ld\n", i, result.values[i]); printf("result.values[%d]: %ld\n", i, result.values[i]);
} }
#endif #endif
@ -95,99 +102,110 @@ nyx_fdl_t* nyx_fdl_init(shadow_memory_t* shadow_memory){
} }
/* restore operation */ /* restore operation */
uint32_t nyx_snapshot_nyx_fdl_restore(nyx_fdl_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ uint32_t nyx_snapshot_nyx_fdl_restore(nyx_fdl_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
uint32_t num_dirty_pages = 0; uint32_t num_dirty_pages = 0;
void* current_region = NULL; void *current_region = NULL;
struct fdl_result result; struct fdl_result result;
memset(&result, 0, sizeof(struct fdl_result)); memset(&result, 0, sizeof(struct fdl_result));
int res = ioctl(self->vmx_fdl_fd, KVM_VMX_FDL_GET_INDEX, &result); int res = ioctl(self->vmx_fdl_fd, KVM_VMX_FDL_GET_INDEX, &result);
assert(!res); assert(!res);
//nyx_snapshot_nyx_fdl_unset_blocklisted_pages(self, shadow_memory_state, blocklist); // nyx_snapshot_nyx_fdl_unset_blocklisted_pages(self, shadow_memory_state, blocklist);
for(uint8_t i = 0; i < result.num; i++){ for (uint8_t i = 0; i < result.num; i++) {
#ifdef SHOW_NUM_DIRTY_PAGES #ifdef SHOW_NUM_DIRTY_PAGES
printf("Kernel -> [%d] %ld \t%ldKB\n", i, result.values[i], (0x1000*result.values[i])>>0x10); printf("Kernel -> [%d] %ld \t%ldKB\n", i, result.values[i],
(0x1000 * result.values[i]) >> 0x10);
#endif #endif
if(shadow_memory_state->incremental_enabled){ if (shadow_memory_state->incremental_enabled) {
current_region = shadow_memory_state->ram_regions[i].incremental_region_ptr; current_region =
} shadow_memory_state->ram_regions[i].incremental_region_ptr;
else{ } else {
current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr; current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr;
} }
for(uint64_t j = 0; j < result.values[i]; j++){ for (uint64_t j = 0; j < result.values[i]; j++) {
uint64_t physical_addr = self->entry[i].stack[j]; uint64_t physical_addr = self->entry[i].stack[j];
uint64_t entry_offset_addr = physical_addr - shadow_memory_state->ram_regions[i].base; uint64_t entry_offset_addr =
physical_addr - shadow_memory_state->ram_regions[i].base;
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + entry_offset_addr; void *host_addr = shadow_memory_state->ram_regions[i].host_region_ptr +
void* snapshot_addr = current_region + entry_offset_addr; entry_offset_addr;
void *snapshot_addr = current_region + entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) ==
true)
{
#ifdef DEBUG_VERFIY_BITMAP #ifdef DEBUG_VERFIY_BITMAP
if(!is_black_listed_addr(self, entry_offset_addr)){ if (!is_black_listed_addr(self, entry_offset_addr)) {
printf("WARNING: %s: -> %lx is not blacklisted\n", __func__, entry_offset_addr); printf("WARNING: %s: -> %lx is not blacklisted\n", __func__,
entry_offset_addr);
abort(); abort();
} }
#endif #endif
continue; // blacklisted page continue; // blacklisted page
} }
clear_bit(entry_offset_addr>>12, (void*)self->entry[i].bitmap); clear_bit(entry_offset_addr >> 12, (void *)self->entry[i].bitmap);
memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE); memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE);
num_dirty_pages++; num_dirty_pages++;
} }
} }
#ifdef RESET_VRAM #ifdef RESET_VRAM
//nyx_snapshot_nyx_fdl_restore_vram(self, shadow_memory_state); // nyx_snapshot_nyx_fdl_restore_vram(self, shadow_memory_state);
#endif #endif
return num_dirty_pages; return num_dirty_pages;
} }
void nyx_snapshot_nyx_fdl_save_root_pages(nyx_fdl_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ void nyx_snapshot_nyx_fdl_save_root_pages(nyx_fdl_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
struct fdl_result result; struct fdl_result result;
memset(&result, 0, sizeof(struct fdl_result)); memset(&result, 0, sizeof(struct fdl_result));
int res = ioctl(self->vmx_fdl_fd, KVM_VMX_FDL_GET_INDEX, &result); int res = ioctl(self->vmx_fdl_fd, KVM_VMX_FDL_GET_INDEX, &result);
assert(!res); assert(!res);
for(uint8_t i = 0; i < result.num; i++){ for (uint8_t i = 0; i < result.num; i++) {
#ifdef SHOW_NUM_DIRTY_PAGES #ifdef SHOW_NUM_DIRTY_PAGES
printf("Kernel -> [%d] %ld \t%ldKB\n", i, result.values[i], (0x1000*result.values[i])>>0x10); printf("Kernel -> [%d] %ld \t%ldKB\n", i, result.values[i],
(0x1000 * result.values[i]) >> 0x10);
#endif #endif
for(uint64_t j = 0; j < result.values[i]; j++){ for (uint64_t j = 0; j < result.values[i]; j++) {
uint64_t physical_addr = self->entry[i].stack[j]; uint64_t physical_addr = self->entry[i].stack[j];
uint64_t entry_offset_addr = physical_addr - shadow_memory_state->ram_regions[i].base; uint64_t entry_offset_addr =
physical_addr - shadow_memory_state->ram_regions[i].base;
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + entry_offset_addr; void *host_addr = shadow_memory_state->ram_regions[i].host_region_ptr +
void* incremental_addr = shadow_memory_state->ram_regions[i].incremental_region_ptr + entry_offset_addr; entry_offset_addr;
void *incremental_addr =
shadow_memory_state->ram_regions[i].incremental_region_ptr +
entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) ==
true)
{
#ifdef DEBUG_VERFIY_BITMAP #ifdef DEBUG_VERFIY_BITMAP
if(!is_black_listed_addr(self, entry_offset_addr)){ if (!is_black_listed_addr(self, entry_offset_addr)) {
printf("WARNING: %s: -> %lx is not blacklisted\n", __func__, entry_offset_addr); printf("WARNING: %s: -> %lx is not blacklisted\n", __func__,
entry_offset_addr);
abort(); abort();
} }
#endif #endif
continue; // skip blacklisted page continue; // skip blacklisted page
} }
clear_bit(entry_offset_addr>>12, (void*)self->entry[i].bitmap); clear_bit(entry_offset_addr >> 12, (void *)self->entry[i].bitmap);
shadow_memory_track_dirty_root_pages(shadow_memory_state, entry_offset_addr, i); shadow_memory_track_dirty_root_pages(shadow_memory_state,
entry_offset_addr, i);
memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE); memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE);
} }
} }
} }

View File

@ -19,7 +19,7 @@
#define FDL_MAX_AREAS 8 #define FDL_MAX_AREAS 8
struct fdl_area{ struct fdl_area {
uint64_t base_address; uint64_t base_address;
uint64_t size; uint64_t size;
uint64_t mmap_bitmap_offset; uint64_t mmap_bitmap_offset;
@ -28,34 +28,38 @@ struct fdl_area{
uint64_t mmap_stack_size; uint64_t mmap_stack_size;
}; };
struct fdl_conf{ struct fdl_conf {
uint8_t num; uint8_t num;
uint64_t mmap_size; uint64_t mmap_size;
struct fdl_area areas[FDL_MAX_AREAS]; struct fdl_area areas[FDL_MAX_AREAS];
}; };
struct fdl_result{ struct fdl_result {
uint8_t num; uint8_t num;
uint64_t values[FDL_MAX_AREAS]; uint64_t values[FDL_MAX_AREAS];
}; };
typedef struct nyx_fdl_s{ typedef struct nyx_fdl_s {
/* vmx_fdl file descriptor */ /* vmx_fdl file descriptor */
int vmx_fdl_fd; int vmx_fdl_fd;
/* mmap mapping of fdl data -> might be useful for destructor */ /* mmap mapping of fdl data -> might be useful for destructor */
void* vmx_fdl_mmap; void *vmx_fdl_mmap;
struct { struct {
uint64_t* stack; uint64_t *stack;
uint8_t* bitmap; uint8_t *bitmap;
}entry[FDL_MAX_AREAS]; } entry[FDL_MAX_AREAS];
uint8_t num; uint8_t num;
}nyx_fdl_t; } nyx_fdl_t;
nyx_fdl_t* nyx_fdl_init(shadow_memory_t* self); nyx_fdl_t *nyx_fdl_init(shadow_memory_t *self);
uint32_t nyx_snapshot_nyx_fdl_restore(nyx_fdl_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); uint32_t nyx_snapshot_nyx_fdl_restore(nyx_fdl_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);
void nyx_snapshot_nyx_fdl_save_root_pages(nyx_fdl_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); void nyx_snapshot_nyx_fdl_save_root_pages(nyx_fdl_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);

View File

@ -1,34 +1,37 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qemu/rcu_queue.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/snapshot/memory/block_list.h"
#include "nyx/snapshot/helper.h" #include "nyx/snapshot/helper.h"
#include "nyx/snapshot/memory/block_list.h"
#include "nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/memory/shadow_memory.h"
#define REALLOC_SIZE 0x8000 #define REALLOC_SIZE 0x8000
//#define DEBUG_NYX_SNAPSHOT_PAGE_BLOCKLIST // #define DEBUG_NYX_SNAPSHOT_PAGE_BLOCKLIST
snapshot_page_blocklist_t* snapshot_page_blocklist_init(void){ snapshot_page_blocklist_t *snapshot_page_blocklist_init(void)
{
snapshot_page_blocklist_t* self = malloc(sizeof(snapshot_page_blocklist_t)); snapshot_page_blocklist_t *self = malloc(sizeof(snapshot_page_blocklist_t));
uint64_t ram_size = get_ram_size(); uint64_t ram_size = get_ram_size();
self->phys_area_size = ram_size <= MEM_SPLIT_START ? ram_size : ram_size + (MEM_SPLIT_END-MEM_SPLIT_START); self->phys_area_size = ram_size <= MEM_SPLIT_START ?
ram_size :
ram_size + (MEM_SPLIT_END - MEM_SPLIT_START);
self->phys_bitmap = malloc(BITMAP_SIZE(self->phys_area_size)); self->phys_bitmap = malloc(BITMAP_SIZE(self->phys_area_size));
memset(self->phys_bitmap, 0x0, BITMAP_SIZE(self->phys_area_size)); memset(self->phys_bitmap, 0x0, BITMAP_SIZE(self->phys_area_size));
if(ram_size > MEM_SPLIT_START){ if (ram_size > MEM_SPLIT_START) {
memset(self->phys_bitmap+BITMAP_SIZE(MEM_SPLIT_START), 0xff, BITMAP_SIZE((MEM_SPLIT_END-MEM_SPLIT_START))); memset(self->phys_bitmap + BITMAP_SIZE(MEM_SPLIT_START), 0xff,
BITMAP_SIZE((MEM_SPLIT_END - MEM_SPLIT_START)));
} }
self->pages_num = 0; self->pages_num = 0;
@ -38,8 +41,9 @@ snapshot_page_blocklist_t* snapshot_page_blocklist_init(void){
return self; return self;
} }
void snapshot_page_blocklist_add(snapshot_page_blocklist_t* self, uint64_t phys_addr){ void snapshot_page_blocklist_add(snapshot_page_blocklist_t *self, uint64_t phys_addr)
if(phys_addr == -1){ {
if (phys_addr == -1) {
fprintf(stderr, "ERROR %s: phys_addr=%lx\n", __func__, phys_addr); fprintf(stderr, "ERROR %s: phys_addr=%lx\n", __func__, phys_addr);
return; return;
} }
@ -47,7 +51,7 @@ void snapshot_page_blocklist_add(snapshot_page_blocklist_t* self, uint64_t phys_
assert(phys_addr < self->phys_area_size); assert(phys_addr < self->phys_area_size);
if(self->pages_num <= self->pages_size){ if (self->pages_num <= self->pages_size) {
self->pages_size += REALLOC_SIZE; self->pages_size += REALLOC_SIZE;
self->pages = realloc(self->pages, sizeof(uint64_t) * self->pages_size); self->pages = realloc(self->pages, sizeof(uint64_t) * self->pages_size);
} }
@ -56,10 +60,10 @@ void snapshot_page_blocklist_add(snapshot_page_blocklist_t* self, uint64_t phys_
self->pages_num++; self->pages_num++;
/* check if bit is empty */ /* check if bit is empty */
assert(test_bit(phys_addr>>12, (const unsigned long *)self->phys_bitmap) == 0); assert(test_bit(phys_addr >> 12, (const unsigned long *)self->phys_bitmap) == 0);
/* set bit for lookup */ /* set bit for lookup */
set_bit(phys_addr>>12, (unsigned long *)self->phys_bitmap); set_bit(phys_addr >> 12, (unsigned long *)self->phys_bitmap);
#ifdef DEBUG_NYX_SNAPSHOT_PAGE_BLOCKLIST #ifdef DEBUG_NYX_SNAPSHOT_PAGE_BLOCKLIST

View File

@ -1,32 +1,34 @@
#pragma once #pragma once
#include <stdint.h>
#include <stdbool.h>
#include "nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/memory/shadow_memory.h"
#include <stdbool.h>
#include <stdint.h>
typedef struct snapshot_page_blocklist_s{ typedef struct snapshot_page_blocklist_s {
/* total number of blocklisted page frames */ /* total number of blocklisted page frames */
uint64_t pages_num; uint64_t pages_num;
/* lookup array */ /* lookup array */
uint64_t* pages; uint64_t *pages;
/* current size of our array */ /* current size of our array */
uint64_t pages_size; uint64_t pages_size;
/* lookup bitmap of guest's physical memory layout (PCI-area between 3GB-4GB is set by default) */ /* lookup bitmap of guest's physical memory layout (PCI-area between 3GB-4GB is set by default) */
uint8_t* phys_bitmap; uint8_t *phys_bitmap;
/* area of guest's physical memory (including RAM + PCI-hole) */ /* area of guest's physical memory (including RAM + PCI-hole) */
uint64_t phys_area_size; uint64_t phys_area_size;
}snapshot_page_blocklist_t; } snapshot_page_blocklist_t;
void snapshot_page_blocklist_add(snapshot_page_blocklist_t* self, uint64_t phys_addr); void snapshot_page_blocklist_add(snapshot_page_blocklist_t *self, uint64_t phys_addr);
/* returns true if phys_addr is on the blocklis */ /* returns true if phys_addr is on the blocklis */
static inline bool snapshot_page_blocklist_check_phys_addr(snapshot_page_blocklist_t* self, uint64_t phys_addr){ static inline bool snapshot_page_blocklist_check_phys_addr(
return phys_addr < self->phys_area_size && test_bit(phys_addr>>12, (const unsigned long *)self->phys_bitmap) != 0; snapshot_page_blocklist_t *self, uint64_t phys_addr)
{
return phys_addr < self->phys_area_size &&
test_bit(phys_addr >> 12, (const unsigned long *)self->phys_bitmap) != 0;
} }
snapshot_page_blocklist_t* snapshot_page_blocklist_init(void); snapshot_page_blocklist_t *snapshot_page_blocklist_init(void);

View File

@ -1,6 +1,6 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "migration/migration.h" #include "migration/migration.h"
@ -11,83 +11,93 @@
#include <sys/ioctl.h> #include <sys/ioctl.h>
#include "nyx/snapshot/helper.h" #include "nyx/snapshot/helper.h"
#include "nyx/snapshot/memory/shadow_memory.h"
#include "nyx/snapshot/memory/nyx_fdl_user.h" #include "nyx/snapshot/memory/nyx_fdl_user.h"
#include "nyx/snapshot/memory/shadow_memory.h"
/* debug option */ /* debug option */
//#define DEBUG_USER_FDL // #define DEBUG_USER_FDL
/* init operation */ /* init operation */
nyx_fdl_user_t* nyx_fdl_user_init(shadow_memory_t* shadow_memory_state){ nyx_fdl_user_t *nyx_fdl_user_init(shadow_memory_t *shadow_memory_state)
{
nyx_fdl_user_t* self = malloc(sizeof(nyx_fdl_user_t)); nyx_fdl_user_t *self = malloc(sizeof(nyx_fdl_user_t));
memset(self, 0, sizeof(nyx_fdl_user_t)); memset(self, 0, sizeof(nyx_fdl_user_t));
/* get rid of that? */ /* get rid of that? */
self->num = shadow_memory_state->ram_regions_num; self->num = shadow_memory_state->ram_regions_num;
for(uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++){ for (uint8_t i = 0; i < shadow_memory_state->ram_regions_num; i++) {
self->entry[i].stack = malloc(DIRTY_STACK_SIZE(shadow_memory_state->ram_regions[i].size)); self->entry[i].stack =
self->entry[i].bitmap = malloc(BITMAP_SIZE(shadow_memory_state->ram_regions[i].size)); malloc(DIRTY_STACK_SIZE(shadow_memory_state->ram_regions[i].size));
self->entry[i].bitmap =
malloc(BITMAP_SIZE(shadow_memory_state->ram_regions[i].size));
} }
return self; return self;
} }
/* enable operation */ /* enable operation */
void nyx_fdl_user_enable(nyx_fdl_user_t* self){ void nyx_fdl_user_enable(nyx_fdl_user_t *self)
{
assert(self); assert(self);
self->enabled = true; self->enabled = true;
} }
static void nyx_snapshot_user_fdl_reset(nyx_fdl_user_t* self){ static void nyx_snapshot_user_fdl_reset(nyx_fdl_user_t *self)
if(self){ {
for(uint8_t i = 0; i < self->num; i++){ if (self) {
for (uint8_t i = 0; i < self->num; i++) {
self->entry[i].pos = 0; self->entry[i].pos = 0;
} }
} }
} }
/* reset operation */ /* reset operation */
uint32_t nyx_snapshot_user_fdl_restore(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ uint32_t nyx_snapshot_user_fdl_restore(nyx_fdl_user_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist)
{
uint32_t num_dirty_pages = 0; uint32_t num_dirty_pages = 0;
if(self){ if (self) {
void *current_region = NULL;
void* current_region = NULL;
for(uint8_t i = 0; i < self->num; i++){ for (uint8_t i = 0; i < self->num; i++) {
#ifdef DEBUG_USER_FDL #ifdef DEBUG_USER_FDL
printf("User -> [%d] %ld \t%ldKB\n", i, self->entry[i].pos, (0x1000*self->entry[i].pos)>>0x10); printf("User -> [%d] %ld \t%ldKB\n", i, self->entry[i].pos,
(0x1000 * self->entry[i].pos) >> 0x10);
#endif #endif
if(shadow_memory_state->incremental_enabled){ if (shadow_memory_state->incremental_enabled) {
current_region = shadow_memory_state->ram_regions[i].incremental_region_ptr; current_region =
} shadow_memory_state->ram_regions[i].incremental_region_ptr;
else{ } else {
current_region = shadow_memory_state->ram_regions[i].snapshot_region_ptr; current_region =
shadow_memory_state->ram_regions[i].snapshot_region_ptr;
} }
for(uint64_t j = 0; j < self->entry[i].pos; j++){ for (uint64_t j = 0; j < self->entry[i].pos; j++) {
uint64_t physical_addr = self->entry[i].stack[j]; uint64_t physical_addr = self->entry[i].stack[j];
uint64_t entry_offset_addr = physical_addr - shadow_memory_state->ram_regions[i].base; uint64_t entry_offset_addr =
physical_addr - shadow_memory_state->ram_regions[i].base;
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + entry_offset_addr; void *host_addr = shadow_memory_state->ram_regions[i].host_region_ptr +
void* snapshot_addr = current_region + entry_offset_addr; entry_offset_addr;
void *snapshot_addr = current_region + entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist,
physical_addr) == true)
{
continue; continue;
} }
#ifdef DEBUG_USER_FDL #ifdef DEBUG_USER_FDL
printf("%s -> %p <-- %p\n", __func__, host_addr, snapshot_addr); printf("%s -> %p <-- %p\n", __func__, host_addr, snapshot_addr);
#endif #endif
clear_bit(entry_offset_addr>>12, (void*)self->entry[i].bitmap); clear_bit(entry_offset_addr >> 12, (void *)self->entry[i].bitmap);
memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE); memcpy(host_addr, snapshot_addr, TARGET_PAGE_SIZE);
num_dirty_pages++; num_dirty_pages++;
} }
} }
} }
nyx_snapshot_user_fdl_reset(self); nyx_snapshot_user_fdl_reset(self);
@ -95,60 +105,106 @@ uint32_t nyx_snapshot_user_fdl_restore(nyx_fdl_user_t* self, shadow_memory_t* sh
} }
/* set operation (mark pf as dirty) */ /* set operation (mark pf as dirty) */
void nyx_fdl_user_set(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, nyx_fdl_t* nyx_fdl_state, uint64_t addr, uint64_t length){ void nyx_fdl_user_set(nyx_fdl_user_t *self,
if(length < 0x1000){ shadow_memory_t *shadow_memory_state,
nyx_fdl_t *nyx_fdl_state,
uint64_t addr,
uint64_t length)
{
if (length < 0x1000) {
length = 0x1000; length = 0x1000;
} }
if(self && self->enabled && length >= 0x1000){ if (self && self->enabled && length >= 0x1000) {
uint8_t ram_area = 0xff; uint8_t ram_area = 0xff;
/* optimize this? */ /* optimize this? */
addr = ram_offset_to_address(addr); addr = ram_offset_to_address(addr);
switch(MAX_REGIONS-shadow_memory_state->ram_regions_num){ switch (MAX_REGIONS - shadow_memory_state->ram_regions_num) {
case 0: case 0:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[7].base, shadow_memory_state->ram_regions[7].base+(shadow_memory_state->ram_regions[7].size-1)) ? 7 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[7].base,
shadow_memory_state->ram_regions[7].base +
(shadow_memory_state->ram_regions[7].size - 1)) ?
7 :
ram_area;
case 1: case 1:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[6].base, shadow_memory_state->ram_regions[6].base+(shadow_memory_state->ram_regions[6].size-1)) ? 6 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[6].base,
shadow_memory_state->ram_regions[6].base +
(shadow_memory_state->ram_regions[6].size - 1)) ?
6 :
ram_area;
case 2: case 2:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[5].base, shadow_memory_state->ram_regions[5].base+(shadow_memory_state->ram_regions[5].size-1)) ? 5 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[5].base,
shadow_memory_state->ram_regions[5].base +
(shadow_memory_state->ram_regions[5].size - 1)) ?
5 :
ram_area;
case 3: case 3:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[4].base, shadow_memory_state->ram_regions[4].base+(shadow_memory_state->ram_regions[4].size-1)) ? 4 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[4].base,
shadow_memory_state->ram_regions[4].base +
(shadow_memory_state->ram_regions[4].size - 1)) ?
4 :
ram_area;
case 4: case 4:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[3].base, shadow_memory_state->ram_regions[3].base+(shadow_memory_state->ram_regions[3].size-1)) ? 3 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[3].base,
shadow_memory_state->ram_regions[3].base +
(shadow_memory_state->ram_regions[3].size - 1)) ?
3 :
ram_area;
case 5: case 5:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[2].base, shadow_memory_state->ram_regions[2].base+(shadow_memory_state->ram_regions[2].size-1)) ? 2 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[2].base,
shadow_memory_state->ram_regions[2].base +
(shadow_memory_state->ram_regions[2].size - 1)) ?
2 :
ram_area;
case 6: case 6:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[1].base, shadow_memory_state->ram_regions[1].base+(shadow_memory_state->ram_regions[1].size-1)) ? 1 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[1].base,
shadow_memory_state->ram_regions[1].base +
(shadow_memory_state->ram_regions[1].size - 1)) ?
1 :
ram_area;
case 7: case 7:
ram_area = FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[0].base, shadow_memory_state->ram_regions[0].base+(shadow_memory_state->ram_regions[0].size-1)) ? 0 : ram_area; ram_area =
FAST_IN_RANGE(addr, shadow_memory_state->ram_regions[0].base,
shadow_memory_state->ram_regions[0].base +
(shadow_memory_state->ram_regions[0].size - 1)) ?
0 :
ram_area;
default: default:
break; break;
} }
if(ram_area == 0xff){ if (ram_area == 0xff) {
printf("ERROR: %s %lx [%d]\n", __func__, addr, ram_area); printf("ERROR: %s %lx [%d]\n", __func__, addr, ram_area);
abort(); abort();
return; return;
} }
for(uint64_t offset = 0; offset < length; offset+=0x1000){ for (uint64_t offset = 0; offset < length; offset += 0x1000) {
uint64_t current_addr = (addr + offset) & 0xFFFFFFFFFFFFF000;
uint64_t current_addr = (addr+offset) & 0xFFFFFFFFFFFFF000; long pfn = (long)((current_addr -
shadow_memory_state->ram_regions[ram_area].base) >>
long pfn = (long) ((current_addr-shadow_memory_state->ram_regions[ram_area].base)>>12); 12);
assert(self->entry[ram_area].bitmap); assert(self->entry[ram_area].bitmap);
/* TODO -> better handling of nyx_fdl_state */ /* TODO -> better handling of nyx_fdl_state */
if(!test_bit(pfn, (const unsigned long*)self->entry[ram_area].bitmap)){ if (!test_bit(pfn, (const unsigned long *)self->entry[ram_area].bitmap)) {
set_bit(pfn, (unsigned long*)self->entry[ram_area].bitmap); set_bit(pfn, (unsigned long *)self->entry[ram_area].bitmap);
self->entry[ram_area].stack[self->entry[ram_area].pos] = current_addr & 0xFFFFFFFFFFFFF000; self->entry[ram_area].stack[self->entry[ram_area].pos] =
current_addr & 0xFFFFFFFFFFFFF000;
self->entry[ram_area].pos++; self->entry[ram_area].pos++;
#ifdef DEBUG_USER_FDL #ifdef DEBUG_USER_FDL
@ -159,21 +215,30 @@ void nyx_fdl_user_set(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state
} }
} }
void nyx_snapshot_nyx_fdl_user_save_root_pages(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist){ void nyx_snapshot_nyx_fdl_user_save_root_pages(nyx_fdl_user_t *self,
shadow_memory_t *shadow_memory_state,
for(uint8_t i = 0; i < self->num; i++){ snapshot_page_blocklist_t *blocklist)
{
for (uint8_t i = 0; i < self->num; i++) {
#ifdef DEBUG_USER_FDL #ifdef DEBUG_USER_FDL
printf("User -> [%d] %ld \t%ldKB\n", i, self->entry[i].pos, (0x1000*self->entry[i].pos)>>0x10); printf("User -> [%d] %ld \t%ldKB\n", i, self->entry[i].pos,
(0x1000 * self->entry[i].pos) >> 0x10);
#endif #endif
for(uint64_t j = 0; j < self->entry[i].pos; j++){ for (uint64_t j = 0; j < self->entry[i].pos; j++) {
uint64_t physical_addr = self->entry[i].stack[j]; uint64_t physical_addr = self->entry[i].stack[j];
uint64_t entry_offset_addr = physical_addr - shadow_memory_state->ram_regions[i].base; uint64_t entry_offset_addr =
physical_addr - shadow_memory_state->ram_regions[i].base;
void* host_addr = shadow_memory_state->ram_regions[i].host_region_ptr + entry_offset_addr; void *host_addr = shadow_memory_state->ram_regions[i].host_region_ptr +
void* incremental_addr = shadow_memory_state->ram_regions[i].incremental_region_ptr + entry_offset_addr; entry_offset_addr;
void *incremental_addr =
shadow_memory_state->ram_regions[i].incremental_region_ptr +
entry_offset_addr;
if(snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) == true){ if (snapshot_page_blocklist_check_phys_addr(blocklist, physical_addr) ==
true)
{
printf("%s: 0x%lx is dirty\n", __func__, physical_addr); printf("%s: 0x%lx is dirty\n", __func__, physical_addr);
continue; continue;
} }
@ -181,10 +246,10 @@ void nyx_snapshot_nyx_fdl_user_save_root_pages(nyx_fdl_user_t* self, shadow_memo
printf("%s -> %p <-- %p\n", __func__, incremental_addr, host_addr); printf("%s -> %p <-- %p\n", __func__, incremental_addr, host_addr);
#endif #endif
clear_bit(entry_offset_addr>>12, (void*)self->entry[i].bitmap); clear_bit(entry_offset_addr >> 12, (void *)self->entry[i].bitmap);
shadow_memory_track_dirty_root_pages(shadow_memory_state, entry_offset_addr, i); shadow_memory_track_dirty_root_pages(shadow_memory_state,
entry_offset_addr, i);
memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE); memcpy(incremental_addr, host_addr, TARGET_PAGE_SIZE);
} }
} }

View File

@ -1,30 +1,38 @@
#pragma once #pragma once
#include <stdint.h>
#include "nyx/snapshot/helper.h" #include "nyx/snapshot/helper.h"
#include "nyx/snapshot/memory/backend/nyx_fdl.h"
#include "nyx/snapshot/memory/block_list.h" #include "nyx/snapshot/memory/block_list.h"
#include "nyx/snapshot/memory/shadow_memory.h" #include "nyx/snapshot/memory/shadow_memory.h"
#include "nyx/snapshot/memory/backend/nyx_fdl.h" #include <stdint.h>
#define MAX_REGIONS 8 /* don't */ #define MAX_REGIONS 8 /* don't */
typedef struct nyx_fdl_user_s{ typedef struct nyx_fdl_user_s {
struct { struct {
uint64_t* stack; uint64_t *stack;
uint8_t* bitmap; uint8_t *bitmap;
uint64_t pos; uint64_t pos;
}entry[MAX_REGIONS]; } entry[MAX_REGIONS];
uint8_t num; uint8_t num;
bool enabled; bool enabled;
}nyx_fdl_user_t; } nyx_fdl_user_t;
nyx_fdl_user_t* nyx_fdl_user_init(shadow_memory_t* shadow_memory_state); nyx_fdl_user_t *nyx_fdl_user_init(shadow_memory_t *shadow_memory_state);
void nyx_fdl_user_enable(nyx_fdl_user_t* self); void nyx_fdl_user_enable(nyx_fdl_user_t *self);
void nyx_fdl_user_set(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, nyx_fdl_t* nyx_fdl_state, uint64_t addr, uint64_t length); void nyx_fdl_user_set(nyx_fdl_user_t *self,
shadow_memory_t *shadow_memory_state,
nyx_fdl_t *nyx_fdl_state,
uint64_t addr,
uint64_t length);
uint32_t nyx_snapshot_user_fdl_restore(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); uint32_t nyx_snapshot_user_fdl_restore(nyx_fdl_user_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);
void nyx_snapshot_nyx_fdl_user_save_root_pages(nyx_fdl_user_t* self, shadow_memory_t* shadow_memory_state, snapshot_page_blocklist_t* blocklist); void nyx_snapshot_nyx_fdl_user_save_root_pages(nyx_fdl_user_t *self,
shadow_memory_t *shadow_memory_state,
snapshot_page_blocklist_t *blocklist);

View File

@ -1,193 +1,218 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "qemu/main-loop.h" #include "qemu/main-loop.h"
#include "sysemu/sysemu.h"
#include "exec/ram_addr.h" #include "exec/ram_addr.h"
#include "qemu/rcu_queue.h"
#include "migration/migration.h" #include "migration/migration.h"
#include "qemu/rcu_queue.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include "nyx/snapshot/memory/shadow_memory.h"
#include "nyx/snapshot/helper.h" #include "nyx/snapshot/helper.h"
#include "nyx/snapshot/memory/shadow_memory.h"
typedef struct fast_reload_dump_head_s{ typedef struct fast_reload_dump_head_s {
uint32_t shadow_memory_regions; uint32_t shadow_memory_regions;
uint32_t ram_region_index; // remove uint32_t ram_region_index; // remove
} fast_reload_dump_head_t; } fast_reload_dump_head_t;
typedef struct fast_reload_dump_entry_s{ typedef struct fast_reload_dump_entry_s {
uint64_t shadow_memory_offset; uint64_t shadow_memory_offset;
char idstr[256]; char idstr[256];
} fast_reload_dump_entry_t; } fast_reload_dump_entry_t;
static void shadow_memory_set_incremental_ptrs(shadow_memory_t* self){ static void shadow_memory_set_incremental_ptrs(shadow_memory_t *self)
for(uint8_t i = 0; i < self->ram_regions_num; i++){ {
self->ram_regions[i].incremental_region_ptr = self->incremental_ptr + self->ram_regions[i].offset; for (uint8_t i = 0; i < self->ram_regions_num; i++) {
self->ram_regions[i].incremental_region_ptr =
self->incremental_ptr + self->ram_regions[i].offset;
} }
} }
static void shadow_memory_pre_alloc_incremental(shadow_memory_t* self){ static void shadow_memory_pre_alloc_incremental(shadow_memory_t *self)
self->incremental_ptr = mmap(0, self->memory_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, self->snapshot_ptr_fd, 0); {
self->incremental_ptr = mmap(0, self->memory_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE, self->snapshot_ptr_fd, 0);
shadow_memory_set_incremental_ptrs(self); shadow_memory_set_incremental_ptrs(self);
} }
static void shadow_memory_init_generic(shadow_memory_t* self){ static void shadow_memory_init_generic(shadow_memory_t *self)
{
self->root_track_pages_num = 0; self->root_track_pages_num = 0;
self->root_track_pages_size = 32 << 10; self->root_track_pages_size = 32 << 10;
self->root_track_pages_stack = malloc(sizeof(uint64_t)*self->root_track_pages_size); self->root_track_pages_stack =
malloc(sizeof(uint64_t) * self->root_track_pages_size);
shadow_memory_pre_alloc_incremental(self); shadow_memory_pre_alloc_incremental(self);
self->incremental_enabled = false; self->incremental_enabled = false;
} }
shadow_memory_t* shadow_memory_init(void){ shadow_memory_t *shadow_memory_init(void)
{
RAMBlock *block; RAMBlock *block;
RAMBlock* block_array[10]; RAMBlock *block_array[10];
void* snapshot_ptr_offset_array[10]; void *snapshot_ptr_offset_array[10];
shadow_memory_t* self = malloc(sizeof(shadow_memory_t)); shadow_memory_t *self = malloc(sizeof(shadow_memory_t));
memset(self, 0x0, sizeof(shadow_memory_t)); memset(self, 0x0, sizeof(shadow_memory_t));
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
self->memory_size += block->used_length; self->memory_size += block->used_length;
} }
self->snapshot_ptr_fd = memfd_create("in_memory_root_snapshot", MFD_CLOEXEC | MFD_ALLOW_SEALING); self->snapshot_ptr_fd =
memfd_create("in_memory_root_snapshot", MFD_CLOEXEC | MFD_ALLOW_SEALING);
assert(!ftruncate(self->snapshot_ptr_fd, self->memory_size)); assert(!ftruncate(self->snapshot_ptr_fd, self->memory_size));
fcntl(self->snapshot_ptr_fd, F_ADD_SEALS, F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL); fcntl(self->snapshot_ptr_fd, F_ADD_SEALS,
F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL);
self->snapshot_ptr = mmap(NULL, self->memory_size, PROT_READ | PROT_WRITE , MAP_SHARED , self->snapshot_ptr_fd, 0); self->snapshot_ptr = mmap(NULL, self->memory_size, PROT_READ | PROT_WRITE,
MAP_SHARED, self->snapshot_ptr_fd, 0);
madvise(self->snapshot_ptr, self->memory_size, MADV_RANDOM | MADV_MERGEABLE); madvise(self->snapshot_ptr, self->memory_size, MADV_RANDOM | MADV_MERGEABLE);
nyx_debug_p(RELOAD_PREFIX, "Allocating Memory (%p) Size: %lx", self->snapshot_ptr, self->memory_size); nyx_debug_p(RELOAD_PREFIX, "Allocating Memory (%p) Size: %lx",
self->snapshot_ptr, self->memory_size);
uint64_t offset = 0; uint64_t offset = 0;
uint8_t i = 0; uint8_t i = 0;
uint8_t regions_num = 0; uint8_t regions_num = 0;
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
nyx_debug_p(RELOAD_PREFIX, "%lx %lx %lx\t%s\t%p", block->offset, block->used_length, block->max_length, block->idstr, block->host); nyx_debug_p(RELOAD_PREFIX, "%lx %lx %lx\t%s\t%p", block->offset,
block->used_length, block->max_length, block->idstr, block->host);
block_array[i] = block; block_array[i] = block;
memcpy(self->snapshot_ptr+offset, block->host, block->used_length); memcpy(self->snapshot_ptr + offset, block->host, block->used_length);
snapshot_ptr_offset_array[i++] = self->snapshot_ptr+offset; snapshot_ptr_offset_array[i++] = self->snapshot_ptr + offset;
offset += block->used_length; offset += block->used_length;
regions_num++; regions_num++;
} }
for(uint8_t i = 0; i < regions_num; i++){ for (uint8_t i = 0; i < regions_num; i++) {
block = block_array[i]; block = block_array[i];
if(!block->mr->readonly){ if (!block->mr->readonly) {
if (self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START) {
if(self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START){
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = block->mr->addr; self->ram_regions[self->ram_regions_num].base = block->mr->addr;
self->ram_regions[self->ram_regions_num].size = MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].size = MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].offset = snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0]; self->ram_regions[self->ram_regions_num].offset =
snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0];
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host; self->ram_regions[self->ram_regions_num].host_region_ptr = block->host;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = self->snapshot_ptr+self->ram_regions[self->ram_regions_num].offset; self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); self->snapshot_ptr +
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].offset;
self->ram_regions[self->ram_regions_num].idstr =
malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0,
strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
self->ram_regions_num++; self->ram_regions_num++;
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = MEM_SPLIT_END; self->ram_regions[self->ram_regions_num].base =
self->ram_regions[self->ram_regions_num].size = block->used_length-MEM_SPLIT_START; MEM_SPLIT_END
self->ram_regions[self->ram_regions_num].offset = (snapshot_ptr_offset_array[i] + MEM_SPLIT_START) - snapshot_ptr_offset_array[0]; ;
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host+MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].size = block->used_length - MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = snapshot_ptr_offset_array[i]+MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].offset =
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); (snapshot_ptr_offset_array[i] + MEM_SPLIT_START) - snapshot_ptr_offset_array[0];
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].host_region_ptr =
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); block->host + MEM_SPLIT_START;
} self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
else{ snapshot_ptr_offset_array[i] + MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
}
else {
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = block->mr->addr; self->ram_regions[self->ram_regions_num].base = block->mr->addr;
self->ram_regions[self->ram_regions_num].size = block->used_length; self->ram_regions[self->ram_regions_num].size = block->used_length;
self->ram_regions[self->ram_regions_num].offset = snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0]; self->ram_regions[self->ram_regions_num].offset =
snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0];
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host; self->ram_regions[self->ram_regions_num].host_region_ptr = block->host;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = self->snapshot_ptr+self->ram_regions[self->ram_regions_num].offset; self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
self->snapshot_ptr + self->ram_regions[self->ram_regions_num].offset;
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); memset(self->ram_regions[self->ram_regions_num].idstr, 0,
strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
}
self->ram_regions_num++;
}
}
shadow_memory_init_generic(self);
return self;
} }
shadow_memory_t* shadow_memory_init_from_snapshot(const char* snapshot_folder, bool pre_snapshot){ self->ram_regions_num++;
}
}
shadow_memory_init_generic(self);
return self;
}
shadow_memory_t *shadow_memory_init_from_snapshot(const char *snapshot_folder,
bool pre_snapshot)
{
RAMBlock *block; RAMBlock *block;
RAMBlock* block_array[10]; RAMBlock *block_array[10];
void* snapshot_ptr_offset_array[10]; void *snapshot_ptr_offset_array[10];
shadow_memory_t* self = malloc(sizeof(shadow_memory_t)); shadow_memory_t *self = malloc(sizeof(shadow_memory_t));
memset(self, 0x0, sizeof(shadow_memory_t)); memset(self, 0x0, sizeof(shadow_memory_t));
/* count total memory size */ /* count total memory size */
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
self->memory_size += block->used_length; self->memory_size += block->used_length;
} }
/* count number of ram regions */ /* count number of ram regions */
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
if(!block->mr->readonly){ if (!block->mr->readonly) {
if(self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START){ if (self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START) {
self->ram_regions_num++; self->ram_regions_num++;
} }
self->ram_regions_num++; self->ram_regions_num++;
} }
} }
char* path_meta; char *path_meta;
char* path_dump; char *path_dump;
assert(asprintf(&path_meta, "%s/fast_snapshot.mem_meta", snapshot_folder) != -1); assert(asprintf(&path_meta, "%s/fast_snapshot.mem_meta", snapshot_folder) != -1);
assert(asprintf(&path_dump, "%s/fast_snapshot.mem_dump", snapshot_folder) != -1); assert(asprintf(&path_dump, "%s/fast_snapshot.mem_dump", snapshot_folder) != -1);
fast_reload_dump_head_t head; fast_reload_dump_head_t head;
FILE* file_mem_meta = fopen (path_meta, "r"); FILE *file_mem_meta = fopen(path_meta, "r");
assert(file_mem_meta != NULL); assert(file_mem_meta != NULL);
assert(fread(&head, sizeof(fast_reload_dump_head_t), 1, file_mem_meta) == 1); assert(fread(&head, sizeof(fast_reload_dump_head_t), 1, file_mem_meta) == 1);
fclose(file_mem_meta); fclose(file_mem_meta);
if(self->ram_regions_num != head.shadow_memory_regions){ if (self->ram_regions_num != head.shadow_memory_regions) {
nyx_error("Error: self->ram_regions_num (%d) != head.shadow_memory_regions (%d)\n", self->ram_regions_num, head.shadow_memory_regions); nyx_error(
"Error: self->ram_regions_num (%d) != head.shadow_memory_regions (%d)\n",
self->ram_regions_num, head.shadow_memory_regions);
exit(1); exit(1);
} }
//printf("LOAD -> self->ram_regions_num: %d\n", self->ram_regions_num); // printf("LOAD -> self->ram_regions_num: %d\n", self->ram_regions_num);
FILE* file_mem_dump = fopen (path_dump, "r"); FILE *file_mem_dump = fopen(path_dump, "r");
assert(file_mem_dump != NULL); assert(file_mem_dump != NULL);
fseek(file_mem_dump, 0L, SEEK_END); fseek(file_mem_dump, 0L, SEEK_END);
uint64_t file_mem_dump_size = ftell(file_mem_dump); uint64_t file_mem_dump_size = ftell(file_mem_dump);
nyx_debug("guest_ram_size == ftell(f) => 0x%lx vs 0x%lx (%s)\n", self->memory_size, file_mem_dump_size, path_dump); nyx_debug("guest_ram_size == ftell(f) => 0x%lx vs 0x%lx (%s)\n",
self->memory_size, file_mem_dump_size, path_dump);
#define VGA_SIZE (16<<20) #define VGA_SIZE (16 << 20)
if(self->memory_size != file_mem_dump_size){ if (self->memory_size != file_mem_dump_size) {
if (file_mem_dump_size >= VGA_SIZE){ if (file_mem_dump_size >= VGA_SIZE) {
nyx_error("ERROR: guest size should be %ld MB - set it to %ld MB\n", (file_mem_dump_size-VGA_SIZE)>>20, (self->memory_size-VGA_SIZE)>>20); nyx_error("ERROR: guest size should be %ld MB - set it to %ld MB\n",
(file_mem_dump_size - VGA_SIZE) >> 20,
(self->memory_size - VGA_SIZE) >> 20);
exit(1); exit(1);
} } else {
else{
nyx_error("ERROR: guest size: %ld bytes\n", file_mem_dump_size); nyx_error("ERROR: guest size: %ld bytes\n", file_mem_dump_size);
exit(1); exit(1);
} }
@ -197,116 +222,137 @@ shadow_memory_t* shadow_memory_init_from_snapshot(const char* snapshot_folder, b
fclose(file_mem_dump); fclose(file_mem_dump);
self->snapshot_ptr_fd = open(path_dump, O_RDONLY); self->snapshot_ptr_fd = open(path_dump, O_RDONLY);
self->snapshot_ptr = mmap(0, self->memory_size, PROT_READ, MAP_SHARED, self->snapshot_ptr_fd, 0); self->snapshot_ptr =
mmap(0, self->memory_size, PROT_READ, MAP_SHARED, self->snapshot_ptr_fd, 0);
assert(self->snapshot_ptr != (void*)-1); assert(self->snapshot_ptr != (void *)-1);
madvise(self->snapshot_ptr, self->memory_size, MADV_MERGEABLE); madvise(self->snapshot_ptr, self->memory_size, MADV_MERGEABLE);
uint64_t offset = 0; uint64_t offset = 0;
uint8_t i = 0; uint8_t i = 0;
uint8_t regions_num = 0; uint8_t regions_num = 0;
QLIST_FOREACH_RCU(block, &ram_list.blocks, next) { QLIST_FOREACH_RCU (block, &ram_list.blocks, next) {
nyx_debug_p(RELOAD_PREFIX, "%lx %lx %lx\t%s\t%p", block->offset, block->used_length, block->max_length, block->idstr, block->host); nyx_debug_p(RELOAD_PREFIX, "%lx %lx %lx\t%s\t%p", block->offset,
block->used_length, block->max_length, block->idstr, block->host);
block_array[i] = block; block_array[i] = block;
snapshot_ptr_offset_array[i++] = self->snapshot_ptr+offset; snapshot_ptr_offset_array[i++] = self->snapshot_ptr + offset;
offset += block->used_length; offset += block->used_length;
regions_num++; regions_num++;
} }
self->ram_regions_num = 0; self->ram_regions_num = 0;
for(uint8_t i = 0; i < regions_num; i++){ for (uint8_t i = 0; i < regions_num; i++) {
block = block_array[i]; block = block_array[i];
if(!block->mr->readonly){ if (!block->mr->readonly) {
if (self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START) {
if(self->ram_regions_num == 0 && block->used_length >= MEM_SPLIT_START){
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = block->mr->addr; self->ram_regions[self->ram_regions_num].base = block->mr->addr;
self->ram_regions[self->ram_regions_num].size = MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].size = MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].offset = snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0]; self->ram_regions[self->ram_regions_num].offset =
snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0];
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host; self->ram_regions[self->ram_regions_num].host_region_ptr = block->host;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = self->snapshot_ptr+self->ram_regions[self->ram_regions_num].offset; self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); self->snapshot_ptr +
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].offset;
self->ram_regions[self->ram_regions_num].idstr =
malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0,
strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
self->ram_regions_num++; self->ram_regions_num++;
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = MEM_SPLIT_END; self->ram_regions[self->ram_regions_num].base =
self->ram_regions[self->ram_regions_num].size = block->used_length-MEM_SPLIT_START; MEM_SPLIT_END
self->ram_regions[self->ram_regions_num].offset = (snapshot_ptr_offset_array[i] + MEM_SPLIT_START) - snapshot_ptr_offset_array[0]; ;
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host+MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].size = block->used_length - MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = snapshot_ptr_offset_array[i]+MEM_SPLIT_START; self->ram_regions[self->ram_regions_num].offset =
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); (snapshot_ptr_offset_array[i] + MEM_SPLIT_START) - snapshot_ptr_offset_array[0];
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].host_region_ptr =
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); block->host + MEM_SPLIT_START;
} self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
else{ snapshot_ptr_offset_array[i] + MEM_SPLIT_START;
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
}
else {
self->ram_regions[self->ram_regions_num].ram_region = i; self->ram_regions[self->ram_regions_num].ram_region = i;
self->ram_regions[self->ram_regions_num].base = block->mr->addr; self->ram_regions[self->ram_regions_num].base = block->mr->addr;
self->ram_regions[self->ram_regions_num].size = block->used_length; self->ram_regions[self->ram_regions_num].size = block->used_length;
self->ram_regions[self->ram_regions_num].offset = snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0]; self->ram_regions[self->ram_regions_num].offset =
snapshot_ptr_offset_array[i] - snapshot_ptr_offset_array[0];
self->ram_regions[self->ram_regions_num].host_region_ptr = block->host; self->ram_regions[self->ram_regions_num].host_region_ptr = block->host;
self->ram_regions[self->ram_regions_num].snapshot_region_ptr = self->snapshot_ptr+self->ram_regions[self->ram_regions_num].offset; self->ram_regions[self->ram_regions_num].snapshot_region_ptr =
self->snapshot_ptr + self->ram_regions[self->ram_regions_num].offset;
self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1); self->ram_regions[self->ram_regions_num].idstr = malloc(strlen(block->idstr) + 1);
memset(self->ram_regions[self->ram_regions_num].idstr, 0, strlen(block->idstr) + 1); memset(self->ram_regions[self->ram_regions_num].idstr, 0,
strlen(block->idstr) + 1);
strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr); strcpy(self->ram_regions[self->ram_regions_num].idstr, block->idstr);
} }
self->ram_regions_num++; self->ram_regions_num++;
} }
} }
#ifdef DEBUG_SHADOW_MEMCPY_VERSION #ifdef DEBUG_SHADOW_MEMCPY_VERSION
/* memcpy version */ /* memcpy version */
for(uint8_t i = 0; i < self->ram_regions_num; i++){ for (uint8_t i = 0; i < self->ram_regions_num; i++) {
void* host_addr = self->ram_regions[i].host_region_ptr + 0; void *host_addr = self->ram_regions[i].host_region_ptr + 0;
void* snapshot_addr = self->ram_regions[i].snapshot_region_ptr + 0; void *snapshot_addr = self->ram_regions[i].snapshot_region_ptr + 0;
memcpy(host_addr, snapshot_addr, self->ram_regions[i].size); memcpy(host_addr, snapshot_addr, self->ram_regions[i].size);
} }
#else #else
/* munmap + mmap version */ /* munmap + mmap version */
for(uint8_t i = 0; i < self->ram_regions_num; i++){ for (uint8_t i = 0; i < self->ram_regions_num; i++) {
void* host_addr = self->ram_regions[i].host_region_ptr + 0; void *host_addr = self->ram_regions[i].host_region_ptr + 0;
assert(munmap(host_addr, self->ram_regions[i].size) != EINVAL); assert(munmap(host_addr, self->ram_regions[i].size) != EINVAL);
assert(mmap(host_addr, self->ram_regions[i].size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED, self->snapshot_ptr_fd, self->ram_regions[i].offset) != MAP_FAILED); assert(mmap(host_addr, self->ram_regions[i].size,
} PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_FIXED,
self->snapshot_ptr_fd, self->ram_regions[i].offset) != MAP_FAILED);
}
#endif #endif
shadow_memory_init_generic(self); shadow_memory_init_generic(self);
return self; return self;
} }
void shadow_memory_prepare_incremental(shadow_memory_t* self){ void shadow_memory_prepare_incremental(shadow_memory_t *self)
{
static int count = 0; static int count = 0;
if(count >= RESTORE_RATE){ if (count >= RESTORE_RATE) {
count = 0; count = 0;
munmap(self->incremental_ptr, self->memory_size); munmap(self->incremental_ptr, self->memory_size);
self->incremental_ptr = mmap(0, self->memory_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, self->snapshot_ptr_fd, 0); self->incremental_ptr = mmap(0, self->memory_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE, self->snapshot_ptr_fd, 0);
shadow_memory_set_incremental_ptrs(self); shadow_memory_set_incremental_ptrs(self);
} }
count++; count++;
} }
void shadow_memory_switch_snapshot(shadow_memory_t* self, bool incremental){ void shadow_memory_switch_snapshot(shadow_memory_t *self, bool incremental)
{
self->incremental_enabled = incremental; self->incremental_enabled = incremental;
} }
void shadow_memory_restore_memory(shadow_memory_t* self){ void shadow_memory_restore_memory(shadow_memory_t *self)
{
rcu_read_lock(); rcu_read_lock();
uint8_t slot = 0; uint8_t slot = 0;
uint64_t addr = 0; uint64_t addr = 0;
for(uint64_t i = 0; i < self->root_track_pages_num; i++){ for (uint64_t i = 0; i < self->root_track_pages_num; i++) {
addr = self->root_track_pages_stack[i] & 0xFFFFFFFFFFFFF000; addr = self->root_track_pages_stack[i] & 0xFFFFFFFFFFFFF000;
slot = self->root_track_pages_stack[i] & 0xFFF; slot = self->root_track_pages_stack[i] & 0xFFF;
memcpy(self->ram_regions[slot].host_region_ptr+addr, self->ram_regions[slot].snapshot_region_ptr+addr, TARGET_PAGE_SIZE); memcpy(self->ram_regions[slot].host_region_ptr + addr,
memcpy(self->ram_regions[slot].incremental_region_ptr+addr, self->ram_regions[slot].snapshot_region_ptr+addr, TARGET_PAGE_SIZE); self->ram_regions[slot].snapshot_region_ptr + addr, TARGET_PAGE_SIZE);
memcpy(self->ram_regions[slot].incremental_region_ptr + addr,
self->ram_regions[slot].snapshot_region_ptr + addr, TARGET_PAGE_SIZE);
} }
self->root_track_pages_num = 0; self->root_track_pages_num = 0;
@ -315,25 +361,29 @@ void shadow_memory_restore_memory(shadow_memory_t* self){
/* only used in debug mode -> no need to be fast */ /* only used in debug mode -> no need to be fast */
bool shadow_memory_is_root_page_tracked(shadow_memory_t* self, uint64_t address, uint8_t slot){ bool shadow_memory_is_root_page_tracked(shadow_memory_t *self,
uint64_t address,
uint8_t slot)
{
uint64_t value = (address & 0xFFFFFFFFFFFFF000) | slot; uint64_t value = (address & 0xFFFFFFFFFFFFF000) | slot;
for(uint64_t i = 0; i < self->root_track_pages_num; i++){ for (uint64_t i = 0; i < self->root_track_pages_num; i++) {
if(self->root_track_pages_stack[i] == value){ if (self->root_track_pages_stack[i] == value) {
return true; return true;
} }
} }
return false; return false;
} }
void shadow_memory_serialize(shadow_memory_t* self, const char* snapshot_folder){ void shadow_memory_serialize(shadow_memory_t *self, const char *snapshot_folder)
char* tmp1; {
char* tmp2; char *tmp1;
char *tmp2;
assert(asprintf(&tmp1, "%s/fast_snapshot.mem_meta", snapshot_folder) != -1); assert(asprintf(&tmp1, "%s/fast_snapshot.mem_meta", snapshot_folder) != -1);
assert(asprintf(&tmp2, "%s/fast_snapshot.mem_dump", snapshot_folder) != -1); assert(asprintf(&tmp2, "%s/fast_snapshot.mem_dump", snapshot_folder) != -1);
FILE* file_mem_meta = fopen(tmp1, "w+b"); FILE *file_mem_meta = fopen(tmp1, "w+b");
FILE* file_mem_data = fopen(tmp2, "w+b"); FILE *file_mem_data = fopen(tmp2, "w+b");
fast_reload_dump_head_t head; fast_reload_dump_head_t head;
fast_reload_dump_entry_t entry; fast_reload_dump_entry_t entry;
@ -343,10 +393,10 @@ void shadow_memory_serialize(shadow_memory_t* self, const char* snapshot_folder)
fwrite(&head, sizeof(fast_reload_dump_head_t), 1, file_mem_meta); fwrite(&head, sizeof(fast_reload_dump_head_t), 1, file_mem_meta);
for (uint64_t i = 0; i < self->ram_regions_num; i++){ for (uint64_t i = 0; i < self->ram_regions_num; i++) {
memset(&entry, 0x0, sizeof(fast_reload_dump_entry_t)); memset(&entry, 0x0, sizeof(fast_reload_dump_entry_t));
entry.shadow_memory_offset = (uint64_t)self->ram_regions[i].offset; entry.shadow_memory_offset = (uint64_t)self->ram_regions[i].offset;
strncpy((char*)&entry.idstr, (const char*)self->ram_regions[i].idstr, 255); strncpy((char *)&entry.idstr, (const char *)self->ram_regions[i].idstr, 255);
fwrite(&entry, sizeof(fast_reload_dump_entry_t), 1, file_mem_meta); fwrite(&entry, sizeof(fast_reload_dump_entry_t), 1, file_mem_meta);
} }
@ -356,43 +406,57 @@ void shadow_memory_serialize(shadow_memory_t* self, const char* snapshot_folder)
fclose(file_mem_data); fclose(file_mem_data);
} }
static bool shadow_memory_read_page_frame(shadow_memory_t* self, uint64_t address, void* ptr, uint16_t offset, uint16_t size){ static bool shadow_memory_read_page_frame(shadow_memory_t *self,
uint64_t address,
void *ptr,
uint16_t offset,
uint16_t size)
{
assert((offset + size) <= 0x1000); assert((offset + size) <= 0x1000);
for(uint8_t i = 0; i < self->ram_regions_num; i++){ for (uint8_t i = 0; i < self->ram_regions_num; i++) {
if(address >= self->ram_regions[i].base && address < (self->ram_regions[i].base + self->ram_regions[i].size)){ if (address >= self->ram_regions[i].base &&
void* snapshot_ptr = self->ram_regions[i].snapshot_region_ptr + (address-self->ram_regions[i].base); address < (self->ram_regions[i].base + self->ram_regions[i].size))
memcpy(ptr, snapshot_ptr+offset, size); {
void *snapshot_ptr = self->ram_regions[i].snapshot_region_ptr +
(address - self->ram_regions[i].base);
memcpy(ptr, snapshot_ptr + offset, size);
return true; return true;
} }
} }
return false; return false;
} }
bool shadow_memory_read_physical_memory(shadow_memory_t* self, uint64_t address, void* ptr, size_t size){ bool shadow_memory_read_physical_memory(shadow_memory_t *self,
uint64_t address,
void *ptr,
size_t size)
{
size_t bytes_left = size; size_t bytes_left = size;
size_t copy_bytes = 0; size_t copy_bytes = 0;
uint64_t current_address = address; uint64_t current_address = address;
uint64_t offset = 0; uint64_t offset = 0;
while (bytes_left != 0) { while (bytes_left != 0) {
/* full page */ /* full page */
if ((current_address & 0xFFF) == 0){ if ((current_address & 0xFFF) == 0) {
copy_bytes = 0x1000; copy_bytes = 0x1000;
} }
/* partial page (starting at an offset) */ /* partial page (starting at an offset) */
else { else
{
copy_bytes = 0x1000 - (current_address & 0xFFF); copy_bytes = 0x1000 - (current_address & 0xFFF);
} }
/* partial page */ /* partial page */
if (bytes_left < copy_bytes){ if (bytes_left < copy_bytes) {
copy_bytes = bytes_left; copy_bytes = bytes_left;
} }
if (shadow_memory_read_page_frame(self, current_address & ~0xFFFULL, ptr + offset, current_address & 0xFFFULL, copy_bytes) == false){ if (shadow_memory_read_page_frame(self, current_address & ~0xFFFULL,
ptr + offset, current_address & 0xFFFULL,
copy_bytes) == false)
{
return false; return false;
} }
current_address += copy_bytes; current_address += copy_bytes;

View File

@ -1,13 +1,12 @@
#pragma once #pragma once
#include <stdint.h>
#include "nyx/snapshot/devices/state_reallocation.h" #include "nyx/snapshot/devices/state_reallocation.h"
#include <stdint.h>
/* munmap & mmap incremental snapshot area after RESTORE_RATE restores to avoid high memory pressure */ /* munmap & mmap incremental snapshot area after RESTORE_RATE restores to avoid high memory pressure */
#define RESTORE_RATE 2000 #define RESTORE_RATE 2000
typedef struct ram_region_s{ typedef struct ram_region_s {
/* simple numeric identifier /* simple numeric identifier
* (can be the same for multiple regions if the memory is * (can be the same for multiple regions if the memory is
* actually splitted across different bases in the guest's memory * actually splitted across different bases in the guest's memory
@ -25,30 +24,30 @@ typedef struct ram_region_s{
uint64_t offset; uint64_t offset;
/* pointer to the actual mmap region used by KVM */ /* pointer to the actual mmap region used by KVM */
void* host_region_ptr; void *host_region_ptr;
/* pointer to the snapshot mmap + offset */ /* pointer to the snapshot mmap + offset */
void* snapshot_region_ptr; void *snapshot_region_ptr;
/* pointer to the incremental CoW mmap + offset */ /* pointer to the incremental CoW mmap + offset */
void* incremental_region_ptr; void *incremental_region_ptr;
char* idstr; char *idstr;
} ram_region_t; } ram_region_t;
typedef struct shadow_memory_s{ typedef struct shadow_memory_s {
/* snapshot memory backup */ /* snapshot memory backup */
void* snapshot_ptr; void *snapshot_ptr;
/* snapshot memory backup memfd */ /* snapshot memory backup memfd */
int snapshot_ptr_fd; int snapshot_ptr_fd;
/* incremental memory backup */ /* incremental memory backup */
void* incremental_ptr; void *incremental_ptr;
//fast_reload_tmp_snapshot_t tmp_snapshot; // fast_reload_tmp_snapshot_t tmp_snapshot;
/* total memory size */ /* total memory size */
uint64_t memory_size; uint64_t memory_size;
@ -60,31 +59,43 @@ typedef struct shadow_memory_s{
/* additional dirty stack to restore root snapshot */ /* additional dirty stack to restore root snapshot */
uint64_t root_track_pages_num; uint64_t root_track_pages_num;
uint64_t root_track_pages_size; uint64_t root_track_pages_size;
uint64_t* root_track_pages_stack; uint64_t *root_track_pages_stack;
bool incremental_enabled; bool incremental_enabled;
}shadow_memory_t; } shadow_memory_t;
shadow_memory_t* shadow_memory_init(void); shadow_memory_t *shadow_memory_init(void);
shadow_memory_t* shadow_memory_init_from_snapshot(const char* snapshot_folder, bool pre_snapshot); shadow_memory_t *shadow_memory_init_from_snapshot(const char *snapshot_folder,
bool pre_snapshot);
void shadow_memory_prepare_incremental(shadow_memory_t* self); void shadow_memory_prepare_incremental(shadow_memory_t *self);
void shadow_memory_switch_snapshot(shadow_memory_t* self, bool incremental); void shadow_memory_switch_snapshot(shadow_memory_t *self, bool incremental);
void shadow_memory_restore_memory(shadow_memory_t* self); void shadow_memory_restore_memory(shadow_memory_t *self);
static inline void shadow_memory_track_dirty_root_pages(shadow_memory_t* self, uint64_t address, uint8_t slot){ static inline void shadow_memory_track_dirty_root_pages(shadow_memory_t *self,
if(unlikely(self->root_track_pages_num >= self->root_track_pages_size)){ uint64_t address,
uint8_t slot)
{
if (unlikely(self->root_track_pages_num >= self->root_track_pages_size)) {
self->root_track_pages_size <<= 2; self->root_track_pages_size <<= 2;
self->root_track_pages_stack = realloc(self->root_track_pages_stack, self->root_track_pages_size*sizeof(uint64_t)); self->root_track_pages_stack =
realloc(self->root_track_pages_stack,
self->root_track_pages_size * sizeof(uint64_t));
} }
self->root_track_pages_stack[self->root_track_pages_num] = (address & 0xFFFFFFFFFFFFF000) | slot; self->root_track_pages_stack[self->root_track_pages_num] =
(address & 0xFFFFFFFFFFFFF000) | slot;
self->root_track_pages_num++; self->root_track_pages_num++;
} }
bool shadow_memory_is_root_page_tracked(shadow_memory_t* self, uint64_t address, uint8_t slot); bool shadow_memory_is_root_page_tracked(shadow_memory_t *self,
uint64_t address,
uint8_t slot);
void shadow_memory_serialize(shadow_memory_t* self, const char* snapshot_folder); void shadow_memory_serialize(shadow_memory_t *self, const char *snapshot_folder);
bool shadow_memory_read_physical_memory(shadow_memory_t* self, uint64_t address, void* ptr, size_t size); bool shadow_memory_read_physical_memory(shadow_memory_t *self,
uint64_t address,
void *ptr,
size_t size);

View File

@ -3,50 +3,52 @@
#include "sysemu/cpus.h" #include "sysemu/cpus.h"
#include "nyx/state/snapshot_state.h" #include "nyx/state/snapshot_state.h"
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/state/state.h"
#include "nyx/memory_access.h" #include "nyx/memory_access.h"
#include <stdio.h> #include "nyx/state/state.h"
#include <stdint.h> #include <stdint.h>
#include <stdio.h>
void serialize_state(const char* filename_prefix, bool is_pre_snapshot){ void serialize_state(const char *filename_prefix, bool is_pre_snapshot)
{
nyx_trace(); nyx_trace();
char* tmp; char *tmp;
assert(asprintf(&tmp, "%s/global.state", filename_prefix) != -1); assert(asprintf(&tmp, "%s/global.state", filename_prefix) != -1);
FILE *fp = fopen(tmp, "wb"); FILE *fp = fopen(tmp, "wb");
if(fp == NULL) { if (fp == NULL) {
nyx_error("[%s] Could not open file %s.\n", __func__, tmp); nyx_error("[%s] Could not open file %s.\n", __func__, tmp);
assert(false); assert(false);
} }
serialized_state_header_t header = {0}; serialized_state_header_t header = { 0 };
header.magic = NYX_SERIALIZED_STATE_MAGIC; header.magic = NYX_SERIALIZED_STATE_MAGIC;
header.version = NYX_SERIALIZED_STATE_VERSION; header.version = NYX_SERIALIZED_STATE_VERSION;
if (is_pre_snapshot){ if (is_pre_snapshot) {
header.type = NYX_SERIALIZED_TYPE_PRE_SNAPSHOT; header.type = NYX_SERIALIZED_TYPE_PRE_SNAPSHOT;
fwrite(&header, sizeof(serialized_state_header_t), 1, fp); fwrite(&header, sizeof(serialized_state_header_t), 1, fp);
} } else {
else{
header.type = NYX_SERIALIZED_TYPE_ROOT_SNAPSHOT; header.type = NYX_SERIALIZED_TYPE_ROOT_SNAPSHOT;
fwrite(&header, sizeof(serialized_state_header_t), 1, fp); fwrite(&header, sizeof(serialized_state_header_t), 1, fp);
qemu_nyx_state_t* nyx_global_state = GET_GLOBAL_STATE(); qemu_nyx_state_t *nyx_global_state = GET_GLOBAL_STATE();
serialized_state_root_snapshot_t root_snapshot = {0}; serialized_state_root_snapshot_t root_snapshot = { 0 };
for (uint8_t i = 0; i < 4; i++){ for (uint8_t i = 0; i < 4; i++) {
root_snapshot.pt_ip_filter_configured[i] = nyx_global_state->pt_ip_filter_configured[i]; root_snapshot.pt_ip_filter_configured[i] =
nyx_global_state->pt_ip_filter_configured[i];
root_snapshot.pt_ip_filter_a[i] = nyx_global_state->pt_ip_filter_a[i]; root_snapshot.pt_ip_filter_a[i] = nyx_global_state->pt_ip_filter_a[i];
root_snapshot.pt_ip_filter_b[i] = nyx_global_state->pt_ip_filter_b[i]; root_snapshot.pt_ip_filter_b[i] = nyx_global_state->pt_ip_filter_b[i];
} }
root_snapshot.parent_cr3 = nyx_global_state->parent_cr3; root_snapshot.parent_cr3 = nyx_global_state->parent_cr3;
root_snapshot.disassembler_word_width = nyx_global_state->disassembler_word_width; root_snapshot.disassembler_word_width =
nyx_global_state->disassembler_word_width;
root_snapshot.fast_reload_pre_image = nyx_global_state->fast_reload_pre_image; root_snapshot.fast_reload_pre_image = nyx_global_state->fast_reload_pre_image;
root_snapshot.mem_mode = nyx_global_state->mem_mode; root_snapshot.mem_mode = nyx_global_state->mem_mode;
root_snapshot.pt_trace_mode =nyx_global_state->pt_trace_mode; root_snapshot.pt_trace_mode = nyx_global_state->pt_trace_mode;
root_snapshot.input_buffer_vaddr = nyx_global_state->payload_buffer; root_snapshot.input_buffer_vaddr = nyx_global_state->payload_buffer;
root_snapshot.protect_input_buffer = nyx_global_state->protect_payload_buffer; root_snapshot.protect_input_buffer = nyx_global_state->protect_payload_buffer;
@ -55,60 +57,66 @@ void serialize_state(const char* filename_prefix, bool is_pre_snapshot){
root_snapshot.cap_timeout_detection = nyx_global_state->cap_timeout_detection; root_snapshot.cap_timeout_detection = nyx_global_state->cap_timeout_detection;
root_snapshot.cap_only_reload_mode = nyx_global_state->cap_only_reload_mode; root_snapshot.cap_only_reload_mode = nyx_global_state->cap_only_reload_mode;
root_snapshot.cap_compile_time_tracing = nyx_global_state->cap_compile_time_tracing; root_snapshot.cap_compile_time_tracing =
nyx_global_state->cap_compile_time_tracing;
root_snapshot.cap_ijon_tracing = nyx_global_state->cap_ijon_tracing; root_snapshot.cap_ijon_tracing = nyx_global_state->cap_ijon_tracing;
root_snapshot.cap_cr3 = nyx_global_state->cap_cr3; root_snapshot.cap_cr3 = nyx_global_state->cap_cr3;
root_snapshot.cap_compile_time_tracing_buffer_vaddr = nyx_global_state->cap_compile_time_tracing_buffer_vaddr; root_snapshot.cap_compile_time_tracing_buffer_vaddr =
root_snapshot.cap_ijon_tracing_buffer_vaddr = nyx_global_state->cap_ijon_tracing_buffer_vaddr; nyx_global_state->cap_compile_time_tracing_buffer_vaddr;
root_snapshot.cap_coverage_bitmap_size = nyx_global_state->cap_coverage_bitmap_size; root_snapshot.cap_ijon_tracing_buffer_vaddr =
nyx_global_state->cap_ijon_tracing_buffer_vaddr;
root_snapshot.cap_coverage_bitmap_size =
nyx_global_state->cap_coverage_bitmap_size;
fwrite(&root_snapshot, sizeof(serialized_state_root_snapshot_t), 1, fp); fwrite(&root_snapshot, sizeof(serialized_state_root_snapshot_t), 1, fp);
} }
fclose(fp); fclose(fp);
free(tmp); free(tmp);
} }
void deserialize_state(const char* filename_prefix){ void deserialize_state(const char *filename_prefix)
{
nyx_trace(); nyx_trace();
char* tmp; char *tmp;
assert(asprintf(&tmp, "%s/global.state", filename_prefix) != -1); assert(asprintf(&tmp, "%s/global.state", filename_prefix) != -1);
FILE *fp = fopen(tmp, "rb"); FILE *fp = fopen(tmp, "rb");
if(fp == NULL) { if (fp == NULL) {
nyx_debug("[%s] Could not open file %s.\n", __func__, tmp); nyx_debug("[%s] Could not open file %s.\n", __func__, tmp);
assert(false); assert(false);
} }
serialized_state_header_t header = {0}; serialized_state_header_t header = { 0 };
assert(fread(&header, sizeof(serialized_state_header_t), 1, fp) == 1); assert(fread(&header, sizeof(serialized_state_header_t), 1, fp) == 1);
assert(header.magic == NYX_SERIALIZED_STATE_MAGIC); assert(header.magic == NYX_SERIALIZED_STATE_MAGIC);
assert(header.version == NYX_SERIALIZED_STATE_VERSION); assert(header.version == NYX_SERIALIZED_STATE_VERSION);
if(header.type == NYX_SERIALIZED_TYPE_PRE_SNAPSHOT){ if (header.type == NYX_SERIALIZED_TYPE_PRE_SNAPSHOT) {
/* we're done here */ /* we're done here */
} } else if (header.type == NYX_SERIALIZED_TYPE_ROOT_SNAPSHOT) {
else if (header.type == NYX_SERIALIZED_TYPE_ROOT_SNAPSHOT){ qemu_nyx_state_t *nyx_global_state = GET_GLOBAL_STATE();
qemu_nyx_state_t* nyx_global_state = GET_GLOBAL_STATE(); serialized_state_root_snapshot_t root_snapshot = { 0 };
serialized_state_root_snapshot_t root_snapshot = {0}; assert(fread(&root_snapshot, sizeof(serialized_state_root_snapshot_t), 1,
assert(fread(&root_snapshot, sizeof(serialized_state_root_snapshot_t), 1, fp) == 1); fp) == 1);
for (uint8_t i = 0; i < 4; i++){ for (uint8_t i = 0; i < 4; i++) {
nyx_global_state->pt_ip_filter_configured[i] = root_snapshot.pt_ip_filter_configured[i]; nyx_global_state->pt_ip_filter_configured[i] =
root_snapshot.pt_ip_filter_configured[i];
nyx_global_state->pt_ip_filter_a[i] = root_snapshot.pt_ip_filter_a[i]; nyx_global_state->pt_ip_filter_a[i] = root_snapshot.pt_ip_filter_a[i];
nyx_global_state->pt_ip_filter_b[i] = root_snapshot.pt_ip_filter_b[i]; nyx_global_state->pt_ip_filter_b[i] = root_snapshot.pt_ip_filter_b[i];
} }
nyx_global_state->parent_cr3 = root_snapshot.parent_cr3; nyx_global_state->parent_cr3 = root_snapshot.parent_cr3;
nyx_global_state->disassembler_word_width = root_snapshot.disassembler_word_width; nyx_global_state->disassembler_word_width =
root_snapshot.disassembler_word_width;
nyx_global_state->fast_reload_pre_image = root_snapshot.fast_reload_pre_image; nyx_global_state->fast_reload_pre_image = root_snapshot.fast_reload_pre_image;
nyx_global_state->mem_mode = root_snapshot.mem_mode; nyx_global_state->mem_mode = root_snapshot.mem_mode;
nyx_global_state->pt_trace_mode =root_snapshot.pt_trace_mode; nyx_global_state->pt_trace_mode = root_snapshot.pt_trace_mode;
nyx_global_state->payload_buffer = root_snapshot.input_buffer_vaddr; nyx_global_state->payload_buffer = root_snapshot.input_buffer_vaddr;
nyx_global_state->protect_payload_buffer = root_snapshot.protect_input_buffer; nyx_global_state->protect_payload_buffer = root_snapshot.protect_input_buffer;
@ -117,21 +125,25 @@ void deserialize_state(const char* filename_prefix){
nyx_global_state->cap_timeout_detection = root_snapshot.cap_timeout_detection; nyx_global_state->cap_timeout_detection = root_snapshot.cap_timeout_detection;
nyx_global_state->cap_only_reload_mode = root_snapshot.cap_only_reload_mode; nyx_global_state->cap_only_reload_mode = root_snapshot.cap_only_reload_mode;
nyx_global_state->cap_compile_time_tracing = root_snapshot.cap_compile_time_tracing; nyx_global_state->cap_compile_time_tracing =
root_snapshot.cap_compile_time_tracing;
nyx_global_state->cap_ijon_tracing = root_snapshot.cap_ijon_tracing; nyx_global_state->cap_ijon_tracing = root_snapshot.cap_ijon_tracing;
nyx_global_state->cap_cr3 = root_snapshot.cap_cr3; nyx_global_state->cap_cr3 = root_snapshot.cap_cr3;
nyx_global_state->cap_compile_time_tracing_buffer_vaddr = root_snapshot.cap_compile_time_tracing_buffer_vaddr; nyx_global_state->cap_compile_time_tracing_buffer_vaddr =
nyx_global_state->cap_ijon_tracing_buffer_vaddr = root_snapshot.cap_ijon_tracing_buffer_vaddr; root_snapshot.cap_compile_time_tracing_buffer_vaddr;
nyx_global_state->cap_coverage_bitmap_size = root_snapshot.cap_coverage_bitmap_size; nyx_global_state->cap_ijon_tracing_buffer_vaddr =
root_snapshot.cap_ijon_tracing_buffer_vaddr;
nyx_global_state->cap_coverage_bitmap_size =
root_snapshot.cap_coverage_bitmap_size;
assert(apply_capabilities(qemu_get_cpu(0))); assert(apply_capabilities(qemu_get_cpu(0)));
remap_payload_buffer(nyx_global_state->payload_buffer, ((CPUState *)qemu_get_cpu(0)) ); remap_payload_buffer(nyx_global_state->payload_buffer,
((CPUState *)qemu_get_cpu(0)));
/* makes sure that we are allowed to enter the fuzzing loop */ /* makes sure that we are allowed to enter the fuzzing loop */
nyx_global_state->get_host_config_done = true; nyx_global_state->get_host_config_done = true;
nyx_global_state->set_agent_config_done = true; nyx_global_state->set_agent_config_done = true;
} } else {
else{
fprintf(stderr, "[QEMU-Nyx]: this feature is currently missing\n"); fprintf(stderr, "[QEMU-Nyx]: this feature is currently missing\n");
abort(); abort();
} }

View File

@ -42,6 +42,5 @@ typedef struct serialized_state_root_snapshot_s {
} serialized_state_root_snapshot_t; } serialized_state_root_snapshot_t;
void serialize_state(const char *filename_prefix, bool is_pre_snapshot);
void serialize_state(const char* filename_prefix, bool is_pre_snapshot); void deserialize_state(const char *filename_prefix);
void deserialize_state(const char* filename_prefix);

View File

@ -24,23 +24,24 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#include <stdint.h> #include <stdint.h>
#include <stdio.h> #include <stdio.h>
#include "nyx/state/state.h"
#include "nyx/debug.h"
#include "nyx/memory_access.h"
#include "sysemu/kvm.h" #include "sysemu/kvm.h"
#include "nyx/auxiliary_buffer.h" #include "nyx/auxiliary_buffer.h"
#include "nyx/sharedir.h" #include "nyx/debug.h"
#include "nyx/fast_vm_reload_sync.h" #include "nyx/fast_vm_reload_sync.h"
#include "nyx/helpers.h" #include "nyx/helpers.h"
#include "nyx/memory_access.h"
#include "nyx/sharedir.h"
#include "nyx/state/state.h"
//#define STATE_VERBOSE // #define STATE_VERBOSE
/* global singleton */ /* global singleton */
qemu_nyx_state_t global_state; qemu_nyx_state_t global_state;
#define LIBXDC_RELEASE_VERSION_REQUIRED 2 #define LIBXDC_RELEASE_VERSION_REQUIRED 2
void state_init_global(void){ void state_init_global(void)
{
#ifdef STATE_VERBOSE #ifdef STATE_VERBOSE
fprintf(stderr, "--> %s <--\n", __func__); fprintf(stderr, "--> %s <--\n", __func__);
#endif #endif
@ -73,7 +74,7 @@ void state_init_global(void){
global_state.patches_disable_pending = false; global_state.patches_disable_pending = false;
global_state.redqueen_state = NULL; global_state.redqueen_state = NULL;
for(uint8_t i = 0; i < INTEL_PT_MAX_RANGES; i++){ for (uint8_t i = 0; i < INTEL_PT_MAX_RANGES; i++) {
global_state.pt_ip_filter_configured[i] = false; global_state.pt_ip_filter_configured[i] = false;
global_state.pt_ip_filter_enabled[i] = false; global_state.pt_ip_filter_enabled[i] = false;
global_state.pt_ip_filter_a[i] = 0x0; global_state.pt_ip_filter_a[i] = 0x0;
@ -149,95 +150,114 @@ void state_init_global(void){
} }
fast_reload_t* get_fast_reload_snapshot(void){ fast_reload_t *get_fast_reload_snapshot(void)
{
return global_state.fast_reload_snapshot; return global_state.fast_reload_snapshot;
} }
void set_fast_reload_mode(bool mode){ void set_fast_reload_mode(bool mode)
{
global_state.fast_reload_mode = mode; global_state.fast_reload_mode = mode;
} }
void set_fast_reload_path(const char* path){ void set_fast_reload_path(const char *path)
{
assert(global_state.fast_reload_path == NULL); assert(global_state.fast_reload_path == NULL);
global_state.fast_reload_path = malloc(strlen(path)+1); global_state.fast_reload_path = malloc(strlen(path) + 1);
strcpy(global_state.fast_reload_path, path); strcpy(global_state.fast_reload_path, path);
} }
void set_fast_reload_pre_path(const char* path){ void set_fast_reload_pre_path(const char *path)
{
assert(global_state.fast_reload_pre_path == NULL); assert(global_state.fast_reload_pre_path == NULL);
global_state.fast_reload_pre_path = malloc(strlen(path)+1); global_state.fast_reload_pre_path = malloc(strlen(path) + 1);
strcpy(global_state.fast_reload_pre_path, path); strcpy(global_state.fast_reload_pre_path, path);
} }
void set_fast_reload_pre_image(void){ void set_fast_reload_pre_image(void)
{
assert(global_state.fast_reload_pre_path != NULL); assert(global_state.fast_reload_pre_path != NULL);
global_state.fast_reload_pre_image = true; global_state.fast_reload_pre_image = true;
} }
void enable_fast_reloads(void){ void enable_fast_reloads(void)
{
assert(global_state.fast_reload_path != NULL); assert(global_state.fast_reload_path != NULL);
global_state.fast_reload_enabled = true; global_state.fast_reload_enabled = true;
} }
void init_page_cache(char* path){ void init_page_cache(char *path)
{
assert(global_state.page_cache == NULL); assert(global_state.page_cache == NULL);
global_state.page_cache = page_cache_new((CPUState *)qemu_get_cpu(0), path); global_state.page_cache = page_cache_new((CPUState *)qemu_get_cpu(0), path);
} }
page_cache_t* get_page_cache(void){ page_cache_t *get_page_cache(void)
{
assert(global_state.page_cache); assert(global_state.page_cache);
return global_state.page_cache; return global_state.page_cache;
} }
void init_redqueen_state(void){ void init_redqueen_state(void)
global_state.redqueen_state = new_rq_state((CPUState *)qemu_get_cpu(0), get_page_cache()); {
global_state.redqueen_state =
new_rq_state((CPUState *)qemu_get_cpu(0), get_page_cache());
} }
redqueen_t* get_redqueen_state(void){ redqueen_t *get_redqueen_state(void)
{
assert(global_state.redqueen_state != NULL); assert(global_state.redqueen_state != NULL);
return global_state.redqueen_state; return global_state.redqueen_state;
} }
static void* alloc_auxiliary_buffer(const char* file){ static void *alloc_auxiliary_buffer(const char *file)
void* ptr; {
void *ptr;
struct stat st; struct stat st;
int fd = open(file, O_CREAT|O_RDWR, S_IRWXU|S_IRWXG|S_IRWXO); int fd = open(file, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
assert(ftruncate(fd, AUX_BUFFER_SIZE) == 0); assert(ftruncate(fd, AUX_BUFFER_SIZE) == 0);
stat(file, &st); stat(file, &st);
nyx_debug_p(INTERFACE_PREFIX, "new aux buffer file: (max size: %x) %lx", AUX_BUFFER_SIZE, st.st_size); nyx_debug_p(INTERFACE_PREFIX, "new aux buffer file: (max size: %x) %lx",
AUX_BUFFER_SIZE, st.st_size);
assert(AUX_BUFFER_SIZE == st.st_size); assert(AUX_BUFFER_SIZE == st.st_size);
ptr = mmap(0, AUX_BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); ptr = mmap(0, AUX_BUFFER_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) { if (ptr == MAP_FAILED) {
fprintf(stderr, "aux buffer allocation failed!\n"); fprintf(stderr, "aux buffer allocation failed!\n");
return (void*)-1; return (void *)-1;
} }
return ptr; return ptr;
} }
void init_aux_buffer(const char* filename){ void init_aux_buffer(const char *filename)
global_state.auxilary_buffer = (auxilary_buffer_t*)alloc_auxiliary_buffer(filename); {
global_state.auxilary_buffer =
(auxilary_buffer_t *)alloc_auxiliary_buffer(filename);
init_auxiliary_buffer(global_state.auxilary_buffer); init_auxiliary_buffer(global_state.auxilary_buffer);
} }
void set_payload_buffer(uint64_t payload_buffer){ void set_payload_buffer(uint64_t payload_buffer)
{
assert(global_state.payload_buffer == 0 && global_state.nested == false); assert(global_state.payload_buffer == 0 && global_state.nested == false);
global_state.payload_buffer = payload_buffer; global_state.payload_buffer = payload_buffer;
global_state.nested = false; global_state.nested = false;
} }
void set_payload_pages(uint64_t* payload_pages, uint32_t pages){ void set_payload_pages(uint64_t *payload_pages, uint32_t pages)
assert(global_state.nested_payload_pages == NULL && global_state.nested_payload_pages_num == 0); {
global_state.nested_payload_pages = (uint64_t*)malloc(sizeof(uint64_t)*pages); assert(global_state.nested_payload_pages == NULL &&
global_state.nested_payload_pages_num == 0);
global_state.nested_payload_pages = (uint64_t *)malloc(sizeof(uint64_t) * pages);
global_state.nested_payload_pages_num = pages; global_state.nested_payload_pages_num = pages;
memcpy(global_state.nested_payload_pages, payload_pages, sizeof(uint64_t)*pages); memcpy(global_state.nested_payload_pages, payload_pages, sizeof(uint64_t) * pages);
global_state.nested = true; global_state.nested = true;
} }
void set_workdir_path(char* workdir){ void set_workdir_path(char *workdir)
{
assert(workdir && !global_state.workdir_path); assert(workdir && !global_state.workdir_path);
assert(asprintf(&global_state.workdir_path, "%s", workdir) != -1); assert(asprintf(&global_state.workdir_path, "%s", workdir) != -1);
} }

View File

@ -21,42 +21,41 @@ along with QEMU-PT. If not, see <http://www.gnu.org/licenses/>.
#pragma once #pragma once
#include "nyx/auxiliary_buffer.h"
#include "nyx/fast_vm_reload.h"
#include "nyx/fast_vm_reload_sync.h"
#include "nyx/page_cache.h"
#include "nyx/redqueen.h" #include "nyx/redqueen.h"
#include "nyx/redqueen_patch.h" #include "nyx/redqueen_patch.h"
#include "nyx/fast_vm_reload.h"
#include "nyx/page_cache.h"
#include "nyx/synchronization.h"
#include "nyx/auxiliary_buffer.h"
#include "nyx/sharedir.h" #include "nyx/sharedir.h"
#include "nyx/fast_vm_reload_sync.h" #include "nyx/synchronization.h"
#include "nyx/types.h" #include "nyx/types.h"
#include <libxdc.h> #include <libxdc.h>
#define INTEL_PT_MAX_RANGES 4 #define INTEL_PT_MAX_RANGES 4
typedef struct qemu_nyx_state_s{ typedef struct qemu_nyx_state_s {
/* set if FDL backend is used (required to perform some additional runtime tests) */ /* set if FDL backend is used (required to perform some additional runtime tests) */
bool nyx_fdl; bool nyx_fdl;
char* workdir_path; char *workdir_path;
uint32_t worker_id; uint32_t worker_id;
/* FAST VM RELOAD */ /* FAST VM RELOAD */
bool fast_reload_enabled; bool fast_reload_enabled;
bool fast_reload_mode; bool fast_reload_mode;
char* fast_reload_path; char *fast_reload_path;
char* fast_reload_pre_path; char *fast_reload_pre_path;
bool fast_reload_pre_image; bool fast_reload_pre_image;
fast_reload_t* fast_reload_snapshot; fast_reload_t *fast_reload_snapshot;
fast_vm_reload_sync_t* reload_state; fast_vm_reload_sync_t *reload_state;
/* PAGE CACHE */ /* PAGE CACHE */
page_cache_t* page_cache; page_cache_t *page_cache;
/* Decoder */ /* Decoder */
libxdc_t* decoder; libxdc_t *decoder;
/* REDQUEEN */ /* REDQUEEN */
bool redqueen_enable_pending; bool redqueen_enable_pending;
@ -65,7 +64,7 @@ typedef struct qemu_nyx_state_s{
bool redqueen_update_blacklist; bool redqueen_update_blacklist;
bool patches_enable_pending; bool patches_enable_pending;
bool patches_disable_pending; bool patches_disable_pending;
redqueen_t* redqueen_state; redqueen_t *redqueen_state;
/* Intel PT Options (not migratable) */ /* Intel PT Options (not migratable) */
uint64_t pt_c3_filter; uint64_t pt_c3_filter;
@ -73,8 +72,9 @@ typedef struct qemu_nyx_state_s{
bool pt_trace_mode; // enabled by default; disabled if compile-time tracing is implemented by agent bool pt_trace_mode; // enabled by default; disabled if compile-time tracing is implemented by agent
/* disabled by default; enable to force usage of PT tracing /* disabled by default; enable to force usage of PT tracing
* (useful for targets that use compile-time tracing and redqueen at the same time (which obviously relies on PT traces)) * (useful for targets that use compile-time tracing and redqueen at the same
* This mode is usually enabled by the fuzzing logic by enabling trace mode. * time (which obviously relies on PT traces)) This mode is usually enabled by
* the fuzzing logic by enabling trace mode.
* *** THIS FEATURES IS STILL EXPERIMENTAL *** * *** THIS FEATURES IS STILL EXPERIMENTAL ***
* */ * */
bool pt_trace_mode_force; bool pt_trace_mode_force;
@ -86,14 +86,14 @@ typedef struct qemu_nyx_state_s{
int shared_bitmap_fd; int shared_bitmap_fd;
uint32_t shared_bitmap_size; /* size of the shared memory file */ uint32_t shared_bitmap_size; /* size of the shared memory file */
uint32_t shared_bitmap_real_size; /* actual size of the bitmap */ uint32_t shared_bitmap_real_size; /* actual size of the bitmap */
void* shared_bitmap_ptr; void *shared_bitmap_ptr;
int shared_payload_buffer_fd; int shared_payload_buffer_fd;
uint32_t shared_payload_buffer_size; uint32_t shared_payload_buffer_size;
int shared_ijon_bitmap_fd; int shared_ijon_bitmap_fd;
uint32_t shared_ijon_bitmap_size; uint32_t shared_ijon_bitmap_size;
void* shared_ijon_bitmap_ptr; void *shared_ijon_bitmap_ptr;
/* Intel PT Options (migratable) */ /* Intel PT Options (migratable) */
bool pt_ip_filter_configured[4]; bool pt_ip_filter_configured[4];
@ -106,7 +106,7 @@ typedef struct qemu_nyx_state_s{
bool nested; bool nested;
uint64_t payload_buffer; uint64_t payload_buffer;
uint32_t nested_payload_pages_num; uint32_t nested_payload_pages_num;
uint64_t* nested_payload_pages; uint64_t *nested_payload_pages;
bool protect_payload_buffer; bool protect_payload_buffer;
bool discard_tmp_snapshot; bool discard_tmp_snapshot;
mem_mode_t mem_mode; mem_mode_t mem_mode;
@ -147,9 +147,9 @@ typedef struct qemu_nyx_state_s{
uint64_t cap_ijon_tracing_buffer_vaddr; uint64_t cap_ijon_tracing_buffer_vaddr;
uint64_t cap_coverage_bitmap_size; uint64_t cap_coverage_bitmap_size;
auxilary_buffer_t* auxilary_buffer; auxilary_buffer_t *auxilary_buffer;
auxilary_buffer_config_t shadow_config; auxilary_buffer_config_t shadow_config;
sharedir_t* sharedir; sharedir_t *sharedir;
QTAILQ_HEAD(, kvm_sw_breakpoint) redqueen_breakpoints; QTAILQ_HEAD(, kvm_sw_breakpoint) redqueen_breakpoints;
} qemu_nyx_state_t; } qemu_nyx_state_t;
@ -159,26 +159,26 @@ extern qemu_nyx_state_t global_state;
#define GET_GLOBAL_STATE() (&global_state) #define GET_GLOBAL_STATE() (&global_state)
void state_init_global(void); void state_init_global(void);
fast_reload_t* get_fast_reload_snapshot(void); fast_reload_t *get_fast_reload_snapshot(void);
void set_fast_reload_mode(bool mode); void set_fast_reload_mode(bool mode);
void set_fast_reload_path(const char* path); void set_fast_reload_path(const char *path);
void set_fast_reload_pre_image(void); void set_fast_reload_pre_image(void);
void enable_fast_reloads(void); void enable_fast_reloads(void);
/* Page Cache */ /* Page Cache */
void init_page_cache(char* path); void init_page_cache(char *path);
page_cache_t* get_page_cache(void); page_cache_t *get_page_cache(void);
void init_redqueen_state(void); void init_redqueen_state(void);
redqueen_t* get_redqueen_state(void); redqueen_t *get_redqueen_state(void);
void init_aux_buffer(const char* filename); void init_aux_buffer(const char *filename);
void set_fast_reload_pre_path(const char* path); void set_fast_reload_pre_path(const char *path);
void set_payload_buffer(uint64_t payload_buffer); void set_payload_buffer(uint64_t payload_buffer);
void set_payload_pages(uint64_t* payload_pages, uint32_t pages); void set_payload_pages(uint64_t *payload_pages, uint32_t pages);
void set_workdir_path(char* workdir); void set_workdir_path(char *workdir);

View File

@ -1,18 +1,18 @@
#include "qemu/osdep.h"
#include "qemu/main-loop.h"
#include "sysemu/kvm.h"
#include "sysemu/sysemu.h"
#include "qemu-common.h"
#include "nyx/synchronization.h" #include "nyx/synchronization.h"
#include "nyx/debug.h"
#include "nyx/fast_vm_reload.h"
#include "nyx/file_helper.h"
#include "nyx/helpers.h"
#include "nyx/hypercall/hypercall.h" #include "nyx/hypercall/hypercall.h"
#include "nyx/interface.h" #include "nyx/interface.h"
#include "nyx/fast_vm_reload.h"
#include "qemu-common.h"
#include "qemu/osdep.h"
#include "sysemu/sysemu.h"
#include "sysemu/kvm.h"
#include "nyx/debug.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
#include <sys/syscall.h>
#include <linux/kvm.h> #include <linux/kvm.h>
#include "qemu/main-loop.h" #include <sys/syscall.h>
#include "nyx/helpers.h"
#include "nyx/file_helper.h"
#include "pt.h" #include "pt.h"
@ -26,9 +26,10 @@ volatile bool synchronization_kvm_loop_waiting = false;
/* SIGALRM based timeout detection */ /* SIGALRM based timeout detection */
//#define DEBUG_TIMEOUT_DETECTOR // #define DEBUG_TIMEOUT_DETECTOR
void init_timeout_detector(timeout_detector_t* timer){ void init_timeout_detector(timeout_detector_t *timer)
{
timer->kvm_tid = 0; timer->kvm_tid = 0;
timer->detection_enabled = false; timer->detection_enabled = false;
@ -39,10 +40,10 @@ void init_timeout_detector(timeout_detector_t* timer){
timer->alarm.it_interval.tv_usec = 0; timer->alarm.it_interval.tv_usec = 0;
timer->alarm.it_value.tv_sec = 0; timer->alarm.it_value.tv_sec = 0;
timer->alarm.it_value.tv_usec = 0; timer->alarm.it_value.tv_usec = 0;
} }
static void sigalarm_handler(int signum) { static void sigalarm_handler(int signum)
{
/* ensure that SIGALARM is ALWAYS handled by kvm thread */ /* ensure that SIGALARM is ALWAYS handled by kvm thread */
assert(GET_GLOBAL_STATE()->timeout_detector.kvm_tid == syscall(SYS_gettid)); assert(GET_GLOBAL_STATE()->timeout_detector.kvm_tid == syscall(SYS_gettid));
#ifdef DEBUG_TIMEOUT_DETECTOR #ifdef DEBUG_TIMEOUT_DETECTOR
@ -50,7 +51,8 @@ static void sigalarm_handler(int signum) {
#endif #endif
} }
void install_timeout_detector(timeout_detector_t* timer){ void install_timeout_detector(timeout_detector_t *timer)
{
timer->kvm_tid = syscall(SYS_gettid); timer->kvm_tid = syscall(SYS_gettid);
if (signal(SIGALRM, sigalarm_handler) == SIG_ERR) { if (signal(SIGALRM, sigalarm_handler) == SIG_ERR) {
fprintf(stderr, "%s failed!\n", __func__); fprintf(stderr, "%s failed!\n", __func__);
@ -61,7 +63,8 @@ void install_timeout_detector(timeout_detector_t* timer){
#endif #endif
} }
void reset_timeout_detector(timeout_detector_t* timer){ void reset_timeout_detector(timeout_detector_t *timer)
{
#ifdef DEBUG_TIMEOUT_DETECTOR #ifdef DEBUG_TIMEOUT_DETECTOR
fprintf(stderr, "%s!\n", __func__); fprintf(stderr, "%s!\n", __func__);
#endif #endif
@ -75,10 +78,10 @@ void reset_timeout_detector(timeout_detector_t* timer){
} }
} }
void update_itimer(timeout_detector_t* timer, uint8_t sec, uint32_t usec) void update_itimer(timeout_detector_t *timer, uint8_t sec, uint32_t usec)
{ {
#ifdef DEBUG_TIMEOUT_DETECTOR #ifdef DEBUG_TIMEOUT_DETECTOR
//fprintf(stderr, "%s: %x %x\n", __func__, sec, usec); // fprintf(stderr, "%s: %x %x\n", __func__, sec, usec);
#endif #endif
if (sec || usec) { if (sec || usec) {
@ -90,14 +93,17 @@ void update_itimer(timeout_detector_t* timer, uint8_t sec, uint32_t usec)
} }
} }
void arm_sigprof_timer(timeout_detector_t* timer){ void arm_sigprof_timer(timeout_detector_t *timer)
{
#ifdef DEBUG_TIMEOUT_DETECTOR #ifdef DEBUG_TIMEOUT_DETECTOR
fprintf(stderr, "%s (%ld %ld)\n", __func__, timer->alarm.it_value.tv_sec, timer->alarm.it_value.tv_usec); fprintf(stderr, "%s (%ld %ld)\n", __func__, timer->alarm.it_value.tv_sec,
timer->alarm.it_value.tv_usec);
#endif #endif
if (timer->detection_enabled) { if (timer->detection_enabled) {
if (timer->alarm.it_value.tv_usec == 0 && timer->alarm.it_value.tv_sec == 0) { if (timer->alarm.it_value.tv_usec == 0 && timer->alarm.it_value.tv_sec == 0) {
fprintf(stderr, "Attempting to re-arm an expired timer! => reset(%ld.%ld)\n", fprintf(stderr,
"Attempting to re-arm an expired timer! => reset(%ld.%ld)\n",
timer->config.tv_sec, timer->config.tv_usec); timer->config.tv_sec, timer->config.tv_usec);
reset_timeout_detector(timer); reset_timeout_detector(timer);
} }
@ -105,14 +111,15 @@ void arm_sigprof_timer(timeout_detector_t* timer){
} }
} }
bool disarm_sigprof_timer(timeout_detector_t* timer){ bool disarm_sigprof_timer(timeout_detector_t *timer)
{
#ifdef DEBUG_TIMEOUT_DETECTOR #ifdef DEBUG_TIMEOUT_DETECTOR
fprintf(stderr, "%s (%ld %ld)\n", __func__, timer->alarm.it_value.tv_sec, timer->alarm.it_value.tv_usec); fprintf(stderr, "%s (%ld %ld)\n", __func__, timer->alarm.it_value.tv_sec,
timer->alarm.it_value.tv_usec);
#endif #endif
if (timer->detection_enabled) { if (timer->detection_enabled) {
struct itimerval disable = {0}; struct itimerval disable = { 0 };
assert(setitimer(ITIMER_REAL, &disable, &timer->alarm) == 0); assert(setitimer(ITIMER_REAL, &disable, &timer->alarm) == 0);
assert(timer->alarm.it_interval.tv_usec == 0); assert(timer->alarm.it_interval.tv_usec == 0);
@ -124,7 +131,8 @@ bool disarm_sigprof_timer(timeout_detector_t* timer){
return false; return false;
} }
void block_signals(void){ void block_signals(void)
{
sigset_t set; sigset_t set;
sigemptyset(&set); sigemptyset(&set);
@ -132,11 +140,11 @@ void block_signals(void){
sigaddset(&set, SIGABRT); sigaddset(&set, SIGABRT);
sigaddset(&set, SIGSEGV); sigaddset(&set, SIGSEGV);
pthread_sigmask(SIG_BLOCK, &set, NULL); pthread_sigmask(SIG_BLOCK, &set, NULL);
//fprintf(stderr, "%s!\n", __func__); // fprintf(stderr, "%s!\n", __func__);
} }
void unblock_signals(void){ void unblock_signals(void)
{
sigset_t set; sigset_t set;
sigemptyset(&set); sigemptyset(&set);
@ -148,32 +156,35 @@ void unblock_signals(void){
/* -------------------- */ /* -------------------- */
static inline void handle_tmp_snapshot_state(void){ static inline void handle_tmp_snapshot_state(void)
if(GET_GLOBAL_STATE()->discard_tmp_snapshot){ {
if(fast_reload_tmp_created(get_fast_reload_snapshot())){ if (GET_GLOBAL_STATE()->discard_tmp_snapshot) {
if (fast_reload_tmp_created(get_fast_reload_snapshot())) {
qemu_mutex_lock_iothread(); qemu_mutex_lock_iothread();
fast_reload_discard_tmp_snapshot(get_fast_reload_snapshot()); /* bye bye */ fast_reload_discard_tmp_snapshot(get_fast_reload_snapshot()); /* bye bye */
qemu_mutex_unlock_iothread(); qemu_mutex_unlock_iothread();
//fprintf(stderr, "======= SNAPSHOT REMOVED! =======\n"); // fprintf(stderr, "======= SNAPSHOT REMOVED! =======\n");
} }
GET_GLOBAL_STATE()->discard_tmp_snapshot = false; GET_GLOBAL_STATE()->discard_tmp_snapshot = false;
set_tmp_snapshot_created(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_tmp_snapshot_created(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
} }
static inline bool synchronization_check_page_not_found(void){ static inline bool synchronization_check_page_not_found(void)
{
bool failure = false; bool failure = false;
/* a page is missing in the current execution */ /* a page is missing in the current execution */
if(GET_GLOBAL_STATE()->decoder_page_fault){ if (GET_GLOBAL_STATE()->decoder_page_fault) {
set_page_not_found_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, GET_GLOBAL_STATE()->decoder_page_fault_addr); set_page_not_found_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer,
GET_GLOBAL_STATE()->decoder_page_fault_addr);
GET_GLOBAL_STATE()->decoder_page_fault = false; GET_GLOBAL_STATE()->decoder_page_fault = false;
GET_GLOBAL_STATE()->decoder_page_fault_addr = 0; GET_GLOBAL_STATE()->decoder_page_fault_addr = 0;
failure = true; failure = true;
} }
/* page was dumped during this execution */ /* page was dumped during this execution */
if(GET_GLOBAL_STATE()->dump_page){ if (GET_GLOBAL_STATE()->dump_page) {
kvm_remove_all_breakpoints(qemu_get_cpu(0)); kvm_remove_all_breakpoints(qemu_get_cpu(0));
kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_PAGE_DUMP_CR3); kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_PAGE_DUMP_CR3);
kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_MTF); kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_MTF);
@ -184,8 +195,9 @@ static inline bool synchronization_check_page_not_found(void){
return failure; return failure;
} }
void synchronization_unlock(void){ void synchronization_unlock(void)
//fprintf(stderr, "%s\n", __func__); {
// fprintf(stderr, "%s\n", __func__);
pthread_mutex_lock(&synchronization_lock_mutex); pthread_mutex_lock(&synchronization_lock_mutex);
pthread_cond_signal(&synchronization_lock_condition); pthread_cond_signal(&synchronization_lock_condition);
@ -196,20 +208,21 @@ void synchronization_unlock(void){
uint64_t run_counter = 0; uint64_t run_counter = 0;
bool in_fuzzing_loop = false; bool in_fuzzing_loop = false;
void synchronization_lock_hprintf(void){ void synchronization_lock_hprintf(void)
{
pthread_mutex_lock(&synchronization_lock_mutex); pthread_mutex_lock(&synchronization_lock_mutex);
interface_send_char(NYX_INTERFACE_PING); interface_send_char(NYX_INTERFACE_PING);
pthread_cond_wait(&synchronization_lock_condition, &synchronization_lock_mutex); pthread_cond_wait(&synchronization_lock_condition, &synchronization_lock_mutex);
pthread_mutex_unlock(&synchronization_lock_mutex); pthread_mutex_unlock(&synchronization_lock_mutex);
} }
void synchronization_lock(void){ void synchronization_lock(void)
{
timeout_detector_t timer = GET_GLOBAL_STATE()->timeout_detector; timeout_detector_t timer = GET_GLOBAL_STATE()->timeout_detector;
pthread_mutex_lock(&synchronization_lock_mutex); pthread_mutex_lock(&synchronization_lock_mutex);
run_counter++; run_counter++;
if(qemu_get_cpu(0)->intel_pt_run_trashed){ if (qemu_get_cpu(0)->intel_pt_run_trashed) {
set_pt_overflow_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer); set_pt_overflow_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer);
} }
@ -227,18 +240,18 @@ void synchronization_lock(void){
runtime_sec, runtime_usec, runtime_sec, runtime_usec,
GET_GLOBAL_STATE()->num_dirty_pages); GET_GLOBAL_STATE()->num_dirty_pages);
if(synchronization_check_page_not_found()){ if (synchronization_check_page_not_found()) {
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
if(GET_GLOBAL_STATE()->dump_page){ if (GET_GLOBAL_STATE()->dump_page) {
GET_GLOBAL_STATE()->dump_page = false; GET_GLOBAL_STATE()->dump_page = false;
GET_GLOBAL_STATE()->dump_page_addr = 0x0; GET_GLOBAL_STATE()->dump_page_addr = 0x0;
kvm_remove_all_breakpoints(qemu_get_cpu(0)); kvm_remove_all_breakpoints(qemu_get_cpu(0));
kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_PAGE_DUMP_CR3); kvm_vcpu_ioctl(qemu_get_cpu(0), KVM_VMX_PT_DISABLE_PAGE_DUMP_CR3);
} }
if(unlikely(GET_GLOBAL_STATE()->in_redqueen_reload_mode)) { if (unlikely(GET_GLOBAL_STATE()->in_redqueen_reload_mode)) {
fsync_redqueen_files(); fsync_redqueen_files();
} }
@ -251,7 +264,8 @@ void synchronization_lock(void){
pthread_cond_wait(&synchronization_lock_condition, &synchronization_lock_mutex); pthread_cond_wait(&synchronization_lock_condition, &synchronization_lock_mutex);
pthread_mutex_unlock(&synchronization_lock_mutex); pthread_mutex_unlock(&synchronization_lock_mutex);
check_auxiliary_config_buffer(GET_GLOBAL_STATE()->auxilary_buffer, &GET_GLOBAL_STATE()->shadow_config); check_auxiliary_config_buffer(GET_GLOBAL_STATE()->auxilary_buffer,
&GET_GLOBAL_STATE()->shadow_config);
if (GET_GLOBAL_STATE()->starved == true) if (GET_GLOBAL_STATE()->starved == true)
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 2); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 2);
@ -261,23 +275,26 @@ void synchronization_lock(void){
GET_GLOBAL_STATE()->pt_trace_size = 0; GET_GLOBAL_STATE()->pt_trace_size = 0;
} }
static void perform_reload(void){ static void perform_reload(void)
if(fast_reload_root_created(get_fast_reload_snapshot())){ {
if (fast_reload_root_created(get_fast_reload_snapshot())) {
qemu_mutex_lock_iothread(); qemu_mutex_lock_iothread();
fast_reload_restore(get_fast_reload_snapshot()); fast_reload_restore(get_fast_reload_snapshot());
qemu_mutex_unlock_iothread(); qemu_mutex_unlock_iothread();
set_reload_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer); set_reload_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer);
set_result_dirty_pages(GET_GLOBAL_STATE()->auxilary_buffer, get_dirty_page_num(get_fast_reload_snapshot())); set_result_dirty_pages(GET_GLOBAL_STATE()->auxilary_buffer,
} get_dirty_page_num(get_fast_reload_snapshot()));
else{ } else {
fprintf(stderr, "WARNING: Root snapshot is not available yet!\n"); fprintf(stderr, "WARNING: Root snapshot is not available yet!\n");
} }
} }
void synchronization_lock_crash_found(void){ void synchronization_lock_crash_found(void)
if(!in_fuzzing_loop && GET_GLOBAL_STATE()->in_fuzzing_mode){ {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP] at %lx\n", getpid(), run_counter, __func__, get_rip(qemu_get_cpu(0))); if (!in_fuzzing_loop && GET_GLOBAL_STATE()->in_fuzzing_mode) {
//abort(); fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP] at %lx\n", getpid(),
run_counter, __func__, get_rip(qemu_get_cpu(0)));
// abort();
} }
pt_disable(qemu_get_cpu(0), false); pt_disable(qemu_get_cpu(0), false);
@ -291,9 +308,11 @@ void synchronization_lock_crash_found(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_lock_asan_found(void){ void synchronization_lock_asan_found(void)
if(!in_fuzzing_loop){ {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__); if (!in_fuzzing_loop) {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(),
run_counter, __func__);
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
@ -308,12 +327,12 @@ void synchronization_lock_asan_found(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_lock_timeout_found(void){ void synchronization_lock_timeout_found(void)
{
// fprintf(stderr, "<%d>\t%s\n", getpid(), __func__);
//fprintf(stderr, "<%d>\t%s\n", getpid(), __func__); if (!in_fuzzing_loop) {
// fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__);
if(!in_fuzzing_loop){
//fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__);
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
@ -328,9 +347,11 @@ void synchronization_lock_timeout_found(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_lock_shutdown_detected(void){ void synchronization_lock_shutdown_detected(void)
if(!in_fuzzing_loop){ {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__); if (!in_fuzzing_loop) {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(),
run_counter, __func__);
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
@ -343,19 +364,23 @@ void synchronization_lock_shutdown_detected(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_payload_buffer_write_detected(void){ void synchronization_payload_buffer_write_detected(void)
{
static char reason[1024]; static char reason[1024];
if(!in_fuzzing_loop){ if (!in_fuzzing_loop) {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__); fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(),
run_counter, __func__);
} }
pt_disable(qemu_get_cpu(0), false); pt_disable(qemu_get_cpu(0), false);
handle_tmp_snapshot_state(); handle_tmp_snapshot_state();
int bytes = snprintf(reason, 1024, "Payload buffer write attempt at RIP: %lx\n", get_rip(qemu_get_cpu(0))); int bytes = snprintf(reason, 1024, "Payload buffer write attempt at RIP: %lx\n",
set_payload_buffer_write_reason_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer, reason, bytes); get_rip(qemu_get_cpu(0)));
set_payload_buffer_write_reason_auxiliary_buffer(GET_GLOBAL_STATE()->auxilary_buffer,
reason, bytes);
set_reload_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer); set_reload_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer);
perform_reload(); perform_reload();
@ -363,9 +388,11 @@ void synchronization_payload_buffer_write_detected(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_cow_full_detected(void){ void synchronization_cow_full_detected(void)
if(!in_fuzzing_loop){ {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__); if (!in_fuzzing_loop) {
fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(),
run_counter, __func__);
} }
pt_disable(qemu_get_cpu(0), false); pt_disable(qemu_get_cpu(0), false);
@ -377,10 +404,11 @@ void synchronization_cow_full_detected(void){
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_disable_pt(CPUState *cpu){ void synchronization_disable_pt(CPUState *cpu)
{
// nyx_trace(); // nyx_trace();
if(!in_fuzzing_loop){ if (!in_fuzzing_loop) {
//fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__); // fprintf(stderr, "<%d-%ld>\t%s [NOT IN FUZZING LOOP]\n", getpid(), run_counter, __func__);
set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0); set_success_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 0);
} }
@ -388,22 +416,27 @@ void synchronization_disable_pt(CPUState *cpu){
handle_tmp_snapshot_state(); handle_tmp_snapshot_state();
if(GET_GLOBAL_STATE()->in_reload_mode || GET_GLOBAL_STATE()->in_redqueen_reload_mode || GET_GLOBAL_STATE()->dump_page || fast_reload_tmp_created(get_fast_reload_snapshot())){ if (GET_GLOBAL_STATE()->in_reload_mode ||
GET_GLOBAL_STATE()->in_redqueen_reload_mode || GET_GLOBAL_STATE()->dump_page ||
fast_reload_tmp_created(get_fast_reload_snapshot()))
{
perform_reload(); perform_reload();
} }
set_result_pt_trace_size(GET_GLOBAL_STATE()->auxilary_buffer, GET_GLOBAL_STATE()->pt_trace_size); set_result_pt_trace_size(GET_GLOBAL_STATE()->auxilary_buffer,
set_result_bb_coverage(GET_GLOBAL_STATE()->auxilary_buffer, GET_GLOBAL_STATE()->bb_coverage); GET_GLOBAL_STATE()->pt_trace_size);
set_result_bb_coverage(GET_GLOBAL_STATE()->auxilary_buffer,
GET_GLOBAL_STATE()->bb_coverage);
in_fuzzing_loop = false; in_fuzzing_loop = false;
} }
void synchronization_enter_fuzzing_loop(CPUState *cpu){ void synchronization_enter_fuzzing_loop(CPUState *cpu)
if (pt_enable(cpu, false) == 0){ {
if (pt_enable(cpu, false) == 0) {
cpu->pt_enabled = true; cpu->pt_enabled = true;
} }
in_fuzzing_loop = true; in_fuzzing_loop = true;
reset_timeout_detector(&(GET_GLOBAL_STATE()->timeout_detector)); reset_timeout_detector(&(GET_GLOBAL_STATE()->timeout_detector));
} }

View File

@ -13,12 +13,12 @@ typedef struct timeout_detector_s {
struct itimerval alarm; struct itimerval alarm;
} timeout_detector_t; } timeout_detector_t;
void init_timeout_detector(timeout_detector_t* timeout_detector); void init_timeout_detector(timeout_detector_t *timeout_detector);
void install_timeout_detector(timeout_detector_t* timeout_detector); void install_timeout_detector(timeout_detector_t *timeout_detector);
void reset_timeout_detector(timeout_detector_t* timeout_detector); void reset_timeout_detector(timeout_detector_t *timeout_detector);
void arm_sigprof_timer(timeout_detector_t* timeout_detector); void arm_sigprof_timer(timeout_detector_t *timeout_detector);
bool disarm_sigprof_timer(timeout_detector_t* timeout_detector); bool disarm_sigprof_timer(timeout_detector_t *timeout_detector);
void update_itimer(timeout_detector_t* timeout_detector, uint8_t sec, uint32_t usec); void update_itimer(timeout_detector_t *timeout_detector, uint8_t sec, uint32_t usec);
void block_signals(void); void block_signals(void);
void unblock_signals(void); void unblock_signals(void);

View File

@ -1,9 +1,9 @@
#include "qemu/osdep.h" #include "qemu/osdep.h"
#include <stdint.h>
#include <unistd.h>
#include <stdio.h>
#include <assert.h> #include <assert.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/state/state.h" #include "nyx/state/state.h"
@ -15,36 +15,40 @@ char *pt_trace_dump_filename;
bool pt_dump_initialized = false; bool pt_dump_initialized = false;
bool pt_dump_enabled = false; bool pt_dump_enabled = false;
void pt_trace_dump_enable(bool enable){ void pt_trace_dump_enable(bool enable)
{
if (pt_dump_initialized) if (pt_dump_initialized)
pt_dump_enabled = enable; pt_dump_enabled = enable;
} }
void pt_trace_dump_init(char* filename) void pt_trace_dump_init(char *filename)
{ {
int test_fd; int test_fd;
nyx_debug("Enable pt trace dump at %s", filename); nyx_debug("Enable pt trace dump at %s", filename);
pt_dump_initialized = true; pt_dump_initialized = true;
test_fd = open(filename, O_CREAT|O_TRUNC|O_WRONLY, 0644); test_fd = open(filename, O_CREAT | O_TRUNC | O_WRONLY, 0644);
if (test_fd < 0) if (test_fd < 0)
fprintf(stderr, "Error accessing pt_dump output path %s: %s", pt_trace_dump_filename, strerror(errno)); fprintf(stderr, "Error accessing pt_dump output path %s: %s",
pt_trace_dump_filename, strerror(errno));
assert(test_fd >= 0); assert(test_fd >= 0);
pt_trace_dump_filename = strdup(filename); pt_trace_dump_filename = strdup(filename);
assert(pt_trace_dump_filename); assert(pt_trace_dump_filename);
} }
void pt_truncate_pt_dump_file(void) { void pt_truncate_pt_dump_file(void)
{
int fd; int fd;
if (!pt_dump_enabled) if (!pt_dump_enabled)
return; return;
fd = open(pt_trace_dump_filename, O_CREAT|O_TRUNC|O_WRONLY, 0644); fd = open(pt_trace_dump_filename, O_CREAT | O_TRUNC | O_WRONLY, 0644);
if (fd < 0) { if (fd < 0) {
fprintf(stderr, "Error truncating %s: %s\n", pt_trace_dump_filename, strerror(errno)); fprintf(stderr, "Error truncating %s: %s\n", pt_trace_dump_filename,
strerror(errno));
assert(0); assert(0);
} }
close(fd); close(fd);
@ -57,12 +61,12 @@ void pt_write_pt_dump_file(uint8_t *data, size_t bytes)
if (!pt_dump_enabled) if (!pt_dump_enabled)
return; return;
fd = open(pt_trace_dump_filename, O_APPEND|O_WRONLY, 0644); fd = open(pt_trace_dump_filename, O_APPEND | O_WRONLY, 0644);
if (fd < 0) { if (fd < 0) {
fprintf(stderr, "Error writing pt_trace_dump to %s: %s\n", pt_trace_dump_filename, strerror(errno)); fprintf(stderr, "Error writing pt_trace_dump to %s: %s\n",
pt_trace_dump_filename, strerror(errno));
assert(0); assert(0);
} }
assert(bytes == write(fd, data, bytes)); assert(bytes == write(fd, data, bytes));
close(fd); close(fd);
} }

View File

@ -2,7 +2,7 @@
#include <stdint.h> #include <stdint.h>
void pt_trace_dump_init(char* filename); void pt_trace_dump_init(char *filename);
void pt_trace_dump_enable(bool enable); void pt_trace_dump_enable(bool enable);
void pt_write_pt_dump_file(uint8_t *data, size_t bytes); void pt_write_pt_dump_file(uint8_t *data, size_t bytes);
void pt_truncate_pt_dump_file(void); void pt_truncate_pt_dump_file(void);

139
vl.c
View File

@ -137,12 +137,12 @@ int main(int argc, char **argv)
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
#include "nyx/debug.h" #include "nyx/debug.h"
#include "nyx/pt.h"
#include "nyx/hypercall/hypercall.h"
#include "nyx/synchronization.h"
#include "nyx/fast_vm_reload.h" #include "nyx/fast_vm_reload.h"
#include "nyx/state/state.h"
#include "nyx/fast_vm_reload_sync.h" #include "nyx/fast_vm_reload_sync.h"
#include "nyx/hypercall/hypercall.h"
#include "nyx/pt.h"
#include "nyx/state/state.h"
#include "nyx/synchronization.h"
// clang-format off // clang-format off
#endif #endif
@ -261,22 +261,19 @@ static QemuOptsList qemu_fast_vm_reloads_opts = {
.implied_opt_name = "order", .implied_opt_name = "order",
.head = QTAILQ_HEAD_INITIALIZER(qemu_fast_vm_reloads_opts.head), .head = QTAILQ_HEAD_INITIALIZER(qemu_fast_vm_reloads_opts.head),
.merge_lists = true, .merge_lists = true,
.desc = { .desc = {{
{ .name = "path",
.name = "path", .type = QEMU_OPT_STRING,
.type = QEMU_OPT_STRING, }, {
},{
.name = "load", .name = "load",
.type = QEMU_OPT_BOOL, .type = QEMU_OPT_BOOL,
},{ }, {
.name = "pre_path", .name = "pre_path",
.type = QEMU_OPT_STRING, .type = QEMU_OPT_STRING,
},{ }, {
.name = "skip_serialization", .name = "skip_serialization",
.type = QEMU_OPT_BOOL, .type = QEMU_OPT_BOOL,
}, }, {}},
{ }
},
}; };
// clang-format off // clang-format off
#endif #endif
@ -1481,7 +1478,7 @@ void vm_state_notify(int running, RunState state)
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
char* loadvm_global = NULL; char *loadvm_global = NULL;
// clang-format off // clang-format off
#endif #endif
@ -1660,8 +1657,8 @@ void qemu_system_guest_panicked(GuestPanicInformation *info)
void qemu_system_reset_request(ShutdownCause reason) void qemu_system_reset_request(ShutdownCause reason)
{ {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(GET_GLOBAL_STATE()->in_fuzzing_mode){ if (GET_GLOBAL_STATE()->in_fuzzing_mode) {
nyx_trace(); nyx_trace();
GET_GLOBAL_STATE()->shutdown_requested = true; GET_GLOBAL_STATE()->shutdown_requested = true;
return; return;
@ -1872,8 +1869,8 @@ static bool main_loop_should_exit(void)
} }
if (qemu_vmstop_requested(&r)) { if (qemu_vmstop_requested(&r)) {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
if(check_if_relood_request_exists_post(GET_GLOBAL_STATE()->reload_state)){ if (check_if_relood_request_exists_post(GET_GLOBAL_STATE()->reload_state)) {
return false; return false;
} }
// clang-format off // clang-format off
@ -1902,9 +1899,9 @@ static void main_loop(void)
static void version(void) static void version(void)
{ {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
printf("QEMU-PT emulator version " QEMU_VERSION QEMU_PKGVERSION " (kAFL)\n" printf("QEMU-PT emulator version " QEMU_VERSION QEMU_PKGVERSION
QEMU_COPYRIGHT "\n"); " (kAFL)\n" QEMU_COPYRIGHT "\n");
// clang-format off // clang-format off
#else #else
printf("QEMU emulator version " QEMU_FULL_VERSION "\n" printf("QEMU emulator version " QEMU_FULL_VERSION "\n"
@ -2809,17 +2806,17 @@ static bool object_create_delayed(const char *type, QemuOpts *opts)
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
static bool verifiy_snapshot_folder(const char* folder){ static bool verifiy_snapshot_folder(const char *folder)
{
struct stat s; struct stat s;
if(!folder){ if (!folder) {
return false; return false;
} }
if(-1 != stat(folder, &s)) { if (-1 != stat(folder, &s)) {
if(S_ISDIR(s.st_mode)) { if (S_ISDIR(s.st_mode)) {
return true; return true;
} } else {
else{
error_report("fast_vm_reload: path is not a folder"); error_report("fast_vm_reload: path is not a folder");
exit(1); exit(1);
} }
@ -2943,7 +2940,7 @@ int main(int argc, char **argv, char **envp)
{ {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
bool fast_vm_reload = false; bool fast_vm_reload = false;
state_init_global(); state_init_global();
const char *fast_vm_reload_opt_arg = NULL; const char *fast_vm_reload_opt_arg = NULL;
@ -3011,7 +3008,7 @@ int main(int argc, char **argv, char **envp)
qemu_add_opts(&qemu_nic_opts); qemu_add_opts(&qemu_nic_opts);
qemu_add_opts(&qemu_net_opts); qemu_add_opts(&qemu_net_opts);
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
qemu_add_opts(&qemu_fast_vm_reloads_opts); qemu_add_opts(&qemu_fast_vm_reloads_opts);
// clang-format off // clang-format off
#endif #endif
@ -3103,7 +3100,7 @@ int main(int argc, char **argv, char **envp)
} }
switch(popt->index) { switch(popt->index) {
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
case QEMU_OPTION_fast_vm_reload: case QEMU_OPTION_fast_vm_reload:
opts = qemu_opts_parse_noisily(qemu_find_opts("fast_vm_reload-opts"), opts = qemu_opts_parse_noisily(qemu_find_opts("fast_vm_reload-opts"),
optarg, true); optarg, true);
@ -3571,8 +3568,8 @@ int main(int argc, char **argv, char **envp)
case QEMU_OPTION_loadvm: case QEMU_OPTION_loadvm:
loadvm = optarg; loadvm = optarg;
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
loadvm_global = (char*)optarg; loadvm_global = (char *)optarg;
// clang-format off // clang-format off
#endif #endif
break; break;
@ -4015,7 +4012,7 @@ int main(int argc, char **argv, char **envp)
} }
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
block_signals(); block_signals();
// clang-format off // clang-format off
#endif #endif
@ -4590,19 +4587,21 @@ int main(int argc, char **argv, char **envp)
register_global_state(); register_global_state();
#ifdef QEMU_NYX #ifdef QEMU_NYX
// clang-format on // clang-format on
fast_reload_init(GET_GLOBAL_STATE()->fast_reload_snapshot); fast_reload_init(GET_GLOBAL_STATE()->fast_reload_snapshot);
if (fast_vm_reload){ if (fast_vm_reload) {
if (getenv("NYX_DISABLE_BLOCK_COW")) {
if(getenv("NYX_DISABLE_BLOCK_COW")){ nyx_error("Nyx block COW cache layer cannot be disabled while using "
nyx_error("Nyx block COW cache layer cannot be disabled while using fast snapshots\n"); "fast snapshots\n");
exit(1); exit(1);
} }
QemuOpts *opts = qemu_opts_parse_noisily(qemu_find_opts("fast_vm_reload-opts"), fast_vm_reload_opt_arg, true); QemuOpts *opts =
const char* snapshot_path = qemu_opt_get(opts, "path"); qemu_opts_parse_noisily(qemu_find_opts("fast_vm_reload-opts"),
const char* pre_snapshot_path = qemu_opt_get(opts, "pre_path"); fast_vm_reload_opt_arg, true);
const char *snapshot_path = qemu_opt_get(opts, "path");
const char *pre_snapshot_path = qemu_opt_get(opts, "pre_path");
/* /*
@ -4630,59 +4629,67 @@ int main(int argc, char **argv, char **envp)
bool load_mode = qemu_opt_get_bool(opts, "load", false); bool load_mode = qemu_opt_get_bool(opts, "load", false);
bool skip_serialization = qemu_opt_get_bool(opts, "skip_serialization", false); bool skip_serialization = qemu_opt_get_bool(opts, "skip_serialization", false);
if((snapshot_used || load_mode || skip_serialization) && getenv("NYX_DISABLE_DIRTY_RING")){ if ((snapshot_used || load_mode || skip_serialization) &&
error_report("NYX_DISABLE_DIRTY_RING is only allowed during pre-snapshot creation\n"); getenv("NYX_DISABLE_DIRTY_RING"))
{
error_report("NYX_DISABLE_DIRTY_RING is only allowed during "
"pre-snapshot creation\n");
exit(1); exit(1);
} }
if((pre_snapshot_used && !snapshot_used && !load_mode) && !getenv("NYX_DISABLE_DIRTY_RING")){ if ((pre_snapshot_used && !snapshot_used && !load_mode) &&
error_report("NYX_DISABLE_DIRTY_RING is required during pre-snapshot creation\n"); !getenv("NYX_DISABLE_DIRTY_RING"))
{
error_report(
"NYX_DISABLE_DIRTY_RING is required during pre-snapshot creation\n");
exit(1); exit(1);
} }
if(pre_snapshot_used && load_mode){ if (pre_snapshot_used && load_mode) {
error_report("invalid argument (pre_snapshot_used && load_mode)!\n"); error_report("invalid argument (pre_snapshot_used && load_mode)!\n");
exit(1); exit(1);
} }
if((!snapshot_used && !pre_snapshot_used) && load_mode){ if ((!snapshot_used && !pre_snapshot_used) && load_mode) {
error_report("invalid argument ((!pre_snapshot_used && !pre_snapshot_used) && load_mode)!\n"); error_report("invalid argument ((!pre_snapshot_used && "
"!pre_snapshot_used) && load_mode)!\n");
exit(1); exit(1);
} }
if(pre_snapshot_used && snapshot_used){ if (pre_snapshot_used && snapshot_used) {
nyx_printf("[Qemu-Nyx]: loading pre image to start fuzzing...\n"); nyx_printf("[Qemu-Nyx]: loading pre image to start fuzzing...\n");
set_fast_reload_mode(false); set_fast_reload_mode(false);
set_fast_reload_path(snapshot_path); set_fast_reload_path(snapshot_path);
if(!skip_serialization){ if (!skip_serialization) {
enable_fast_reloads(); enable_fast_reloads();
} }
fast_reload_create_from_file_pre_image(get_fast_reload_snapshot(), pre_snapshot_path, false); fast_reload_create_from_file_pre_image(get_fast_reload_snapshot(),
pre_snapshot_path, false);
fast_reload_destroy(get_fast_reload_snapshot()); fast_reload_destroy(get_fast_reload_snapshot());
GET_GLOBAL_STATE()->fast_reload_snapshot = fast_reload_new(); GET_GLOBAL_STATE()->fast_reload_snapshot = fast_reload_new();
fast_reload_init(GET_GLOBAL_STATE()->fast_reload_snapshot); fast_reload_init(GET_GLOBAL_STATE()->fast_reload_snapshot);
} } else {
else{ if (pre_snapshot_used) {
if(pre_snapshot_used){
nyx_printf("[Qemu-Nyx]: preparing to create pre image...\n"); nyx_printf("[Qemu-Nyx]: preparing to create pre image...\n");
set_fast_reload_pre_path(pre_snapshot_path); set_fast_reload_pre_path(pre_snapshot_path);
set_fast_reload_pre_image(); set_fast_reload_pre_image();
} } else if (snapshot_used) {
else if(snapshot_used){
set_fast_reload_path(snapshot_path); set_fast_reload_path(snapshot_path);
if(!skip_serialization){ if (!skip_serialization) {
enable_fast_reloads(); enable_fast_reloads();
} }
if (load_mode){ if (load_mode) {
set_fast_reload_mode(true); set_fast_reload_mode(true);
nyx_printf("[Qemu-Nyx]: waiting for snapshot to start fuzzing...\n"); nyx_printf(
fast_reload_create_from_file(get_fast_reload_snapshot(), snapshot_path, false); "[Qemu-Nyx]: waiting for snapshot to start fuzzing...\n");
//cpu_synchronize_all_post_reset(); fast_reload_create_from_file(get_fast_reload_snapshot(),
set_state_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer, 3); snapshot_path, false);
// cpu_synchronize_all_post_reset();
set_state_auxiliary_result_buffer(GET_GLOBAL_STATE()->auxilary_buffer,
3);
skip_init(); skip_init();
//GET_GLOBAL_STATE()->pt_trace_mode = false; // GET_GLOBAL_STATE()->pt_trace_mode = false;
} } else {
else{
nyx_printf("[Qemu-Nyx]: Booting VM to start fuzzing...\n"); nyx_printf("[Qemu-Nyx]: Booting VM to start fuzzing...\n");
set_fast_reload_mode(false); set_fast_reload_mode(false);
} }