#include "stdafx.h"
#include <algorithm>
#include "system_information_sampler.h"
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWCH Buffer;
} UNICODE_STRING;
typedef LONG KPRIORITY;
typedef LONG KWAIT_REASON;
typedef struct _VM_COUNTERS {
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
} VM_COUNTERS;
typedef enum _SYSTEM_INFORMATION_CLASS {
SystemBasicInformation = 0,
SystemPerformanceInformation = 2,
SystemTimeOfDayInformation = 3,
SystemProcessInformation = 5,
SystemProcessorPerformanceInformation = 8,
SystemInterruptInformation = 23,
SystemExceptionInformation = 33,
SystemRegistryQuotaInformation = 37,
SystemLookasideInformation = 45
} SYSTEM_INFORMATION_CLASS;
typedef struct {
HANDLE UniqueProcess;
HANDLE UniqueThread;
} CLIENT_ID;
struct SYSTEM_THREAD_INFORMATION {
ULONGLONG KernelTime;
ULONGLONG UserTime;
ULONGLONG CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitchCount;
ULONG State;
KWAIT_REASON WaitReason;
};
#if _M_X64
static_assert(sizeof(SYSTEM_THREAD_INFORMATION) == 80,
"Structure size mismatch");
#else
static_assert(sizeof(SYSTEM_THREAD_INFORMATION) == 64,
"Structure size mismatch");
#endif
struct SYSTEM_PROCESS_INFORMATION {
ULONG NextEntryOffset;
ULONG NumberOfThreads;
ULONGLONG WorkingSetPrivateSize;
ULONG HardFaultCount;
ULONG Reserved1;
ULONGLONG CycleTime;
ULONGLONG CreateTime;
ULONGLONG UserTime;
ULONGLONG KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE ProcessId;
HANDLE ParentProcessId;
ULONG HandleCount;
ULONG Reserved2[2];
VM_COUNTERS VirtualMemoryCounters;
size_t Reserved3;
IO_COUNTERS IoCounters;
SYSTEM_THREAD_INFORMATION Threads[1];
};
#if _M_X64
static_assert(sizeof(SYSTEM_PROCESS_INFORMATION) == 336,
"Structure size mismatch");
#else
static_assert(sizeof(SYSTEM_PROCESS_INFORMATION) == 248,
"Structure size mismatch");
#endif
#define STATUS_SUCCESS ((NTSTATUS)0x00000000L)
#define STATUS_BUFFER_TOO_SMALL ((NTSTATUS)0xC0000023L)
#define STATUS_INFO_LENGTH_MISMATCH ((NTSTATUS)0xC0000004L)
typedef NTSTATUS(WINAPI* NTQUERYSYSTEMINFORMATION)(
SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);
__declspec(noreturn) void oops(const char* pMessage) {
printf("%s\n", pMessage);
exit(0);
}
class ByteBuffer {
public:
explicit ByteBuffer(size_t capacity) : size_(0), capacity_(0) {
if (capacity > 0)
grow(capacity);
}
~ByteBuffer() {}
BYTE* data() { return data_.get(); }
size_t size() { return size_; }
void set_size(size_t new_size) { size_ = new_size; }
size_t capacity() { return capacity_; }
void grow(size_t new_capacity) {
capacity_ = new_capacity;
data_.reset(new BYTE[new_capacity]);
}
private:
std::unique_ptr<BYTE[]> data_;
size_t size_;
size_t capacity_;
ByteBuffer& operator=(const ByteBuffer&) = delete;
ByteBuffer(const ByteBuffer&) = delete;
};
bool QuerySystemProcessInformation(ByteBuffer* buffer) {
typedef NTSTATUS(WINAPI * NTQUERYSYSTEMINFORMATION)(
SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation,
ULONG SystemInformationLength, PULONG ReturnLength);
HMODULE ntdll = GetModuleHandle(L"ntdll.dll");
if (!ntdll) {
oops("Couldn't load ntdll.dll");
}
NTQUERYSYSTEMINFORMATION nt_query_system_information_ptr =
reinterpret_cast<NTQUERYSYSTEMINFORMATION>(
GetProcAddress(ntdll, "NtQuerySystemInformation"));
if (!nt_query_system_information_ptr)
oops("Couldn't find NtQuerySystemInformation");
NTSTATUS result;
for (int i = 0; i < 10; i++) {
ULONG data_size = 0;
ULONG buffer_size = static_cast<ULONG>(buffer->capacity());
result = nt_query_system_information_ptr(
SystemProcessInformation, buffer->data(), buffer_size, &data_size);
if (result == STATUS_SUCCESS) {
buffer->set_size(data_size);
break;
}
if (result == STATUS_INFO_LENGTH_MISMATCH ||
result == STATUS_BUFFER_TOO_SMALL) {
buffer->grow(static_cast<ULONG>(data_size * 1.1));
} else {
break;
}
}
return result == STATUS_SUCCESS;
}
SystemInformationSampler::SystemInformationSampler(
const wchar_t* process_name) {
lstrcpyn(target_process_name_, process_name,
sizeof(target_process_name_) / sizeof(wchar_t));
errno = 0;
wchar_t* end_ptr;
target_process_id_ = wcstoul(target_process_name_, &end_ptr, 10);
if (errno != 0 || target_process_id_ < 0 || *end_ptr != L'\0')
target_process_id_ = 0;
QueryPerformanceFrequency(&perf_frequency_);
QueryPerformanceCounter(&initial_counter_);
}
SystemInformationSampler::~SystemInformationSampler() {}
ProcessData GetProcessData(const SYSTEM_PROCESS_INFORMATION* const pi) {
ProcessData process_data;
process_data.cpu_time = pi->KernelTime + pi->UserTime;
process_data.memory = pi->VirtualMemoryCounters.PagefileUsage;
process_data.handle_count = pi->HandleCount;
for (ULONG thread_index = 0; thread_index < pi->NumberOfThreads;
++thread_index) {
const SYSTEM_THREAD_INFORMATION* ti = &pi->Threads[thread_index];
if (ti->ClientId.UniqueProcess != pi->ProcessId)
continue;
ThreadData thread_data;
thread_data.thread_id = ti->ClientId.UniqueThread;
thread_data.context_switches = ti->ContextSwitchCount;
process_data.threads.push_back(thread_data);
}
std::sort(process_data.threads.begin(), process_data.threads.end(),
[](const ThreadData& l, const ThreadData r) {
return l.thread_id < r.thread_id;
});
return process_data;
}
std::unique_ptr<ProcessDataSnapshot> SystemInformationSampler::TakeSnapshot() {
ByteBuffer data_buffer(previous_buffer_size_);
if (!QuerySystemProcessInformation(&data_buffer))
return std::unique_ptr<ProcessDataSnapshot>();
previous_buffer_size_ = data_buffer.capacity();
std::unique_ptr<ProcessDataSnapshot> snapshot(new ProcessDataSnapshot);
LARGE_INTEGER perf_counter_value;
QueryPerformanceCounter(&perf_counter_value);
snapshot->timestamp = static_cast<double>(
(perf_counter_value.QuadPart - initial_counter_.QuadPart) /
perf_frequency_.QuadPart);
for (size_t offset = 0; offset < data_buffer.size();) {
if (offset + sizeof(SYSTEM_PROCESS_INFORMATION) > data_buffer.size())
break;
auto pi = reinterpret_cast<const SYSTEM_PROCESS_INFORMATION*>(
data_buffer.data() + offset);
if (pi->NumberOfThreads > 0) {
if (offset + sizeof(SYSTEM_PROCESS_INFORMATION) +
(pi->NumberOfThreads - 1) * sizeof(SYSTEM_THREAD_INFORMATION) >
data_buffer.size()) {
break;
}
if (target_process_id_ > 0) {
if (reinterpret_cast<uintptr_t>(pi->ProcessId) == target_process_id_ ||
reinterpret_cast<uintptr_t>(pi->ParentProcessId) ==
target_process_id_) {
snapshot->processes.insert(
std::make_pair(pi->ProcessId, GetProcessData(pi)));
}
} else if (pi->ImageName.Buffer) {
size_t image_name_offset =
reinterpret_cast<BYTE*>(pi->ImageName.Buffer) - data_buffer.data();
if (image_name_offset + pi->ImageName.Length > data_buffer.size())
break;
if (wcsncmp(target_process_name_filter(), pi->ImageName.Buffer,
lstrlen(target_process_name_filter())) == 0) {
if (wcscmp(target_process_name_filter(), L"System") != 0 ||
wcslen(pi->ImageName.Buffer) == 6)
snapshot->processes.insert(
std::make_pair(pi->ProcessId, GetProcessData(pi)));
}
}
}
if (!pi->NextEntryOffset)
break;
offset += pi->NextEntryOffset;
}
return snapshot;
}