Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add KUSER_SHARED_DATA MMIO support #27

Merged
merged 5 commits into from
Nov 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/emulator/serialization_helper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,20 @@ inline void deserialize(utils::buffer_deserializer& buffer, std::chrono::steady_
tp = time_point{duration{count}};
}

inline void serialize(utils::buffer_serializer& buffer, const std::chrono::system_clock::time_point& tp)
{
buffer.write(tp.time_since_epoch().count());
}

inline void deserialize(utils::buffer_deserializer& buffer, std::chrono::system_clock::time_point& tp)
{
using time_point = std::chrono::system_clock::time_point;
using duration = time_point::duration;

const auto count = buffer.read<duration::rep>();
tp = time_point{duration{count}};
}

inline void serialize(utils::buffer_serializer& buffer, const std::filesystem::path& path)
{
buffer.write_string<wchar_t>(path.wstring());
Expand Down
20 changes: 18 additions & 2 deletions src/test-sample/test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,14 @@
#include <fstream>
#include <thread>
#include <atomic>
#include <optional>
#include <vector>
#include <optional>
#include <string_view>

#include <Windows.h>

using namespace std::literals;

// Externally visible and potentially modifiable state
// to trick compiler optimizations
__declspec(dllexport) bool do_the_task = true;
Expand Down Expand Up @@ -178,6 +182,12 @@ bool test_native_exceptions()
}
}

void print_time()
{
const auto epoch_time = std::chrono::system_clock::now().time_since_epoch();
printf("Time: %lld\n", epoch_time.count());
}

#define RUN_TEST(func, name) \
{ \
printf("Running test '" name "': "); \
Expand All @@ -186,8 +196,14 @@ bool test_native_exceptions()
puts(res ? "Success" : "Fail"); \
}

int main(int /*argc*/, const char* /*argv*/[])
int main(int argc, const char* argv[])
{
if(argc == 2 && argv[1] == "-time"sv)
{
print_time();
return 0;
}

bool valid = true;

RUN_TEST(test_io, "I/O")
Expand Down
17 changes: 11 additions & 6 deletions src/windows-emulator-test/emulation_test_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,35 @@

#define ASSERT_NOT_TERMINATED(win_emu) \
do { \
ASSERT_FALSE(win_emu.process().exit_status.has_value()); \
ASSERT_FALSE((win_emu).process().exit_status.has_value()); \
} while(false)


#define ASSERT_TERMINATED_WITH_STATUS(win_emu, status) \
do { \
ASSERT_TRUE(win_emu.process().exit_status.has_value()); \
ASSERT_EQ(*win_emu.process().exit_status, status); \
ASSERT_TRUE((win_emu).process().exit_status.has_value()); \
ASSERT_EQ(*(win_emu).process().exit_status, status); \
} while(false)

#define ASSERT_TERMINATED_SUCCESSFULLY(win_emu) \
ASSERT_TERMINATED_WITH_STATUS(win_emu, STATUS_SUCCESS)

namespace test
{
inline windows_emulator create_sample_emulator(emulator_settings& settings)
{
settings.application = "./test-sample.exe";
return windows_emulator{settings};
}

inline windows_emulator create_sample_emulator()
{
const emulator_settings settings
emulator_settings settings
{
.application = "./test-sample.exe",
.disable_logging = true,
.use_relative_time = true,
};

return windows_emulator{settings};
return create_sample_emulator(settings);
}
}
45 changes: 45 additions & 0 deletions src/windows-emulator-test/time_test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include "emulation_test_utils.hpp"

namespace test
{
TEST(TimeTest, SystemTimeIsAccurate)
{
std::string output_buffer{};

emulator_settings settings{
.arguments = {L"-time"},
.stdout_callback = [&output_buffer](const std::string_view data)
{
output_buffer.append(data);
},
.disable_logging = true,
.use_relative_time = false,
};

auto emu = create_sample_emulator(settings);
emu.start();

constexpr auto prefix = "Time: "sv;

ASSERT_TERMINATED_SUCCESSFULLY(emu);
ASSERT_TRUE(output_buffer.starts_with(prefix));

output_buffer = output_buffer.substr(prefix.size());
while (!output_buffer.empty() && (output_buffer.back() == '\n' || output_buffer.back() == '\r'))
{
output_buffer.pop_back();
}

const auto time = strtoll(output_buffer.c_str(), nullptr, 10);

using time_point = std::chrono::system_clock::time_point;

const time_point::duration time_duration(time);
const time_point tp(time_duration);

const auto now = std::chrono::system_clock::now();
const auto diff = now - tp;

ASSERT_LE(diff, std::chrono::hours(1));
}
}
2 changes: 2 additions & 0 deletions src/windows-emulator/emulator_utils.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,10 @@ class object_wrapper
};

class windows_emulator;
struct process_context;

using x64_emulator_wrapper = object_wrapper<x64_emulator>;
using process_context_wrapper = object_wrapper<process_context>;
using windows_emulator_wrapper = object_wrapper<windows_emulator>;

template <typename T>
Expand Down
222 changes: 222 additions & 0 deletions src/windows-emulator/kusd_mmio.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,222 @@
#include "kusd_mmio.hpp"
#include "syscall_utils.hpp"
#include "windows_emulator.hpp"

#include <address_utils.hpp>

constexpr auto KUSD_ADDRESS = 0x7ffe0000ULL;
constexpr auto KUSD_SIZE = sizeof(KUSER_SHARED_DATA);
constexpr auto KUSD_BUFFER_SIZE = page_align_up(KUSD_SIZE);

namespace
{
void setup_kusd(KUSER_SHARED_DATA& kusd, const bool use_relative_time)
{
memset(&kusd, 0, sizeof(kusd));

kusd.TickCountMultiplier = 0x0fa00000;
kusd.InterruptTime.LowPart = 0x17bd9547;
kusd.InterruptTime.High1Time = 0x0000004b;
kusd.InterruptTime.High2Time = 0x0000004b;
kusd.SystemTime.LowPart = 0x7af9da99;
kusd.SystemTime.High1Time = 0x01db27b9;
kusd.SystemTime.High2Time = 0x01db27b9;
kusd.TimeZoneBias.LowPart = 0x3c773000;
kusd.TimeZoneBias.High1Time = -17;
kusd.TimeZoneBias.High2Time = -17;
kusd.TimeZoneId = 0x00000002;
kusd.LargePageMinimum = 0x00200000;
kusd.RNGSeedVersion = 0x0000000000000013;
kusd.TimeZoneBiasStamp = 0x00000004;
kusd.NtBuildNumber = 0x00006c51;
kusd.NtProductType = NtProductWinNt;
kusd.ProductTypeIsValid = 0x01;
kusd.NativeProcessorArchitecture = 0x0009;
kusd.NtMajorVersion = 0x0000000a;
kusd.BootId = 0x0000000b;
kusd.SystemExpirationDate.QuadPart = 0x01dc26860a9ff300;
kusd.SuiteMask = 0x00000110;
kusd.MitigationPolicies.MitigationPolicies = 0x0a;
kusd.MitigationPolicies.NXSupportPolicy = 0x02;
kusd.MitigationPolicies.SEHValidationPolicy = 0x02;
kusd.CyclesPerYield = 0x0064;
kusd.DismountCount = 0x00000006;
kusd.ComPlusPackage = 0x00000001;
kusd.LastSystemRITEventTickCount = 0x01ec1fd3;
kusd.NumberOfPhysicalPages = 0x00bf0958;
kusd.FullNumberOfPhysicalPages = 0x0000000000bf0958;
kusd.TickCount.TickCount.LowPart = 0x001f7f05;
kusd.TickCount.TickCountQuad = 0x00000000001f7f05;
kusd.Cookie = 0x1c3471da;
kusd.ConsoleSessionForegroundProcessId = 0x00000000000028f4;
kusd.TimeUpdateLock = 0x0000000002b28586;
kusd.BaselineSystemTimeQpc = 0x0000004b17cd596c;
kusd.BaselineInterruptTimeQpc = 0x0000004b17cd596c;
kusd.QpcSystemTimeIncrement = 0x8000000000000000;
kusd.QpcInterruptTimeIncrement = 0x8000000000000000;
kusd.QpcSystemTimeIncrementShift = 0x01;
kusd.QpcInterruptTimeIncrementShift = 0x01;
kusd.UnparkedProcessorCount = 0x000c;
kusd.TelemetryCoverageRound = 0x00000001;
kusd.LangGenerationCount = 0x00000003;
kusd.InterruptTimeBias = 0x00000015a5d56406;
kusd.QpcBias = 0x000000159530c4af;
kusd.ActiveProcessorCount = 0x0000000c;
kusd.ActiveGroupCount = 0x01;
kusd.QpcData.QpcData = 0x0083;
kusd.QpcData.QpcBypassEnabled = 0x83;
kusd.TimeZoneBiasEffectiveStart.QuadPart = 0x01db276e654cb2ff;
kusd.TimeZoneBiasEffectiveEnd.QuadPart = 0x01db280b8c3b2800;
kusd.XState.EnabledFeatures = 0x000000000000001f;
kusd.XState.EnabledVolatileFeatures = 0x000000000000000f;
kusd.XState.Size = 0x000003c0;

if (use_relative_time)
{
kusd.QpcFrequency = 1000;
}
else
{
kusd.QpcFrequency = std::chrono::steady_clock::period::den;
}

constexpr std::wstring_view root_dir{L"C:\\WINDOWS"};
memcpy(&kusd.NtSystemRoot.arr[0], root_dir.data(), root_dir.size() * 2);

kusd.ImageNumberLow = IMAGE_FILE_MACHINE_I386;
kusd.ImageNumberHigh = IMAGE_FILE_MACHINE_AMD64;
}
}

inline void serialize(utils::buffer_serializer& buffer, const KUSER_SHARED_DATA& kusd)
{
static_assert(KUSD_SIZE == sizeof(kusd));
buffer.write(&kusd, KUSD_SIZE);
}

inline void deserialize(utils::buffer_deserializer& buffer, KUSER_SHARED_DATA& kusd)
{
buffer.read(&kusd, KUSD_SIZE);
}

kusd_mmio::kusd_mmio(x64_emulator& emu, process_context& process)
: emu_(&emu)
, process_(&process)
{
}

kusd_mmio::~kusd_mmio()
{
this->deregister_mmio();
}

kusd_mmio::kusd_mmio(utils::buffer_deserializer& buffer)
: kusd_mmio(buffer.read<x64_emulator_wrapper>(), buffer.read<process_context_wrapper>())
{
}

void kusd_mmio::setup(const bool use_relative_time)
{
this->use_relative_time_ = use_relative_time;

setup_kusd(this->kusd_, use_relative_time);
this->start_time_ = convert_from_ksystem_time(this->kusd_.SystemTime);

this->register_mmio();
}

void kusd_mmio::serialize(utils::buffer_serializer& buffer) const
{
buffer.write(this->use_relative_time_);
buffer.write(this->kusd_);
buffer.write(this->start_time_);
}

void kusd_mmio::deserialize(utils::buffer_deserializer& buffer)
{
buffer.read(this->use_relative_time_);
buffer.read(this->kusd_);
buffer.read(this->start_time_);

this->deregister_mmio();
this->register_mmio();
}

uint64_t kusd_mmio::read(const uint64_t addr, const size_t size)
{
uint64_t result{};

this->update();

if (addr >= KUSD_SIZE)
{
return result;
}

const auto end = addr + size;
const auto valid_end = std::min(end, KUSD_SIZE);
const auto real_size = valid_end - addr;

if (real_size > sizeof(result))
{
return result;
}

const auto* kusd_buffer = reinterpret_cast<uint8_t*>(&this->kusd_);
memcpy(&result, kusd_buffer + addr, real_size);

return result;
}

uint64_t kusd_mmio::address()
{
return KUSD_ADDRESS;
}

void kusd_mmio::update()
{
auto time = this->start_time_;

if (this->use_relative_time_)
{
const auto passed_time = this->process_->executed_instructions;
const auto clock_frequency = this->kusd_.QpcFrequency;

using duration = std::chrono::system_clock::duration;
time += duration(passed_time * duration::period::den / clock_frequency);
}
else
{
time = std::chrono::system_clock::now();
}

convert_to_ksystem_time(&this->kusd_.SystemTime, time);
}

void kusd_mmio::register_mmio()
{
if (this->registered_)
{
return;
}

this->registered_ = true;

this->emu_->allocate_mmio(KUSD_ADDRESS, KUSD_BUFFER_SIZE,
[this](const uint64_t addr, const size_t size)
{
return this->read(addr, size);
}, [this](const uint64_t, const size_t, const uint64_t)
{
// Writing not supported!
});
}

void kusd_mmio::deregister_mmio()
{
if (this->registered_)
{
this->registered_ = false;
this->emu_->release_memory(KUSD_ADDRESS, KUSD_BUFFER_SIZE);
}
}
Loading