Files
DN/Source/OS/dn_os_w32.cpp
T

2639 lines
102 KiB
C++

#if defined(_CLANGD)
#define DN_WITH_OS 1
#include "../dn.h"
#include "dn_os_w32.h"
#include <windows.h>
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: DN OS layer implementation
static DN_U32 DN_Os_MemConvertPageToOSFlags_(DN_U32 protect)
{
DN_Assert((protect & ~DN_MemPage_All) == 0);
DN_Assert(protect != 0);
DN_U32 result = 0;
if (protect & DN_MemPage_NoAccess) {
result = PAGE_NOACCESS;
} else if (protect & DN_MemPage_ReadWrite) {
result = PAGE_READWRITE;
} else if (protect & DN_MemPage_Read) {
result = PAGE_READONLY;
} else if (protect & DN_MemPage_Write) {
DN_LogWarningF("Windows does not support write-only pages, granting read+write access");
result = PAGE_READWRITE;
}
if (protect & DN_MemPage_Guard)
result |= PAGE_GUARD;
DN_AssertF(result != PAGE_GUARD, "Page guard is a modifier, you must also specify a page permission like read or/and write");
return result;
}
DN_API void *DN_Os_MemReserve(DN_USize size, DN_MemCommit commit, DN_U32 page_flags)
{
unsigned long os_page_flags = DN_Os_MemConvertPageToOSFlags_(page_flags);
unsigned long flags = MEM_RESERVE;
if (commit == DN_MemCommit_Yes)
flags |= MEM_COMMIT;
void *result = VirtualAlloc(NULL, size, flags, os_page_flags);
if (result)
DN_GlobalMemStatsReserve(size, (flags & MEM_COMMIT) != 0);
return result;
}
DN_API bool DN_Os_MemCommit(void *ptr, DN_USize size, DN_U32 page_flags)
{
bool result = false;
if (!ptr || size == 0)
return false;
unsigned long os_page_flags = DN_Os_MemConvertPageToOSFlags_(page_flags);
result = VirtualAlloc(ptr, size, MEM_COMMIT, os_page_flags) != NULL;
if (result)
DN_GlobalMemStatsCommit(size);
return result;
}
DN_API void DN_Os_MemDecommit(void *ptr, DN_USize size)
{
// NOTE: This is a decommit call, which is explicitly saying to free the
// pages but not the address space, you would use OS_MemRelease to release
// everything.
DN_MSVC_WARNING_PUSH
DN_MSVC_WARNING_DISABLE(6250) // Calling 'VirtualFree' without the MEM_RELEASE flag might free memory but not address descriptors (VADs). This causes address space leaks.
BOOL ok = VirtualFree(ptr, size, MEM_DECOMMIT);
if (ok)
DN_GlobalMemStatsDecommit(size);
DN_MSVC_WARNING_POP
}
DN_API void DN_Os_MemRelease(void *ptr, DN_USize reserve, DN_USize commit)
{
BOOL ok = VirtualFree(ptr, 0, MEM_RELEASE);
if (ok)
DN_GlobalMemStatsRelease(reserve, commit);
}
DN_API int DN_Os_MemProtect(void *ptr, DN_USize size, DN_U32 page_flags)
{
if (!ptr || size == 0)
return 0;
DN_Str8 const ALIGNMENT_ERROR_MSG = DN_Str8Lit("Page protection requires pointers to be page aligned because we can only guard memory at a multiple of the page boundary.");
DN_AssertF(DN_IsPowerOfTwoAligned(DN_Cast(uintptr_t) ptr, DN_Get()->os.page_size), "%s", ALIGNMENT_ERROR_MSG.data);
DN_AssertF(DN_IsPowerOfTwoAligned(size, DN_Get()->os.page_size), "%s", ALIGNMENT_ERROR_MSG.data);
unsigned long os_page_flags = DN_Os_MemConvertPageToOSFlags_(page_flags);
unsigned long prev_flags = 0;
int result = VirtualProtect(ptr, size, os_page_flags, &prev_flags);
(void)prev_flags;
if (result == 0)
DN_AssertF(result, "VirtualProtect failed");
return result;
}
DN_API void *DN_Os_MemAlloc(DN_USize size, DN_ZMem z_mem)
{
DN_U32 flags = z_mem == DN_ZMem_Yes ? HEAP_ZERO_MEMORY : 0;
DN_Assert(size <= DN_Cast(DWORD)(-1));
void *result = HeapAlloc(GetProcessHeap(), flags, DN_Cast(DWORD) size);
if (result)
DN_GlobalMemStatsAlloc(size);
return result;
}
DN_API void DN_Os_MemDealloc(void *ptr, DN_USize size)
{
if (ptr)
DN_GlobalMemStatsDealloc(size);
HeapFree(GetProcessHeap(), 0, ptr);
}
// NOTE: Date
DN_API DN_Date DN_Os_DateLocalTimeNow()
{
SYSTEMTIME sys_time;
GetLocalTime(&sys_time);
DN_Date result = DN_ZeroInit;
result.hour = DN_Cast(DN_U8) sys_time.wHour;
result.milliseconds = DN_Cast(DN_U8) sys_time.wMilliseconds;
result.minutes = DN_Cast(DN_U8) sys_time.wMinute;
result.seconds = DN_Cast(DN_U8) sys_time.wSecond;
result.day = DN_Cast(DN_U8) sys_time.wDay;
result.month = DN_Cast(DN_U8) sys_time.wMonth;
result.year = DN_Cast(DN_U16) sys_time.wYear;
return result;
}
const DN_U64 DN_Os_WIN32_UNIX_TIME_START = 0x019DB1DED53E8000; // January 1, 1970 (start of Unix epoch) in "ticks"
const DN_U64 DN_Os_WIN32_FILE_TIME_TICKS_PER_SECOND = 10000000; // Filetime returned is in intervals of 100 nanoseconds
DN_API DN_U64 DN_Os_DateUnixTimeNs()
{
FILETIME file_time;
GetSystemTimeAsFileTime(&file_time);
// NOTE: Filetime returned is in intervals of 100 nanoeseconds so we
// multiply by 100 to get nanoseconds.
LARGE_INTEGER date_time;
date_time.u.LowPart = file_time.dwLowDateTime;
date_time.u.HighPart = file_time.dwHighDateTime;
DN_U64 result = (date_time.QuadPart - DN_Os_WIN32_UNIX_TIME_START) * 100;
return result;
}
static SYSTEMTIME DN_Os_DateToSystemTime_(DN_Date date)
{
SYSTEMTIME result = DN_ZeroInit;
result.wYear = date.year;
result.wMonth = date.month;
result.wDay = date.day;
result.wHour = date.hour;
result.wMinute = date.minutes;
result.wSecond = date.seconds;
result.wMilliseconds = date.milliseconds;
return result;
}
static DN_U64 DN_Os_SystemTimeToUnixTimeS_(SYSTEMTIME *sys_time)
{
FILETIME file_time = DN_ZeroInit;
SystemTimeToFileTime(sys_time, &file_time);
LARGE_INTEGER date_time;
date_time.u.LowPart = file_time.dwLowDateTime;
date_time.u.HighPart = file_time.dwHighDateTime;
DN_U64 result = (date_time.QuadPart - DN_Os_WIN32_UNIX_TIME_START) / DN_Os_WIN32_FILE_TIME_TICKS_PER_SECOND;
return result;
}
DN_API DN_U64 DN_Os_DateUnixTimeSFromLocalDate(DN_Date date)
{
SYSTEMTIME local_time = DN_Os_DateToSystemTime_(date);
SYSTEMTIME sys_time = DN_ZeroInit;
TzSpecificLocalTimeToSystemTime(NULL, &local_time, &sys_time);
DN_U64 result = DN_Os_SystemTimeToUnixTimeS_(&sys_time);
return result;
}
DN_API DN_U64 DN_Os_DateLocalUnixTimeSFromUnixTimeS(DN_U64 unix_ts_s)
{
DN_U64 unix_time = DN_Cast(DN_U64) unix_ts_s * 10000000LL; // seconds -> 100ns units
DN_U64 filetime_utc = unix_time + 116444736000000000LL; // Unix epoch -> Windows epoch
FILETIME ft_utc = {DN_Cast(DWORD) filetime_utc, DN_Cast(DWORD)(filetime_utc >> 32)};
FILETIME ft_local;
bool converted = FileTimeToLocalFileTime(&ft_utc, &ft_local);
DN_Assert(converted);
DN_U64 filetime_local = (DN_Cast(DN_U64) ft_local.dwHighDateTime << 32) | ft_local.dwLowDateTime;
DN_U64 result = (filetime_local - 116444736000000000LL) / 10000000LL;
return result;
}
DN_API void DN_Os_GenBytesSecure(void *buffer, DN_U32 size)
{
DN_OsW32Core *w32 = DN_Cast(DN_OsW32Core *) DN_Get()->os.platform_context;
DN_Assert(w32->bcrypt_init_success);
long gen_status = BCryptGenRandom(w32->bcrypt_rng_handle, DN_Cast(unsigned char *) buffer, size, 0 /*flags*/);
// NOTE: This can only fail if the handle is invalid or one or more parameters are invalid. We
// validate our parameters so this shouldn't be the case.
DN_Assert(gen_status == 0);
}
DN_API DN_OsDiskSpace DN_Os_DiskSpace(DN_Str8 path)
{
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsDiskSpace result = DN_ZeroInit;
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
ULARGE_INTEGER free_bytes_avail_to_caller;
ULARGE_INTEGER total_number_of_bytes;
ULARGE_INTEGER total_number_of_free_bytes;
if (!GetDiskFreeSpaceExW(path16.data,
&free_bytes_avail_to_caller,
&total_number_of_bytes,
&total_number_of_free_bytes)) {
DN_TcScratchEnd(&scratch);
return result;
}
result.success = true;
result.avail = free_bytes_avail_to_caller.QuadPart;
result.size = total_number_of_bytes.QuadPart;
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsMemoryInfo DN_Os_MemoryInfo()
{
DN_OsMemoryInfo result = DN_ZeroInit;
MEMORYSTATUSEX status = DN_ZeroInit;
status.dwLength = sizeof(status);
if (GlobalMemoryStatusEx(&status)) {
result.success = true;
result.total_phys = status.ullTotalPhys;
result.avail_phys = status.ullAvailPhys;
result.total_virtual = status.ullTotalVirtual;
result.avail_virtual = status.ullAvailVirtual;
}
return result;
}
DN_API DN_OsSysMonitor DN_Os_SysMonitor(DN_OsSysMonitorContext *context)
{
DN_OsSysMonitor result = DN_ZeroInit;
if (!context)
return result;
DN_U64 now_tsc = DN_Os_PerfCounterNow();
// NOTE: CPU usage
{
FILETIME idle_ft = {};
FILETIME kernel_ft = {};
FILETIME user_ft = {};
if (GetSystemTimes(&idle_ft, &kernel_ft, &user_ft)) {
DN_U64 idle = ((DN_U64)idle_ft.dwHighDateTime << 32) | idle_ft.dwLowDateTime;
DN_U64 kernel = ((DN_U64)kernel_ft.dwHighDateTime << 32) | kernel_ft.dwLowDateTime;
DN_U64 user = ((DN_U64)user_ft.dwHighDateTime << 32) | user_ft.dwLowDateTime;
if (context->cpu_initialised) {
DN_U64 idle_delta = idle - context->prev_cpu_idle;
DN_U64 kernel_delta = kernel - context->prev_cpu_kernel;
DN_U64 user_delta = user - context->prev_cpu_user;
DN_U64 total_delta = kernel_delta + user_delta;
if (total_delta > 0) {
result.cpu_usage_pct = DN_Cast(DN_F32)((total_delta - idle_delta) * 100.0 / total_delta);
result.cpu_usage_valid = true;
}
}
context->prev_cpu_idle = idle;
context->prev_cpu_kernel = kernel;
context->prev_cpu_user = user;
context->cpu_initialised = true;
}
}
// NOTE: CPU clock speed
{
SYSTEM_INFO system_info = {};
GetSystemInfo(&system_info);
if (system_info.dwNumberOfProcessors > 0) {
DN_USize processor_count = system_info.dwNumberOfProcessors;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
PROCESSOR_POWER_INFORMATION *power_info = DN_ArenaNewArray(&scratch.arena, PROCESSOR_POWER_INFORMATION, processor_count, DN_ZMem_Yes);
ULONG power_info_size = DN_Cast(ULONG)(processor_count * sizeof(*power_info));
if (CallNtPowerInformation(ProcessorInformation, NULL, 0, power_info, power_info_size) == 0) {
DN_U64 total_mhz = 0;
DN_U64 count = 0;
for (DN_USize i = 0; i < processor_count; i++) {
if (power_info[i].CurrentMhz > 0) {
total_mhz += power_info[i].CurrentMhz;
count++;
}
}
if (count > 0)
result.cpu_clock_mhz = DN_Cast(DN_U32)(total_mhz / count);
}
DN_TcScratchEnd(&scratch);
}
}
// NOTE: Memory usage
{
DN_OsMemoryInfo mem_info = DN_Os_MemoryInfo();
if (mem_info.success && mem_info.total_phys > 0) {
result.mem_total_bytes = mem_info.total_phys;
result.mem_used_bytes = mem_info.total_phys > mem_info.avail_phys ? mem_info.total_phys - mem_info.avail_phys : 0;
result.mem_usage_pct = DN_Cast(DN_F32)(result.mem_used_bytes * 100.0 / mem_info.total_phys);
}
}
// NOTE: Network usage
{
MIB_IF_TABLE2 *if_table = NULL;
if (GetIfTable2(&if_table) == NO_ERROR && if_table) {
DN_U64 in_octets = 0;
DN_U64 out_octets = 0;
for (ULONG i = 0; i < if_table->NumEntries; i++) {
MIB_IF_ROW2 *row = &if_table->Table[i];
if (row->OperStatus == IfOperStatusUp &&
row->InterfaceAndOperStatusFlags.HardwareInterface &&
row->Type != IF_TYPE_SOFTWARE_LOOPBACK) {
in_octets += row->InOctets;
out_octets += row->OutOctets;
}
}
FreeMibTable(if_table);
if (context->net_initialised) {
DN_F64 elapsed_s = DN_Os_PerfCounterS(context->prev_net_tsc, now_tsc);
if (elapsed_s > 0) {
DN_U64 in_delta = in_octets > context->prev_net_in ? in_octets - context->prev_net_in : 0;
DN_U64 out_delta = out_octets > context->prev_net_out ? out_octets - context->prev_net_out : 0;
result.net_down_bytes_per_s = DN_Cast(DN_U64)(in_delta / elapsed_s);
result.net_up_bytes_per_s = DN_Cast(DN_U64)(out_delta / elapsed_s);
}
}
context->prev_net_in = in_octets;
context->prev_net_out = out_octets;
context->prev_net_tsc = now_tsc;
context->net_initialised = true;
}
}
// NOTE: GPU usage and CPU temperature via PDH
if (!context->pdh_initialised) {
context->pdh_initialised = true;
PDH_HQUERY query = NULL;
if (PdhOpenQueryW(NULL, 0, &query) == ERROR_SUCCESS) {
PDH_HCOUNTER gpu_counter = NULL;
PDH_HCOUNTER thermal_counter = NULL;
PDH_HCOUNTER gpu_vram_counter = NULL;
PDH_HCOUNTER gpu_shared_counter = NULL;
PdhAddEnglishCounterW(query, L"\\GPU Engine(*)\\Utilization Percentage", 0, &gpu_counter);
PdhAddEnglishCounterW(query, L"\\Thermal Zone Information(*)\\Temperature", 0, &thermal_counter);
PdhAddEnglishCounterW(query, L"\\GPU Adapter Memory(*)\\Dedicated Usage", 0, &gpu_vram_counter);
PdhAddEnglishCounterW(query, L"\\GPU Adapter Memory(*)\\Shared Usage", 0, &gpu_shared_counter);
PdhCollectQueryData(query);
context->pdh_query = DN_Cast(DN_UPtr) query;
context->gpu_engine_counter = DN_Cast(DN_UPtr) gpu_counter;
context->thermal_zone_counter = DN_Cast(DN_UPtr) thermal_counter;
context->gpu_vram_counter = DN_Cast(DN_UPtr) gpu_vram_counter;
context->gpu_shared_memory_counter = DN_Cast(DN_UPtr) gpu_shared_counter;
}
} else if (context->pdh_query) {
PDH_HQUERY query = DN_Cast(PDH_HQUERY) context->pdh_query;
if (PdhCollectQueryData(query) == ERROR_SUCCESS) {
// NOTE: GPU usage: sum per engine type, then take the busiest engine
if (context->gpu_engine_counter) {
PDH_HCOUNTER gpu_counter = DN_Cast(PDH_HCOUNTER) context->gpu_engine_counter;
DWORD buffer_size = 0;
DWORD item_count = 0;
PDH_STATUS status = PdhGetFormattedCounterArrayW(gpu_counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, NULL);
if (status == PDH_MORE_DATA && buffer_size > 0) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_U8 *buffer = DN_ArenaNewArray(&scratch.arena, DN_U8, buffer_size, DN_ZMem_No);
status = PdhGetFormattedCounterArrayW(gpu_counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer);
if (status == ERROR_SUCCESS && buffer) {
PDH_FMT_COUNTERVALUE_ITEM_W *items = DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer;
struct
{
DN_Str8x32 name;
DN_F64 value;
} engines[8] = {};
DN_USize engine_count = 0;
for (DWORD i = 0; i < item_count; i++) {
PDH_FMT_COUNTERVALUE_ITEM_W *item = &items[i];
if (item->FmtValue.CStatus != PDH_CSTATUS_VALID_DATA && item->FmtValue.CStatus != PDH_CSTATUS_NEW_DATA)
continue;
WCHAR const *engine_type = wcsstr(item->szName, L"engtype_");
if (engine_type)
engine_type += 8;
else
engine_type = L"unknown";
DN_Str8x32 name = {};
DN_Str16 name16 = {DN_Cast(WCHAR *) engine_type, DN_Cast(DN_USize) lstrlenW(engine_type)};
int name_size = DN_Os_W32Str8FromStr16Buffer(name16, name.data, DN_Cast(int) DN_ArrayCountU(name.data));
name.count = name_size > 0 ? DN_Cast(DN_USize) DN_Min(name_size, DN_Cast(int) DN_ArrayCountU(name.data) - 1) : DN_Cast(DN_USize) 0;
DN_USize engine_index = 0;
for (; engine_index < engine_count; engine_index++) {
if (strcmp(engines[engine_index].name.data, name.data) == 0)
break;
}
if (engine_index == engine_count && engine_count < DN_ArrayCountU(engines)) {
engines[engine_count].name = name;
engine_count++;
}
if (engine_index < engine_count)
engines[engine_index].value += item->FmtValue.doubleValue;
}
DN_F64 max_engine_usage = 0;
for (DN_USize i = 0; i < engine_count; i++) {
if (engines[i].value > max_engine_usage)
max_engine_usage = engines[i].value;
}
if (engine_count > 0) {
result.gpu_usage_pct = DN_Cast(DN_F32) DN_Min(max_engine_usage, 100.0);
result.gpu_usage_valid = true;
}
}
DN_TcScratchEnd(&scratch);
}
}
// NOTE: CPU temperature via ACPI thermal zone
if (context->thermal_zone_counter) {
PDH_HCOUNTER thermal_counter = DN_Cast(PDH_HCOUNTER) context->thermal_zone_counter;
DWORD buffer_size = 0;
DWORD item_count = 0;
PDH_STATUS status = PdhGetFormattedCounterArrayW(thermal_counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, NULL);
if (status == PDH_MORE_DATA && buffer_size > 0) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_U8 *buffer = DN_ArenaNewArray(&scratch.arena, DN_U8, buffer_size, DN_ZMem_No);
status = PdhGetFormattedCounterArrayW(thermal_counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer);
if (status == ERROR_SUCCESS && buffer) {
PDH_FMT_COUNTERVALUE_ITEM_W *items = DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer;
DN_F64 max_temp_k = 0;
for (DWORD i = 0; i < item_count; i++) {
PDH_FMT_COUNTERVALUE_ITEM_W *item = &items[i];
if (item->FmtValue.CStatus == PDH_CSTATUS_VALID_DATA || item->FmtValue.CStatus == PDH_CSTATUS_NEW_DATA) {
if (item->FmtValue.doubleValue > max_temp_k)
max_temp_k = item->FmtValue.doubleValue;
}
}
if (max_temp_k > 0) {
result.cpu_temp_c = DN_Cast(DN_F32)(max_temp_k - 273.15);
result.cpu_temp_valid = true;
}
}
DN_TcScratchEnd(&scratch);
}
}
// NOTE: GPU memory usage (dedicated VRAM and shared system memory)
{
DN_UPtr memory_counters[2] = {context->gpu_vram_counter, context->gpu_shared_memory_counter};
DN_U64 *memory_outputs[2] = {&result.gpu_vram_used_bytes, &result.gpu_shared_used_bytes};
for (DN_USize memory_index = 0; memory_index < 2; memory_index++) {
if (!memory_counters[memory_index])
continue;
PDH_HCOUNTER counter = DN_Cast(PDH_HCOUNTER) memory_counters[memory_index];
DWORD buffer_size = 0;
DWORD item_count = 0;
PDH_STATUS status = PdhGetFormattedCounterArrayW(counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, NULL);
if (status == PDH_MORE_DATA && buffer_size > 0) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_U8 *buffer = DN_ArenaNewArray(&scratch.arena, DN_U8, buffer_size, DN_ZMem_No);
status = PdhGetFormattedCounterArrayW(counter, PDH_FMT_DOUBLE, &buffer_size, &item_count, DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer);
if (status == ERROR_SUCCESS && buffer) {
PDH_FMT_COUNTERVALUE_ITEM_W *items = DN_Cast(PDH_FMT_COUNTERVALUE_ITEM_W *) buffer;
DN_F64 total = 0;
for (DWORD i = 0; i < item_count; i++) {
PDH_FMT_COUNTERVALUE_ITEM_W *item = &items[i];
if (item->FmtValue.CStatus == PDH_CSTATUS_VALID_DATA || item->FmtValue.CStatus == PDH_CSTATUS_NEW_DATA)
total += item->FmtValue.doubleValue;
}
if (total > 0)
*memory_outputs[memory_index] = DN_Cast(DN_U64) total;
}
DN_TcScratchEnd(&scratch);
}
}
}
}
}
// NOTE: GPU temperature via D3DKMT
{
D3DKMT_ADAPTERINFO adapters[16] = {};
D3DKMT_ENUMADAPTERS2 enum_adapters = {};
enum_adapters.NumAdapters = DN_Cast(ULONG) DN_ArrayCountU(adapters);
enum_adapters.pAdapters = adapters;
if (D3DKMTEnumAdapters2(&enum_adapters) == 0) {
for (UINT i = 0; i < enum_adapters.NumAdapters; i++) {
// NOTE: GPU name
{
D3DKMT_ADAPTERREGISTRYINFO registry_info = {};
D3DKMT_QUERYADAPTERINFO query = {};
query.hAdapter = adapters[i].hAdapter;
query.Type = KMTQAITYPE_ADAPTERREGISTRYINFO;
query.pPrivateDriverData = &registry_info;
query.PrivateDriverDataSize = sizeof(registry_info);
if (D3DKMTQueryAdapterInfo(&query) == 0 && registry_info.AdapterString[0] && result.gpu_name.count == 0) {
DN_Str16 name16 = {registry_info.AdapterString, DN_Cast(DN_USize) lstrlenW(registry_info.AdapterString)};
int name_size = DN_Os_W32Str8FromStr16Buffer(name16, result.gpu_name.data, DN_Cast(int) DN_ArrayCountU(result.gpu_name.data));
result.gpu_name.count = name_size > 0 ? DN_Cast(DN_USize) DN_Min(name_size, DN_Cast(int) DN_ArrayCountU(result.gpu_name.data) - 1) : DN_Cast(DN_USize) 0;
}
}
// NOTE: GPU temperature and memory clock
{
D3DKMT_ADAPTER_PERFDATA perf = {};
D3DKMT_QUERYADAPTERINFO query = {};
query.hAdapter = adapters[i].hAdapter;
query.Type = KMTQAITYPE_ADAPTERPERFDATA;
query.pPrivateDriverData = &perf;
query.PrivateDriverDataSize = sizeof(perf);
if (D3DKMTQueryAdapterInfo(&query) == 0) {
if (perf.Temperature > 0) {
result.gpu_temp_c = DN_Cast(DN_F32) perf.Temperature / 10.0f;
result.gpu_temp_valid = true;
}
if (perf.MemoryFrequency > 0) {
DN_U32 memory_clock_mhz = DN_Cast(DN_U32)(perf.MemoryFrequency / 1000000);
if (memory_clock_mhz > result.gpu_memory_clock_mhz)
result.gpu_memory_clock_mhz = memory_clock_mhz;
}
}
}
// NOTE: GPU core clock
{
DN_U64 max_frequency = 0;
for (UINT node_index = 0; node_index < 8; node_index++) {
D3DKMT_NODE_PERFDATA node_perf = {};
node_perf.NodeOrdinal = node_index;
node_perf.PhysicalAdapterIndex = 0;
D3DKMT_QUERYADAPTERINFO query = {};
query.hAdapter = adapters[i].hAdapter;
query.Type = KMTQAITYPE_NODEPERFDATA;
query.pPrivateDriverData = &node_perf;
query.PrivateDriverDataSize = sizeof(node_perf);
if (D3DKMTQueryAdapterInfo(&query) == 0 && node_perf.Frequency > max_frequency)
max_frequency = node_perf.Frequency;
}
if (max_frequency > 0)
result.gpu_core_clock_mhz = DN_Cast(DN_U32)(max_frequency / 1000000);
}
D3DKMT_CLOSEADAPTER close = {};
close.hAdapter = adapters[i].hAdapter;
D3DKMTCloseAdapter(&close);
}
}
}
// NOTE: Drives and drive temperatures
{
bool refresh_drives = !context->drives_initialised || DN_Os_PerfCounterS(context->drives_tsc, now_tsc) >= 5.0;
if (refresh_drives) {
WCHAR roots[512] = {};
DWORD root_bytes = GetLogicalDriveStringsW(DN_Cast(DWORD) DN_ArrayCountU(roots), roots);
if (root_bytes > 0 && root_bytes < DN_ArrayCountU(roots)) {
DN_OsSysMonitorDrive drives[DN_OS_SYS_MONITOR_MAX_DRIVES] = {};
DN_F32 disk_temp[DN_OS_SYS_MONITOR_MAX_DRIVES] = {};
bool disk_temp_valid[DN_OS_SYS_MONITOR_MAX_DRIVES] = {};
DN_USize drive_count = 0;
DN_U64 total_free = 0;
DN_U64 total_space = 0;
for (WCHAR *root = roots; *root && drive_count < DN_ArrayCountU(drives); root += lstrlenW(root) + 1) {
DN_OsSysMonitorDrive *drive = &drives[drive_count];
drive->physical_disk_number = 0xFFFFFFFFu;
drive->drive_type = GetDriveTypeW(root);
DN_Str16 root16 = {root, DN_Cast(DN_USize) lstrlenW(root)};
int root_written = DN_Os_W32Str8FromStr16Buffer(root16, drive->root.data, DN_Cast(int) DN_ArrayCountU(drive->root.data));
drive->root.count = root_written > 0 ? DN_Cast(DN_USize) DN_Min(root_written, DN_Cast(int) DN_ArrayCountU(drive->root.data) - 1) : DN_Cast(DN_USize) 0;
WCHAR volume_label[64] = {};
WCHAR file_system[16] = {};
DWORD serial_number = 0;
DWORD max_component = 0;
DWORD fs_flags = 0;
if (GetVolumeInformationW(root, volume_label, DN_Cast(DWORD) DN_ArrayCountU(volume_label), &serial_number, &max_component, &fs_flags, file_system, DN_Cast(DWORD) DN_ArrayCountU(file_system))) {
DN_Str16 label16 = {volume_label, DN_Cast(DN_USize) lstrlenW(volume_label)};
int label_written = DN_Os_W32Str8FromStr16Buffer(label16, drive->label.data, DN_Cast(int) DN_ArrayCountU(drive->label.data));
drive->label.count = label_written > 0 ? DN_Cast(DN_USize) DN_Min(label_written, DN_Cast(int) DN_ArrayCountU(drive->label.data) - 1) : DN_Cast(DN_USize) 0;
}
ULARGE_INTEGER free_avail = {};
ULARGE_INTEGER total = {};
ULARGE_INTEGER free_total = {};
if (GetDiskFreeSpaceExW(root, &free_avail, &total, &free_total)) {
drive->space_valid = true;
drive->free_bytes = free_avail.QuadPart;
drive->total_bytes = total.QuadPart;
total_free += drive->free_bytes;
total_space += drive->total_bytes;
}
if (drive->drive_type == DRIVE_FIXED || drive->drive_type == DRIVE_REMOVABLE) {
WCHAR volume_path[8] = L"\\\\.\\C:";
volume_path[4] = root[0];
HANDLE volume = CreateFileW(volume_path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (volume != INVALID_HANDLE_VALUE) {
struct { VOLUME_DISK_EXTENTS extents; DISK_EXTENT extra[7]; } extents = {};
DWORD bytes_returned = 0;
if (DeviceIoControl(volume, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, &extents, sizeof(extents), &bytes_returned, NULL) && extents.extents.NumberOfDiskExtents > 0) {
DN_U32 disk_number = extents.extents.Extents[0].DiskNumber;
drive->physical_disk_number = disk_number;
if (disk_number < DN_ArrayCountU(disk_temp)) {
if (!disk_temp_valid[disk_number]) {
WCHAR physical_path[64] = {};
wsprintfW(physical_path, L"\\\\.\\PhysicalDrive%u", disk_number);
HANDLE physical = CreateFileW(physical_path, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
if (physical != INVALID_HANDLE_VALUE) {
STORAGE_PROPERTY_QUERY query = {};
query.PropertyId = StorageDeviceTemperatureProperty;
query.QueryType = PropertyStandardQuery;
STORAGE_TEMPERATURE_DATA_DESCRIPTOR temperature = {};
DWORD temp_bytes = 0;
if (DeviceIoControl(physical, IOCTL_STORAGE_QUERY_PROPERTY, &query, sizeof(query), &temperature, sizeof(temperature), &temp_bytes, NULL)) {
if (temperature.InfoCount > 0 && temperature.TemperatureInfo[0].Temperature > 0) {
disk_temp[disk_number] = temperature.TemperatureInfo[0].Temperature;
disk_temp_valid[disk_number] = true;
}
}
CloseHandle(physical);
}
}
if (disk_temp_valid[disk_number]) {
drive->temp_c = disk_temp[disk_number];
drive->temp_valid = true;
}
}
}
CloseHandle(volume);
}
}
drive_count++;
}
if (drive_count > 0) {
DN_Memcpy(context->drives, drives, sizeof(context->drives));
context->drives_count = drive_count;
context->drives_total_free = total_free;
context->drives_total_space = total_space;
context->drives_initialised = true;
}
}
context->drives_tsc = now_tsc;
}
if (context->drives_initialised) {
DN_Memcpy(result.drives, context->drives, sizeof(result.drives));
result.drive_count = context->drives_count;
result.total_free_bytes = context->drives_total_free;
result.total_space_bytes = context->drives_total_space;
for (DN_USize i = 0; i < result.drive_count; i++) {
if (result.drives[i].temp_valid && result.drives[i].temp_c > result.hdd_temp_c) {
result.hdd_temp_c = result.drives[i].temp_c;
result.hdd_temp_valid = true;
}
}
}
}
return result;
}
DN_API void DN_Os_SysMonitorDeinit(DN_OsSysMonitorContext *context)
{
if (!context)
return;
if (context->pdh_query)
PdhCloseQuery(DN_Cast(PDH_HQUERY) context->pdh_query);
*context = DN_ZeroInit;
}
DN_API bool DN_Os_SetEnvVar(DN_Str8 name, DN_Str8 value)
{
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 name16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, name);
DN_Str16 value16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, value);
bool result = SetEnvironmentVariableW(name16.data, value16.data) != 0;
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_Str8 DN_Os_ExePath(DN_Arena *arena)
{
DN_Str8 result = DN_ZeroInit;
if (!arena)
return result;
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str16 exe_dir16 = DN_Os_W32ExePathW(&scratch.arena);
result = DN_Os_W32Str8FromStr16Arena(arena, exe_dir16);
DN_TcScratchEnd(&scratch);
return result;
}
DN_API void DN_Os_SleepMs(DN_UInt milliseconds)
{
Sleep(milliseconds);
}
DN_API DN_U64 DN_Os_PerfCounterFrequency()
{
DN_OsW32Core *w32 = DN_Cast(DN_OsW32Core *) DN_Get()->os.platform_context;
DN_Assert(w32->qpc_frequency.QuadPart);
DN_U64 result = w32->qpc_frequency.QuadPart;
return result;
}
DN_API DN_U64 DN_Os_PerfCounterNow()
{
LARGE_INTEGER integer = DN_ZeroInit;
QueryPerformanceCounter(&integer);
DN_U64 result = integer.QuadPart;
return result;
}
static DN_U64 DN_Os_W32FileTimeToSeconds_(FILETIME const *time)
{
ULARGE_INTEGER time_large_int = DN_ZeroInit;
time_large_int.u.LowPart = time->dwLowDateTime;
time_large_int.u.HighPart = time->dwHighDateTime;
DN_U64 result = (time_large_int.QuadPart / 10000000ULL) - 11644473600ULL;
return result;
}
DN_API bool DN_Os_FileCopy(DN_Str8 src, DN_Str8 dest, bool overwrite, DN_ErrSink *err)
{
bool result = false;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 src16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, src);
DN_Str16 dest16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, dest);
int fail_if_exists = overwrite == false;
result = CopyFileW(src16.data, dest16.data, fail_if_exists) != 0;
if (!result) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(err,
win_error.code,
"Failed to copy file '%.*s' to '%.*s': (%u) %.*s",
DN_Str8PrintFmt(src),
DN_Str8PrintFmt(dest),
win_error.code,
DN_Str8PrintFmt(win_error.msg));
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_FileMove(DN_Str8 src, DN_Str8 dest, bool overwrite, DN_ErrSink *err)
{
bool result = false;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 src16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, src);
DN_Str16 dest16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, dest);
unsigned long flags = MOVEFILE_COPY_ALLOWED;
if (overwrite)
flags |= MOVEFILE_REPLACE_EXISTING;
result = MoveFileExW(src16.data, dest16.data, flags) != 0;
if (!result) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(err,
win_error.code,
"Failed to move file '%.*s' to '%.*s': (%u) %.*s",
DN_Str8PrintFmt(src),
DN_Str8PrintFmt(dest),
win_error.code,
DN_Str8PrintFmt(win_error.msg));
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsFile DN_Os_FileOpen(DN_Str8 path, DN_OsFileOpen open_mode, DN_OsFileAccess access, DN_ErrSink *err)
{
DN_OsFile result = DN_ZeroInit;
if (path.count == 0 || path.count <= 0)
return result;
if ((access & ~DN_OsFileAccess_All) || ((access & DN_OsFileAccess_All) == 0)) {
DN_AssertInvalidCodePath;
return result;
}
unsigned long create_flag = 0;
switch (open_mode) {
case DN_OsFileOpen_CreateAlways: create_flag = CREATE_ALWAYS; break;
case DN_OsFileOpen_OpenIfExist: create_flag = OPEN_EXISTING; break;
case DN_OsFileOpen_OpenAlways: create_flag = OPEN_ALWAYS; break;
default: DN_AssertInvalidCodePath; return result;
}
unsigned long access_mode = 0;
if (access & DN_OsFileAccess_AppendOnly) {
DN_AssertF((access & ~DN_OsFileAccess_AppendOnly) == 0,
"Append can only be applied exclusively to the file, other access modes not permitted");
access_mode = FILE_APPEND_DATA;
} else {
if (access & DN_OsFileAccess_Read)
access_mode |= GENERIC_READ;
if (access & DN_OsFileAccess_Write)
access_mode |= GENERIC_WRITE;
if (access & DN_OsFileAccess_Execute)
access_mode |= GENERIC_EXECUTE;
}
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
void *handle = CreateFileW(/*LPCWSTR lpFileName*/ path16.data,
/*DWORD dwDesiredAccess*/ access_mode,
/*DWORD dwShareMode*/ FILE_SHARE_READ | FILE_SHARE_WRITE,
/*LPSECURITY_ATTRIBUTES lpSecurityAttributes*/ NULL,
/*DWORD dwCreationDisposition*/ create_flag,
/*DWORD dwFlagsAndAttributes*/ FILE_ATTRIBUTE_NORMAL,
/*HANDLE hTemplateFile*/ NULL);
if (handle == INVALID_HANDLE_VALUE) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.error = true;
DN_ErrSinkAppendF(err, win_error.code, "Failed to open file at '%.*s': '%.*s'", DN_Str8PrintFmt(path), DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
return result;
}
result.handle = handle;
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsFileRead DN_Os_FileRead(DN_OsFile *file, void *buffer, DN_USize size, DN_ErrSink *err)
{
DN_OsFileRead result = DN_ZeroInit;
if (!file || !file->handle || file->error || !buffer)
return result;
if (size == 0) {
result.success = true;
return result;
}
if (size > ULONG_MAX) {
DN_Str8x32 desc = DN_Str8x32FromByteCountU64Auto(size);
DN_ErrSinkAppendF(err, 1 /*error_code*/, "Current implementation doesn't support reading >4GiB file (requested %.*s), implement Win32 overlapped IO", DN_Str8PrintFmt(desc));
return result;
}
unsigned long bytes_read = 0;
unsigned long read_result = ReadFile(/*HANDLE hFile*/ file->handle,
/*LPVOID lpBuffer*/ buffer,
/*DWORD nNumberOfBytesToRead*/ DN_Cast(unsigned long) size,
/*LPDWORD lpNumberOfByesRead*/ &bytes_read,
/*LPOVERLAPPED lpOverlapped*/ NULL);
if (read_result == 0) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(err, win_error.code, "Failed to read data from file: (%u) %.*s", win_error.code, DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
return result;
}
if (bytes_read != size) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(
err,
win_error.code,
"Failed to read the desired number of bytes from file, we read %uB but we expected %uB: (%u) %.*s",
bytes_read,
DN_Cast(unsigned long) size,
win_error.code,
DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
return result;
}
result.bytes_read = bytes_read;
result.success = true;
return result;
}
DN_API bool DN_Os_FileWritePtr(DN_OsFile *file, void const *buffer, DN_USize size, DN_ErrSink *err)
{
if (!file || !file->handle || file->error || !buffer || size <= 0)
return false;
bool result = true;
char const *end = DN_Cast(char *) buffer + size;
for (char const *ptr = DN_Cast(char const *) buffer; result && ptr != end;) {
unsigned long write_size = DN_Cast(unsigned long) DN_Min((unsigned long)-1, end - ptr);
unsigned long bytes_written = 0;
result = WriteFile(file->handle, ptr, write_size, &bytes_written, NULL /*lpOverlapped*/) != 0;
ptr += bytes_written;
}
if (!result) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_Str8x32 buffer_size_str8 = DN_Str8x32FromByteCountU64Auto(size);
DN_ErrSinkAppendF(err, win_error.code, "Failed to write buffer (%.*s) to file handle: %.*s", DN_Str8PrintFmt(buffer_size_str8), DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
}
return result;
}
DN_API bool DN_Os_FileFlush(DN_OsFile *file, DN_ErrSink *err)
{
if (!file || !file->handle || file->error)
return false;
BOOL result = FlushFileBuffers(DN_Cast(HANDLE) file->handle);
if (!result) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(err, win_error.code, "Failed to flush file buffer to disk: %.*s", DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
}
return DN_Cast(bool) result;
}
DN_API void DN_Os_FileClose(DN_OsFile *file)
{
if (!file || !file->handle || file->error)
return;
CloseHandle(file->handle);
*file = DN_Literal(DN_OsFile)DN_ZeroInit;
}
DN_API DN_OsPathInfo DN_Os_PathInfo(DN_Str8 path)
{
DN_OsPathInfo result = DN_ZeroInit;
if (path.count == 0)
return result;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
WIN32_FILE_ATTRIBUTE_DATA attrib_data = DN_ZeroInit;
if (!GetFileAttributesExW(path16.data, GetFileExInfoStandard, &attrib_data)) {
DN_TcScratchEnd(&scratch);
return result;
}
result.exists = true;
result.create_time_in_s = DN_Os_W32FileTimeToSeconds_(&attrib_data.ftCreationTime);
result.last_access_time_in_s = DN_Os_W32FileTimeToSeconds_(&attrib_data.ftLastAccessTime);
result.last_write_time_in_s = DN_Os_W32FileTimeToSeconds_(&attrib_data.ftLastWriteTime);
LARGE_INTEGER large_int = DN_ZeroInit;
large_int.u.HighPart = DN_Cast(int32_t) attrib_data.nFileSizeHigh;
large_int.u.LowPart = attrib_data.nFileSizeLow;
result.size = (DN_U64)large_int.QuadPart;
if (attrib_data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) {
if (attrib_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
result.type = DN_OsPathInfoType_Directory;
else
result.type = DN_OsPathInfoType_File;
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_PathDelete(DN_Str8 path)
{
bool result = false;
if (path.count == 0)
return result;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
if (path16.count) {
result = DeleteFileW(path16.data);
if (!result)
result = RemoveDirectoryW(path16.data);
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsPathResult DN_Os_PathCanonicalise(DN_Arena *arena, DN_Str8 path, DN_ErrSink *error)
{
DN_OsPathResult result = DN_ZeroInit;
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
wchar_t out_path[1024];
HRESULT convert_result = PathCchCanonicalizeEx(out_path, DN_ArrayCountU(out_path), path16.data, PATHCCH_ALLOW_LONG_PATHS);
if (convert_result == S_OK) {
result.success = true;
result.path = DN_Os_W32Str8FromStr16Arena(arena, DN_Str16FromPtr(out_path, DN_CStr16Count(out_path)));
} else {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
DN_ErrSinkAppendF(error, win_error.code, "Failed to canonicalise path. %.*s", DN_Str8PrintFmt(win_error.msg));
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_PathIsFile(DN_Str8 path)
{
bool result = false;
if (path.count == 0)
return result;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
if (path16.count) {
WIN32_FILE_ATTRIBUTE_DATA attrib_data = DN_ZeroInit;
if (GetFileAttributesExW(path16.data, GetFileExInfoStandard, &attrib_data))
result = (attrib_data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) &&
!(attrib_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_PathIsDir(DN_Str8 path)
{
bool result = false;
if (path.count == 0)
return result;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
if (path16.count) {
WIN32_FILE_ATTRIBUTE_DATA attrib_data = DN_ZeroInit;
if (GetFileAttributesExW(path16.data, GetFileExInfoStandard, &attrib_data))
result = (attrib_data.dwFileAttributes != INVALID_FILE_ATTRIBUTES) &&
(attrib_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_PathMakeDir(DN_Str8 path)
{
bool result = true;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, path);
// NOTE: Go back from the end of the string to all the directories in the
// string, and try to create them. Since Win32 API cannot create
// intermediate directories that don't exist in a path we need to go back
// and record all the directories until we encounter one that exists.
//
// From that point onwards go forwards and make all the directories
// inbetween by null-terminating the string temporarily, creating the
// directory and so forth until we reach the end.
//
// If we find a file at some point in the path we fail out because the
// series of directories can not be made if a file exists with the same
// name.
for (DN_USize index = 0; index < path16.count; index++) {
bool first_char = index == (path16.count - 1);
wchar_t ch = path16.data[index];
if (ch == '/' || ch == '\\' || first_char) {
wchar_t temp = path16.data[index];
if (!first_char)
path16.data[index] = 0; // Temporarily null terminate it
WIN32_FILE_ATTRIBUTE_DATA attrib_data = DN_ZeroInit;
bool successful = GetFileAttributesExW(path16.data, GetFileExInfoStandard, &attrib_data); // Check
if (successful) {
if (attrib_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
// NOTE: The directory exists, continue iterating the path
} else {
// NOTE: There's some kind of file that exists at the path
// but it's not a directory. This request to make a
// directory is invalid.
DN_TcScratchEnd(&scratch);
return false;
}
} else {
// NOTE: There's nothing that exists at this path, we can create
// a directory here
result |= (CreateDirectoryW(path16.data, NULL) == 0);
}
if (!first_char)
path16.data[index] = temp; // Undo null termination
}
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_PathIterateDir(DN_Str8 path, DN_OsDirIterator *it)
{
if (path.count == 0 || !it || path.count <= 0)
return false;
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_OsW32FolderIteratorW wide_it = DN_ZeroInit;
DN_Str16 path16 = DN_ZeroInit;
if (it->handle) {
wide_it.handle = it->handle;
} else {
bool needs_asterisks = DN_Str8EndsWithSensitive(path, DN_Str8Lit("\\")) ||
DN_Str8EndsWithSensitive(path, DN_Str8Lit("/"));
bool has_glob = DN_Str8EndsWithSensitive(path, DN_Str8Lit("\\*")) ||
DN_Str8EndsWithSensitive(path, DN_Str8Lit("/*"));
DN_Str8 adjusted_path = path;
if (!has_glob) {
// NOTE: We are missing the glob for enumerating the files, we will
// add those characters in this branch, so overwrite the null
// character, add the glob and re-null terminate the buffer.
if (needs_asterisks)
adjusted_path = DN_Str8PathFmtOsArena(&scratch.arena, "%.*s*", DN_Str8PrintFmt(path)).value;
else
adjusted_path = DN_Str8PathFmtOsArena(&scratch.arena, "%.*s/*", DN_Str8PrintFmt(path)).value;
}
path16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, adjusted_path);
if (path16.count <= 0) { // Conversion error
DN_TcScratchEnd(&scratch);
return false;
}
}
bool result = DN_Os_W32DirWIterate(path16, &wide_it);
it->handle = wide_it.handle;
if (result) {
int size = DN_Os_W32Str8FromStr16Buffer(wide_it.file_name, it->buffer, DN_ArrayCountU(it->buffer));
it->file_name = DN_Str8FromPtr(it->buffer, size);
}
DN_TcScratchEnd(&scratch);
return result;
}
DN_API void DN_Os_Exit(int32_t exit_code)
{
ExitProcess(DN_Cast(UINT) exit_code);
}
DN_API DN_OsExecResult DN_Os_ExecPump(DN_OsExecAsyncHandle handle,
char *stdout_buffer,
DN_USize *stdout_size,
char *stderr_buffer,
DN_USize *stderr_size,
DN_U32 timeout_ms,
DN_ErrSink *err)
{
DN_OsExecResult result = DN_ZeroInit;
size_t stdout_buffer_size = 0;
size_t stderr_buffer_size = 0;
if (stdout_size) {
stdout_buffer_size = *stdout_size;
*stdout_size = 0;
}
if (stderr_size) {
stderr_buffer_size = *stderr_size;
*stderr_size = 0;
}
if (!handle.process || handle.os_error_code || handle.exit_code) {
if (handle.os_error_code)
result.os_error_code = handle.os_error_code;
else
result.exit_code = handle.exit_code;
DN_Assert(!handle.stdout_read);
DN_Assert(!handle.stdout_write);
DN_Assert(!handle.stderr_read);
DN_Assert(!handle.stderr_write);
DN_Assert(!handle.process);
return result;
}
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DWORD stdout_bytes_available = 0;
DWORD stderr_bytes_available = 0;
PeekNamedPipe(handle.stdout_read, NULL, 0, NULL, &stdout_bytes_available, NULL);
PeekNamedPipe(handle.stderr_read, NULL, 0, NULL, &stderr_bytes_available, NULL);
DWORD exec_result = WAIT_TIMEOUT;
if (stdout_bytes_available == 0 && stderr_bytes_available == 0)
exec_result = WaitForSingleObject(handle.process, timeout_ms);
if (exec_result == WAIT_FAILED) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(err, result.os_error_code, "Executed command failed to terminate: %.*s", DN_Str8PrintFmt(win_error.msg));
DN_TcScratchEnd(&scratch);
return result;
}
if (exec_result == WAIT_TIMEOUT || exec_result == WAIT_OBJECT_0) {
// NOTE: Read stdout from process
// If the pipes are full, the process will block. We periodically
// flush the pipes to make sure this doesn't happen
char sink[DN_Kilobytes(8)];
stdout_bytes_available = 0;
if (PeekNamedPipe(handle.stdout_read, NULL, 0, NULL, &stdout_bytes_available, NULL)) {
if (stdout_bytes_available) {
DWORD bytes_read = 0;
char *dest_buffer = handle.stdout_write && stdout_buffer ? stdout_buffer : sink;
DN_USize dest_size = handle.stdout_write && stdout_buffer ? stdout_buffer_size : DN_ArrayCountU(sink);
BOOL success = ReadFile(handle.stdout_read, dest_buffer, DN_Cast(DWORD) dest_size, &bytes_read, NULL);
if (success) {
if (stdout_size)
*stdout_size = bytes_read;
} else {
DN_ErrSinkAppendF(err, 1, "Failed to read bytes from stdout");
}
}
}
// NOTE: Read stderr from process
stderr_bytes_available = 0;
if (PeekNamedPipe(handle.stderr_read, NULL, 0, NULL, &stderr_bytes_available, NULL)) {
if (stderr_bytes_available) {
char *dest_buffer = handle.stderr_write && stderr_buffer ? stderr_buffer : sink;
size_t dest_size = handle.stderr_write && stderr_buffer ? stderr_buffer_size : DN_ArrayCountU(sink);
DWORD bytes_read = 0;
BOOL success = ReadFile(handle.stderr_read, dest_buffer, DN_Cast(DWORD) dest_size, &bytes_read, NULL);
if (success) {
if (stderr_size)
*stderr_size = bytes_read;
} else {
DN_ErrSinkAppendF(err, 1, "Failed to read bytes from stderr");
}
}
}
}
result.finished = exec_result == WAIT_OBJECT_0 || exec_result == WAIT_FAILED;
if (exec_result == WAIT_OBJECT_0) {
DWORD exit_status;
if (GetExitCodeProcess(handle.process, &exit_status)) {
result.exit_code = exit_status;
} else {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(err,
result.os_error_code,
"Failed to retrieve command exit code: %.*s",
DN_Str8PrintFmt(win_error.msg));
}
// NOTE: Cleanup
if (handle.stdout_write)
CloseHandle(handle.stdout_write);
if (handle.stderr_write)
CloseHandle(handle.stderr_write);
if (handle.stdout_read)
CloseHandle(handle.stdout_read);
if (handle.stderr_read)
CloseHandle(handle.stderr_read);
if (handle.process)
CloseHandle(handle.process);
}
result.stdout_text = DN_Str8FromPtr(stdout_buffer, stdout_size ? *stdout_size : 0);
result.stderr_text = DN_Str8FromPtr(stderr_buffer, stderr_size ? *stderr_size : 0);
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsExecResult DN_Os_ExecWait(DN_OsExecAsyncHandle handle, DN_Arena *arena, DN_ErrSink *err)
{
DN_OsExecResult result = DN_ZeroInit;
if (!handle.process || handle.os_error_code || handle.exit_code) {
result.finished = true;
if (handle.os_error_code)
result.os_error_code = handle.os_error_code;
else
result.exit_code = handle.exit_code;
DN_Assert(!handle.stdout_read);
DN_Assert(!handle.stdout_write);
DN_Assert(!handle.stderr_read);
DN_Assert(!handle.stderr_write);
DN_Assert(!handle.process);
return result;
}
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str8Builder stdout_builder = DN_ZeroInit;
DN_Str8Builder stderr_builder = DN_ZeroInit;
if (arena) {
stdout_builder = DN_Str8BuilderFromArena(&scratch.arena);
stderr_builder = DN_Str8BuilderFromArena(&scratch.arena);
}
DN_U32 const SLOW_WAIT_TIME_MS = 100;
DN_U32 const FAST_WAIT_TIME_MS = 20;
DN_U32 wait_ms = FAST_WAIT_TIME_MS;
while (!result.finished) {
size_t stdout_size = DN_Kilobytes(8);
size_t stderr_size = DN_Kilobytes(8);
char *stdout_buffer = DN_ArenaNewArray(&scratch.arena, char, stdout_size, DN_ZMem_No);
char *stderr_buffer = DN_ArenaNewArray(&scratch.arena, char, stderr_size, DN_ZMem_No);
result = DN_Os_ExecPump(handle, stdout_buffer, &stdout_size, stderr_buffer, &stderr_size, wait_ms, err);
DN_Str8BuilderAppendCopy(&stdout_builder, result.stdout_text);
DN_Str8BuilderAppendCopy(&stderr_builder, result.stderr_text);
wait_ms = (result.stdout_text.count || result.stderr_text.count) ? FAST_WAIT_TIME_MS : SLOW_WAIT_TIME_MS;
}
// NOTE: Get stdout/stderr. If no arena is passed this is a no-op
result.stdout_text = DN_Str8FromStr8BuilderArena(&stdout_builder, arena);
result.stderr_text = DN_Str8FromStr8BuilderArena(&stderr_builder, arena);
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_OsExecAsyncHandle DN_Os_ExecAsync(DN_Str8Slice cmd_line, DN_OsExecArgs args, DN_ErrSink *err)
{
// NOTE: Pre-amble
DN_OsExecAsyncHandle result = DN_ZeroInit;
if (cmd_line.count == 0)
return result;
// NOTE: Render the command line into single string to pass into the Win32 API. We'll quote the
// string on behalf of the user if there's whitespace in the string
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str8 cmd = DN_ZeroInit;
{
DN_USize count_req = 0;
DN_Str8 cmd_separator = DN_Str8Lit(" ");
for (DN_ForIt(it, DN_Str8, &cmd_line)) {
if (it.index)
count_req += cmd_separator.count;
if (!DN_Str8StartsWithSensitive(*it.data, DN_Str8Lit("\""))) {
if (DN_Str8Find(*it.data, DN_Str8FindFlag_Whitespace).found)
count_req += 2; // If there's whitespace, we'll quote the string for the user
}
count_req += it.data->count;
}
// NOTE: Build the string
cmd = DN_Str8AllocArena(count_req, DN_ZMem_No, &scratch.arena);
if (cmd.data) {
DN_USize write_index = 0;
for (DN_ForIt(it, DN_Str8, &cmd_line)) {
if (it.index) {
DN_Memcpy(cmd.data + write_index, cmd_separator.data, cmd_separator.count);
write_index += cmd_separator.count;
}
// NOTE: Quote the string if needed
DN_Str8 str8 = *it.data;
bool needs_quotes = false;
if (!DN_Str8StartsWithSensitive(*it.data, DN_Str8Lit("\"")))
needs_quotes = DN_Str8Find(str8, DN_Str8FindFlag_Whitespace).found;
if (needs_quotes)
cmd.data[write_index++] = '\"';
// NOTE: Write contents
DN_Memcpy(cmd.data + write_index, str8.data, str8.count);
write_index += str8.count;
// NOTE: Close quote if needed
if (needs_quotes)
cmd.data[write_index++] = '\"';
}
DN_Assert(write_index == cmd.count);
}
}
DN_AssertF(cmd.count < DN_Kilobytes(32), "Command exceeds the allowable size in Win32");
DN_Str16 cmd16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, cmd);
DN_Str16 working_dir16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, args.working_dir);
DN_Str8Builder env_builder = DN_Str8BuilderFromArena(&scratch.arena);
DN_Str8BuilderAppendArrayRef(&env_builder, args.environment.data, args.environment.count);
if (env_builder.string_size)
DN_Str8BuilderAppendRef(&env_builder, DN_Str8Lit("\0"));
DN_Str8 env_block8 = DN_Str8FromStr8BuilderDelimitArena(&env_builder, DN_Str8Lit("\0"), &scratch.arena);
DN_Str16 env_block16 = DN_ZeroInit;
if (env_block8.count)
env_block16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, env_block8);
// NOTE: Stdout/err security attributes
SECURITY_ATTRIBUTES save_std_security_attribs = DN_ZeroInit;
save_std_security_attribs.nLength = sizeof(save_std_security_attribs);
save_std_security_attribs.bInheritHandle = true;
// NOTE: Redirect stdout
HANDLE stdout_read = DN_ZeroInit;
HANDLE stdout_write = DN_ZeroInit;
if (DN_BitIsSet(args.flags, DN_OsExecFlags_SaveStdout)) {
if (!CreatePipe(&stdout_read, &stdout_write, &save_std_security_attribs, /*nSize*/ 0)) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(
err,
result.os_error_code,
"Failed to create stdout pipe to redirect the output of the command '%.*s': %.*s",
DN_Str8PrintFmt(cmd),
DN_Str8PrintFmt(win_error.msg));
if (result.os_error_code || result.exit_code) {
CloseHandle(stdout_read);
CloseHandle(stdout_write);
}
DN_TcScratchEnd(&scratch);
return result;
}
if (!SetHandleInformation(stdout_read, HANDLE_FLAG_INHERIT, 0)) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(err,
result.os_error_code,
"Failed to make stdout 'read' pipe non-inheritable when trying to "
"execute command '%.*s': %.*s",
DN_Str8PrintFmt(cmd),
DN_Str8PrintFmt(win_error.msg));
if (result.os_error_code || result.exit_code) {
CloseHandle(stdout_read);
CloseHandle(stdout_write);
}
DN_TcScratchEnd(&scratch);
return result;
}
}
// NOTE: Redirect stderr
HANDLE stderr_read = DN_ZeroInit;
HANDLE stderr_write = DN_ZeroInit;
if (DN_BitIsSet(args.flags, DN_OsExecFlags_SaveStderr)) {
if (DN_BitIsSet(args.flags, DN_OsExecFlags_MergeStderrToStdout)) {
stderr_read = stdout_read;
stderr_write = stdout_write;
} else {
if (!CreatePipe(&stderr_read, &stderr_write, &save_std_security_attribs, /*nSize*/ 0)) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(
err,
result.os_error_code,
"Failed to create stderr pipe to redirect the output of the command '%.*s': %.*s",
DN_Str8PrintFmt(cmd),
DN_Str8PrintFmt(win_error.msg));
if (result.os_error_code || result.exit_code) {
CloseHandle(stdout_read);
CloseHandle(stdout_write);
CloseHandle(stderr_read);
CloseHandle(stderr_write);
}
DN_TcScratchEnd(&scratch);
return result;
}
if (!SetHandleInformation(stderr_read, HANDLE_FLAG_INHERIT, 0)) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(err,
result.os_error_code,
"Failed to make stderr 'read' pipe non-inheritable when trying to "
"execute command '%.*s': %.*s",
DN_Str8PrintFmt(cmd),
DN_Str8PrintFmt(win_error.msg));
if (result.os_error_code || result.exit_code) {
CloseHandle(stdout_read);
CloseHandle(stdout_write);
CloseHandle(stderr_read);
CloseHandle(stderr_write);
}
DN_TcScratchEnd(&scratch);
return result;
}
}
}
// NOTE: Create a null stdin pipe so child gets EOF on read
// TODO: Eventually we should let the caller optionally write to stdin
HANDLE stdin_read = DN_ZeroInit;
if (DN_BitIsSet(args.flags, DN_OsExecFlags_SaveStdout) || DN_BitIsSet(args.flags, DN_OsExecFlags_SaveStderr)) {
HANDLE stdin_write = DN_ZeroInit;
if (CreatePipe(&stdin_read, &stdin_write, &save_std_security_attribs, 0))
CloseHandle(stdin_write);
}
// NOTE: Execute command
PROCESS_INFORMATION proc_info = DN_ZeroInit;
STARTUPINFOW startup_info = DN_ZeroInit;
startup_info.cb = sizeof(STARTUPINFOW);
startup_info.hStdError = stderr_write ? stderr_write : GetStdHandle(STD_ERROR_HANDLE);
startup_info.hStdOutput = stdout_write ? stdout_write : GetStdHandle(STD_OUTPUT_HANDLE);
startup_info.hStdInput = stdin_read ? stdin_read : GetStdHandle(STD_INPUT_HANDLE);
startup_info.dwFlags |= STARTF_USESTDHANDLES;
BOOL create_result = CreateProcessW(NULL,
cmd16.data,
NULL,
NULL,
true,
CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT,
env_block16.data,
working_dir16.data,
&startup_info,
&proc_info);
if (stdin_read)
CloseHandle(stdin_read);
if (!create_result) {
DN_OsW32Error win_error = DN_Os_W32ErrorFromLastErrorArena(&scratch.arena);
result.os_error_code = win_error.code;
DN_ErrSinkAppendF(err, result.os_error_code, "Failed to execute command '%.*s': %.*s", DN_Str8PrintFmt(cmd), DN_Str8PrintFmt(win_error.msg));
if (result.os_error_code || result.exit_code) {
if (stdout_read) CloseHandle(stdout_read);
if (stdout_write) CloseHandle(stdout_write);
// NOTE: When stderr is merged into stdout these handles alias the stdout handles and must
// not be closed a second time.
if (DN_BitIsNotSet(args.flags, DN_OsExecFlags_MergeStderrToStdout)) {
if (stderr_read) CloseHandle(stderr_read);
if (stderr_write) CloseHandle(stderr_write);
}
}
DN_TcScratchEnd(&scratch);
return result;
}
// NOTE: Post-amble
CloseHandle(proc_info.hThread);
result.process = proc_info.hProcess;
result.stdout_read = stdout_read;
result.stdout_write = stdout_write;
if (DN_BitIsSet(args.flags, DN_OsExecFlags_SaveStderr) && DN_BitIsNotSet(args.flags, DN_OsExecFlags_MergeStderrToStdout)) {
result.stderr_read = stderr_read;
result.stderr_write = stderr_write;
}
result.exec_flags = args.flags;
DN_TcScratchEnd(&scratch);
return result;
}
static DN_OsW32SyncPrimitive *DN_Os_U64ToW32SyncPrimitive_(DN_U64 u64)
{
DN_OsW32SyncPrimitive *result = NULL;
DN_Memcpy(&result, &u64, sizeof(u64));
return result;
}
static DN_U64 DN_Os_W32SyncPrimitiveToU64(DN_OsW32SyncPrimitive *primitive)
{
DN_U64 result = 0;
DN_StaticAssert(sizeof(result) == sizeof(primitive)); // Pointer size mis-match
DN_Memcpy(&result, &primitive, sizeof(result));
return result;
}
static DN_OsW32SyncPrimitive *DN_Os_W32AllocSyncPrimitive_()
{
DN_OsW32Core *w32 = DN_Os_W32GetCore();
DN_OsW32SyncPrimitive *result = NULL;
EnterCriticalSection(&w32->sync_primitive_free_list_mutex);
{
if (w32->sync_primitive_free_list) {
result = w32->sync_primitive_free_list;
w32->sync_primitive_free_list = w32->sync_primitive_free_list->next;
result->next = NULL;
} else {
DN_OsCore *os = &DN_Get()->os;
result = DN_ArenaNew(&os->arena, DN_OsW32SyncPrimitive, DN_ZMem_Yes);
}
}
LeaveCriticalSection(&w32->sync_primitive_free_list_mutex);
return result;
}
static void DN_Os_W32DeallocSyncPrimitive_(DN_OsW32SyncPrimitive *primitive)
{
if (primitive) {
DN_OsW32Core *w32 = DN_Os_W32GetCore();
EnterCriticalSection(&w32->sync_primitive_free_list_mutex);
primitive->next = w32->sync_primitive_free_list;
w32->sync_primitive_free_list = primitive;
LeaveCriticalSection(&w32->sync_primitive_free_list_mutex);
}
}
DN_API DN_OsSemaphore DN_Os_SemaphoreInit(DN_U32 initial_count)
{
DN_OsSemaphore result = DN_ZeroInit;
DN_OsW32SyncPrimitive *primitive = DN_Os_W32AllocSyncPrimitive_();
if (primitive) {
SECURITY_ATTRIBUTES security_attribs = DN_ZeroInit;
security_attribs.nLength = sizeof(security_attribs);
primitive->sem = CreateSemaphoreA(&security_attribs, initial_count, INT32_MAX, NULL /*name*/);
if (primitive->sem)
result.handle = DN_Os_W32SyncPrimitiveToU64(primitive);
if (!primitive->sem)
DN_Os_W32DeallocSyncPrimitive_(primitive);
}
return result;
}
DN_API void DN_Os_SemaphoreDeinit(DN_OsSemaphore *semaphore)
{
if (semaphore && semaphore->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(semaphore->handle);
CloseHandle(primitive->sem);
DN_Os_W32DeallocSyncPrimitive_(primitive);
*semaphore = DN_Literal(DN_OsSemaphore)DN_ZeroInit;
}
}
DN_API void DN_Os_SemaphoreIncrement(DN_OsSemaphore *semaphore, DN_U32 amount)
{
if (semaphore && semaphore->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(semaphore->handle);
LONG prev_count = 0;
ReleaseSemaphore(primitive->sem, amount, &prev_count);
}
}
DN_API DN_OsSemaphoreWaitResult DN_Os_SemaphoreWait(DN_OsSemaphore *semaphore, DN_U32 timeout_ms)
{
DN_OsSemaphoreWaitResult result = DN_ZeroInit;
if (semaphore && semaphore->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(semaphore->handle);
DWORD wait_result = WaitForSingleObject(primitive->sem, timeout_ms == DN_Os_SEMAPHORE_INFINITE_TIMEOUT ? INFINITE : timeout_ms);
if (wait_result == WAIT_TIMEOUT)
result = DN_OsSemaphoreWaitResult_Timeout;
else if (wait_result == WAIT_OBJECT_0)
result = DN_OsSemaphoreWaitResult_Success;
}
return result;
}
DN_API DN_OsBarrier DN_Os_BarrierInit(DN_U32 thread_count)
{
DN_OsBarrier result = DN_ZeroInit;
DN_OsW32SyncPrimitive *primitive = DN_Os_W32AllocSyncPrimitive_();
if (primitive) {
BOOL init_result = InitializeSynchronizationBarrier(&primitive->barrier, thread_count, /*lSpinCount=*/-1);
if (init_result) {
result.handle = DN_Os_W32SyncPrimitiveToU64(primitive);
} else {
DN_Os_W32DeallocSyncPrimitive_(primitive);
}
}
return result;
}
DN_API void DN_Os_BarrierDeinit(DN_OsBarrier *barrier)
{
if (barrier && barrier->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(barrier->handle);
bool result = DeleteSynchronizationBarrier(&primitive->barrier);
DN_Assert(result);
DN_Os_W32DeallocSyncPrimitive_(primitive);
}
}
DN_API void DN_Os_BarrierWait(DN_OsBarrier *barrier)
{
if (barrier && barrier->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(barrier->handle);
EnterSynchronizationBarrier(&primitive->barrier, /*dwFlags=*/ 0);
}
}
// NOTE: DN_OsMutex
DN_API DN_OsMutex DN_Os_MutexInit()
{
DN_OsW32SyncPrimitive *primitive = DN_Os_W32AllocSyncPrimitive_();
if (primitive)
InitializeCriticalSection(&primitive->mutex);
DN_OsMutex result = DN_ZeroInit;
result.handle = DN_Os_W32SyncPrimitiveToU64(primitive);
return result;
}
DN_API void DN_Os_MutexDeinit(DN_OsMutex *mutex)
{
if (mutex && mutex->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(mutex->handle);
DeleteCriticalSection(&primitive->mutex);
DN_Os_W32DeallocSyncPrimitive_(primitive);
*mutex = DN_Literal(DN_OsMutex)DN_ZeroInit;
}
}
DN_API void DN_Os_MutexLock(DN_OsMutex *mutex)
{
if (mutex && mutex->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(mutex->handle);
EnterCriticalSection(&primitive->mutex);
}
}
DN_API void DN_Os_MutexUnlock(DN_OsMutex *mutex)
{
if (mutex && mutex->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(mutex->handle);
LeaveCriticalSection(&primitive->mutex);
}
}
DN_API DN_OsConditionVariable DN_Os_ConditionVariableInit()
{
DN_OsW32SyncPrimitive *primitive = DN_Os_W32AllocSyncPrimitive_();
if (primitive)
InitializeConditionVariable(&primitive->cv);
DN_OsConditionVariable result = DN_ZeroInit;
result.handle = DN_Os_W32SyncPrimitiveToU64(primitive);
return result;
}
DN_API void DN_Os_ConditionVariableDeinit(DN_OsConditionVariable *cv)
{
if (cv && cv->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(cv->handle);
DN_Os_W32DeallocSyncPrimitive_(primitive);
*cv = DN_Literal(DN_OsConditionVariable)DN_ZeroInit;
}
}
DN_API bool DN_Os_ConditionVariableWaitUntil(DN_OsConditionVariable *cv, DN_OsMutex *mutex, DN_U64 end_ts_ms)
{
bool result = false;
DN_U64 now_ms = DN_Os_DateUnixTimeNs() / (1000 * 1000);
if (now_ms < end_ts_ms) {
DN_U64 sleep_ms = end_ts_ms - now_ms;
result = DN_Os_ConditionVariableWait(cv, mutex, sleep_ms);
}
return result;
}
DN_API bool DN_Os_ConditionVariableWait(DN_OsConditionVariable *cv, DN_OsMutex *mutex, DN_U64 sleep_ms)
{
bool result = false;
if (mutex && cv && mutex->handle != 0 && cv->handle != 0 && sleep_ms > 0) {
DN_OsW32SyncPrimitive *mutex_primitive = DN_Os_U64ToW32SyncPrimitive_(mutex->handle);
DN_OsW32SyncPrimitive *cv_primitive = DN_Os_U64ToW32SyncPrimitive_(cv->handle);
result = SleepConditionVariableCS(&cv_primitive->cv, &mutex_primitive->mutex, DN_Cast(DWORD) sleep_ms);
}
return result;
}
DN_API void DN_Os_ConditionVariableSignal(DN_OsConditionVariable *cv)
{
if (cv && cv->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(cv->handle);
WakeConditionVariable(&primitive->cv);
}
}
DN_API void DN_Os_ConditionVariableBroadcast(DN_OsConditionVariable *cv)
{
if (cv && cv->handle != 0) {
DN_OsW32SyncPrimitive *primitive = DN_Os_U64ToW32SyncPrimitive_(cv->handle);
WakeAllConditionVariable(&primitive->cv);
}
}
DN_API DN_OsWindowMinimise DN_Os_WindowIsMinimised(DN_OsWindow *window)
{
HWND hwnd = window ? DN_Cast(HWND) window->handle : NULL;
DN_OsWindowMinimise result = DN_OsWindowMinimise_No;
if (hwnd && IsIconic(hwnd) != 0)
result = DN_OsWindowMinimise_Yes;
return result;
}
DN_API DN_OsWindowMaximise DN_Os_WindowIsMaximised(DN_OsWindow *window)
{
HWND hwnd = window ? DN_Cast(HWND) window->handle : NULL;
DN_OsWindowMaximise result = DN_OsWindowMaximise_No;
if (hwnd && IsZoomed(hwnd) != 0)
result = DN_OsWindowMaximise_Yes;
return result;
}
DN_API void DN_Os_WindowSetTitle(DN_OsWindow *window, DN_Str8 title)
{
HWND hwnd = window ? DN_Cast(HWND) window->handle : NULL;
if (hwnd) {
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 title16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, title);
SetWindowTextW(hwnd, (WCHAR *)title16.data);
DN_TcScratchEnd(&scratch);
}
}
DN_API void DN_Os_WindowShow(DN_OsWindow *window, DN_OsWindowShow show)
{
switch (show) {
case DN_OsWindowShow_Nil: break;
case DN_OsWindowShow_Restore: ShowWindow(DN_Cast(HWND)window->handle, SW_RESTORE); break;
case DN_OsWindowShow_Minimise: ShowWindow(DN_Cast(HWND)window->handle, SW_MINIMIZE); break;
case DN_OsWindowShow_Maximise: ShowWindow(DN_Cast(HWND)window->handle, SW_MAXIMIZE); break;
case DN_OsWindowShow_Show: ShowWindow(DN_Cast(HWND)window->handle, SW_SHOW); break;
case DN_OsWindowShow_Hide: ShowWindow(DN_Cast(HWND)window->handle, SW_HIDE); break;
}
}
DN_API void DN_Os_WindowBringToFront(DN_OsWindow *window)
{
HWND hwnd = window ? DN_Cast(HWND)window->handle : NULL;
if (hwnd)
BringWindowToTop(hwnd);
}
DN_API void DN_Os_WindowFocus(DN_OsWindow *window)
{
HWND hwnd = window ? DN_Cast(HWND)window->handle : NULL;
if (hwnd) {
SetForegroundWindow(hwnd);
SetFocus(hwnd);
}
}
DN_API bool DN_Os_WindowIsFocused(DN_OsWindow *window)
{
bool result = false;
HWND hwnd = window ? DN_Cast(HWND) window->handle : NULL;
if (hwnd)
result = hwnd == GetForegroundWindow();
return result;
}
static DWORD __stdcall DN_Os_ThreadFunc_(void *user_context)
{
DN_Os_ThreadExecute_(user_context);
return 0;
}
DN_API bool DN_Os_ThreadInitLane(DN_OsThread *thread, DN_OsThreadFunc *func, DN_OsThreadLane *lane, DN_OsThreadInitArgs init_args, void *user_context)
{
bool result = false;
if (!thread)
return result;
DN_Os_ThreadPreInit_(thread, func, lane, init_args, user_context);
// TODO(doyle): Check if semaphore is valid
DWORD thread_id = 0;
SECURITY_ATTRIBUTES security_attribs = DN_ZeroInit;
security_attribs.nLength = sizeof(security_attribs);
thread->handle = CreateThread(&security_attribs,
init_args.stack_size,
DN_Os_ThreadFunc_,
thread,
0 /*creation_flags*/,
&thread_id);
result = thread->handle != NULL;
if (result) {
thread->thread_id = thread_id;
if (thread->flags & DN_OsThreadFlags_Detached) {
CloseHandle(thread->handle);
thread->handle = NULL;
}
}
DN_Os_ThreadPostInit_(thread, result);
return result;
}
DN_API bool DN_Os_ThreadJoin(DN_OsThread *thread, DN_U32 timeout_ms, DN_TcDeinitArenas deinit_arenas)
{
bool result = true;
if (thread && thread->handle && thread->handle != INVALID_HANDLE_VALUE) {
DN_AssertF(DN_BitIsNotSet(thread->flags, DN_OsThreadFlags_Detached),
"Detached threads should have their handle immediately closed and invalidated so this branch should never hit.");
DWORD wait_result = WaitForSingleObject(thread->handle, timeout_ms);
if (wait_result == WAIT_OBJECT_0) {
CloseHandle(thread->handle);
thread->handle = INVALID_HANDLE_VALUE;
thread->thread_id = DN_Literal(DN_U64)DN_ZeroInit;
DN_TcDeinit(&thread->context, deinit_arenas);
} else {
result = false;
}
}
return result;
}
DN_API DN_U32 DN_Os_ThreadID()
{
unsigned long result = GetCurrentThreadId();
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: DN Win32 book-keeping
DN_API void DN_Os_W32Init(DN_OsW32Core *w32)
{
InitializeCriticalSection(&w32->sync_primitive_free_list_mutex);
QueryPerformanceFrequency(&w32->qpc_frequency);
// NOTE: DPI
HMODULE user32 = LoadLibraryA("user32.dll");
if (user32) {
w32->get_dpi_for_window = (DN_OsW32GetDpiForWindowFunc* )GetProcAddress(user32, "GetDpiForWindow");
w32->get_dpi_for_monitor = (DN_OsW32GetDpiForMonitorFunc * )GetProcAddress(user32, "GetDpiForMonitor");
w32->get_system_metrics_for_dpi = (DN_OsW32GetSystemMetricsForDpiFunc *)GetProcAddress(user32, "GetSystemMetricsForDpi");
FreeLibrary(user32);
}
// NOTE: SetThreadDesc
HMODULE kernel32 = LoadLibraryA("kernel32.dll");
if (kernel32) {
w32->set_thread_description = DN_Cast(DN_OsW32SetThreadDescriptionFunc *) GetProcAddress(kernel32, "SetThreadDescription");
FreeLibrary(kernel32);
}
// NOTE: win32 bcrypt
wchar_t const BCRYPT_ALGORITHM[] = L"RNG";
long /*NTSTATUS*/ init_status = BCryptOpenAlgorithmProvider(&w32->bcrypt_rng_handle, BCRYPT_ALGORITHM, NULL /*implementation*/, 0 /*flags*/);
if (w32->bcrypt_rng_handle && init_status == 0)
w32->bcrypt_init_success = true;
else
DN_LogErrorF("Failed to initialise Windows secure random number generator, error: %d", init_status);
}
DN_API DN_OsW32Core *DN_Os_W32GetCore()
{
DN_Core *dn = DN_Get();
DN_Assert(dn && dn->os_init);
DN_OsW32Core *result = DN_Cast(DN_OsW32Core *)dn->os.platform_context;
return result;
}
DN_API DN_OsW32Window* DN_Os_W32WindowFromHwndMaybeAlloc(DN_OsW32Core *w32, HWND hwnd, DN_Arena *arena)
{
DN_OsW32Window *result = NULL;
for (DN_OsW32Window *check = w32->windows; !result && check; check = check->next) {
if (check->hwnd == hwnd)
result = check;
}
if (!result && arena) {
result = DN_ArenaNewZ(arena, DN_OsW32Window);
if (result) {
result->hwnd = hwnd;
if (w32->windows)
w32->windows->next = result;
result->next = w32->windows;
w32->windows = result;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Process management
DN_API void DN_Os_W32ThreadSetName(DN_Str8 name)
{
// NOTE: SetThreadDescription is only available in
// Windows Server 2016, Windows 10 LTSB 2016 and Windows 10 version 1607
//
// See: https://learn.microsoft.com/en-us/windows/w32/api/processthreadsapi/nf-processthreadsapi-setthreaddescription
DN_OsW32Core *w32 = DN_Os_W32GetCore();
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
if (w32->set_thread_description) {
DN_Str16 name16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, name);
w32->set_thread_description(GetCurrentThread(), (WCHAR *)name16.data);
} else {
// NOTE: Fallback to throw-exception method to set thread name
#pragma pack(push, 8)
struct DN_OsW32ThreadNameInfo
{
DN_U32 dwType;
char *szName;
DN_U32 dwThreadID;
DN_U32 dwFlags;
};
#pragma pack(pop)
DN_Str8 copy = DN_Str8FromStr8Arena(name, &scratch.arena);
struct DN_OsW32ThreadNameInfo info = DN_ZeroInit;
info.dwType = 0x1000;
info.szName = (char *)copy.data;
info.dwThreadID = DN_Os_ThreadID();
// TODO: Review warning 6320
DN_MSVC_WARNING_PUSH
DN_MSVC_WARNING_DISABLE(6320) // Exception-filter expression is the constant EXCEPTION_ExeCUTE_HANDLER. This might mask exceptions that were not intended to be handled
DN_MSVC_WARNING_DISABLE(6322) // Empty _except block
#if defined(DN_COMPILER_MSVC) || defined(DN_COMPILER_CLANG_CL)
__try {
RaiseException(0x406D1388, 0, sizeof(info) / sizeof(void *), (const ULONG_PTR *)&info);
} __except (EXCEPTION_EXECUTE_HANDLER) {
}
#else
RaiseException(0x406D1388, 0, sizeof(info) / sizeof(void *), (const ULONG_PTR *)&info);
#endif
DN_MSVC_WARNING_POP
}
DN_TcScratchEnd(&scratch);
}
static NOTIFYICONDATAW DN_Os_W32TrayIconData_(DN_OsW32TrayIcon *tray)
{
NOTIFYICONDATAW result = {};
result.cbSize = sizeof(result);
result.hWnd = tray->hwnd;
result.uID = tray->id;
result.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;
result.uCallbackMessage = tray->callback_message_id;
result.hIcon = (HICON)SendMessageW(tray->hwnd, WM_GETICON, ICON_SMALL, 0);
if (!result.hIcon)
result.hIcon = LoadIconW(NULL, (LPCWSTR)IDI_APPLICATION);
DN_Memcpy(result.szTip, tray->tooltip, sizeof(tray->tooltip));
return result;
}
static bool DN_Os_W32TrayIconAdd_(DN_OsW32TrayIcon *tray)
{
bool result = false;
if (tray && tray->hwnd) {
NOTIFYICONDATAW data = DN_Os_W32TrayIconData_(tray);
result = Shell_NotifyIconW(NIM_ADD, &data) != 0;
}
return result;
}
DN_API bool DN_Os_W32TrayIconInit(DN_OsWindow *window, DN_U32 icon_id, DN_U32 callback_message, DN_Str8 tooltip, DN_OsTrayIconCallback *callback, void *user_data)
{
DN_OsW32Core *w32 = DN_Os_W32GetCore();
if (!w32 || !window || !window->handle || icon_id == 0 || callback_message == 0)
return false;
DN_OsW32TrayIcon *tray = &w32->tray_icon;
if (tray->init)
DN_Os_W32TrayIconDeinit();
tray->hwnd = DN_Cast(HWND) window->handle;
tray->id = icon_id;
tray->callback_message_id = callback_message;
tray->taskbar_created_message_id = RegisterWindowMessageW(L"TaskbarCreated");
tray->callback = callback;
tray->user_data = user_data;
{
DN_TcScratch scratch = DN_TcScratchBeginArena(NULL, 0);
DN_Str16 tooltip16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, tooltip);
DN_USize tooltip_count = DN_Min(tooltip16.count, DN_ArrayCountU(tray->tooltip) - 1);
tray->tooltip[0] = 0;
if (tooltip_count) {
DN_Memcpy(tray->tooltip, tooltip16.data, tooltip_count * sizeof(WCHAR));
tray->tooltip[tooltip_count] = 0;
}
DN_TcScratchEnd(&scratch);
}
bool result = DN_Os_W32TrayIconAdd_(tray);
tray->init = result;
if (!tray->init)
*tray = DN_Literal(DN_OsW32TrayIcon)DN_ZeroInit;
return result;
}
DN_API void DN_Os_W32TrayIconDeinit()
{
DN_OsW32Core *w32 = DN_Os_W32GetCore();
if (w32) {
DN_OsW32TrayIcon *tray = &w32->tray_icon;
if (tray->init) {
NOTIFYICONDATAW data = DN_Os_W32TrayIconData_(tray);
Shell_NotifyIconW(NIM_DELETE, &data);
}
*tray = {};
}
}
DN_API LRESULT __stdcall DN_Os_W32WindowProcCustomTitlebarAndTrayIcon(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param)
{
DN_OsW32Core *w32 = DN_Os_W32GetCore();
DN_AssertF(w32, "Using this window proc requires that DN's OS layer has been initialised");
if (w32->tray_icon.init) {
DN_OsW32TrayIcon *tray = &w32->tray_icon;
if (tray->taskbar_created_message_id && msg == tray->taskbar_created_message_id) {
DN_Os_W32TrayIconAdd_(&w32->tray_icon);
return 0;
}
if (msg == tray->callback_message_id) {
if (w32->tray_icon.callback) {
UINT event = DN_Cast(UINT) l_param;
switch (event) {
case WM_LBUTTONUP: tray->callback(DN_OsTrayIconEvent_LeftClick, tray->user_data); break;
case WM_LBUTTONDBLCLK: tray->callback(DN_OsTrayIconEvent_DoubleClick, tray->user_data); break;
case WM_RBUTTONUP: tray->callback(DN_OsTrayIconEvent_RightClick, tray->user_data); break;
default: break;
}
}
return 0;
}
}
LRESULT result = 0;
bool handled = true;
switch (msg) {
// NOTE: Sent when the size and position of a window's client area must be calculated. By
// processing this message, an application can control the content of the window's client area
// when the size or position of the window changes.
case WM_NCCALCSIZE: {
DN_OsW32Window *w32_window = DN_Os_W32WindowFromHwndMaybeAlloc(w32, hwnd, NULL);
if (w32_window && w32_window->custom_title_bar) {
// NOTE: Code adapted from raddebugger
// https://github.com/EpicGames/raddebugger/blob/7a5a649b89f6a06abdbaee61540468fca9db58f9/src/win32/window_manager/win32_window_manager.c#L668
//
// The goal here is to subtract away the title bar from the window and restore the pixel
// border that native Windows renders windows with. Note that on Windows 11 a non-maximised
// window has rounded corners which eats into the available client space that is normally
// otherwise eaten into from the native titlebar.
DWORD window_style = GetWindowLongW(hwnd, GWL_STYLE);
bool is_fullscreen = !(window_style & WS_OVERLAPPEDWINDOW);
if (is_fullscreen) {
handled = false;
} else {
DN_UInt dpi = w32->get_dpi_for_window ? w32->get_dpi_for_window(hwnd) : 96;
int frame_x = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CXFRAME, dpi) : GetSystemMetrics(SM_CXFRAME);
int frame_y = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CYFRAME, dpi) : GetSystemMetrics(SM_CYFRAME);
int padding = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CXPADDEDBORDER, dpi) : GetSystemMetrics(SM_CXPADDEDBORDER);
RECT *rect = w_param == 0 ? DN_Cast(RECT *)l_param : (DN_Cast(NCCALCSIZE_PARAMS *)l_param)->rgrc;
rect->right -= frame_x + padding;
rect->left += frame_x + padding;
rect->bottom -= frame_y + padding;
bool is_maximised = IsZoomed(hwnd) != 0;
if (is_maximised) {
rect->top += frame_y + padding;
// If we do not do this hidden taskbar can not be unhidden on mouse hover
// Unfortunately it can create an ugly bottom border when maximized...
rect->bottom -= 1;
} else {
int edge_height = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CYEDGE, dpi) : GetSystemMetrics(SM_CYEDGE);
rect->top += edge_height;
}
}
} else {
handled = false;
}
} break;
// NOTE: Sent to a window in order to determine what part of the window corresponds to a
// particular screen coordinate. This can happen, for example, when the cursor moves, when a
// mouse button is pressed or released, or in response to a call to a function such as
// WindowFromPoint. If the mouse is not captured, the message is sent to the window beneath
// the cursor. Otherwise, the message is sent to the window that has captured the mouse.
case WM_NCHITTEST: {
DN_OsW32Window *w32_window = DN_Os_W32WindowFromHwndMaybeAlloc(w32, hwnd, NULL);
if (w32_window && w32_window->custom_title_bar) {
// NOTE: Code adapted from raddebugger
// https://github.com/EpicGames/raddebugger/blob/7a5a649b89f6a06abdbaee61540468fca9db58f9/src/win32/window_manager/win32_window_manager.c#L668
//
// Since we removed the titlebar from the window, the resize handlers/grabbers at the top of
// the window are no longer functional. We have to reimplement it ourselves.
DWORD window_style = GetWindowLongW(hwnd, GWL_STYLE);
bool is_fullscreen = !(window_style & WS_OVERLAPPEDWINDOW);
handled = false;
if (!is_fullscreen) {
// Let the default procedure handle resizing areas
if (w32->fallback_wnd_proc)
result = CallWindowProcW(w32->fallback_wnd_proc, hwnd, msg, w_param, l_param);
else
result = DefWindowProcW(hwnd, msg, w_param, l_param);
switch (result) {
case HTNOWHERE:
case HTRIGHT:
case HTLEFT:
case HTTOPLEFT:
case HTTOPRIGHT:
case HTBOTTOMRIGHT:
case HTBOTTOM:
case HTBOTTOMLEFT: {
handled = true;
} break;
}
if (!handled) {
POINT pos_monitor = DN_ZeroInit;
pos_monitor.x = GET_X_LPARAM(l_param);
pos_monitor.y = GET_Y_LPARAM(l_param);
handled = true;
POINT pos_client = pos_monitor;
ScreenToClient(hwnd, &pos_client);
DN_V2F32 title_bar_min = w32_window->custom_title_bar_rect_that_is_draggable.pos;
DN_V2F32 title_bar_max = DN_V2F32Add(title_bar_min, w32_window->custom_title_bar_rect_that_is_draggable.size);
DN_UInt dpi = w32->get_dpi_for_window ? w32->get_dpi_for_window(hwnd) : 96;
int frame_y = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CYFRAME, dpi) : GetSystemMetrics(SM_CYFRAME);
int padding = w32->get_system_metrics_for_dpi ? w32->get_system_metrics_for_dpi(SM_CXPADDEDBORDER, dpi) : GetSystemMetrics(SM_CXPADDEDBORDER);
bool is_over_top_resize = pos_client.y >= 0 && pos_client.y < (frame_y + padding);
bool is_over_title_bar = pos_client.x >= title_bar_min.x && pos_client.x < title_bar_max.x &&
pos_client.y >= title_bar_min.y && pos_client.y < title_bar_max.y;
bool is_maximised = IsZoomed(hwnd) != 0;
if (!is_maximised && is_over_top_resize)
result = HTTOP;
else if (is_over_title_bar)
result = HTCAPTION;
else
result = HTCLIENT;
}
}
} else {
handled = false;
}
} break;
default: {
handled = false;
} break;
}
if (!handled) {
if (w32->fallback_wnd_proc) {
result = CallWindowProcW(w32->fallback_wnd_proc, hwnd, msg, w_param, l_param);
} else {
result = DefWindowProcW(hwnd, msg, w_param, l_param);
}
}
return result;
}
DN_API void DN_Os_W32MakeProcessDPIAware()
{
typedef bool SetProcessDpiAwareProc(void);
typedef bool SetProcessDpiAwarenessProc(DPI_AWARENESS);
typedef bool SetProcessDpiAwarenessContextProc(void * /*DPI_AWARENESS_CONTEXT*/);
// NOTE(doyle): Taken from cmuratori/refterm snippet on DPI awareness. It
// appears we can make this robust by just loading user32.dll and using
// GetProcAddress on the DPI function. If it's not there, we're on an old
// version of windows, so we can call an older version of the API.
void *lib_handle = LoadLibraryA("user32.dll");
if (!lib_handle)
return;
SetProcessDpiAwarenessContextProc *set_process_dpi_awareness_context = DN_Cast(SetProcessDpiAwarenessContextProc *) GetProcAddress(DN_Cast(HMODULE) lib_handle, "SetProcessDpiAwarenessContext");
SetProcessDpiAwarenessProc *set_process_dpi_awareness = DN_Cast(SetProcessDpiAwarenessProc *) GetProcAddress(DN_Cast(HMODULE) lib_handle, "SetProcessDpiAwareness");
SetProcessDpiAwareProc *set_process_dpi_aware = DN_Cast(SetProcessDpiAwareProc *) GetProcAddress(DN_Cast(HMODULE) lib_handle, "SetProcessDpiAware");
if (set_process_dpi_awareness_context)
set_process_dpi_awareness_context(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
else if (set_process_dpi_awareness)
set_process_dpi_awareness(DPI_AWARENESS_PER_MONITOR_AWARE);
else if (set_process_dpi_aware)
set_process_dpi_aware();
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: DLL
DN_API void DN_Os_W32DllUnload(DN_OsW32DllCore *dll)
{
if (dll) {
if (dll->handle) {
FreeLibrary(DN_Cast(HMODULE) dll->handle);
dll->handle = NULL;
}
for (DN_ForItSize(it, DN_OsW32DllFunction, dll->functions, dll->functions_count))
it.data->func_ptr = NULL;
}
}
DN_API DN_OsW32DllLoadFunctionsResult DN_Os_W32DllLoadFunctions(DN_OsW32DllCore *dll, DN_Str8 dll_path)
{
DN_OsW32DllLoadFunctionsResult result = DN_OsW32DllLoadFunctionsResult_LoadLibraryFailed;
HMODULE handle = LoadLibraryA(dll_path.data);
if (handle) {
bool all_good = true;
// NOTE: Validate that all the functions can be loaded from the DLL
for (DN_ForItSize(it, DN_OsW32DllFunction, dll->functions, dll->functions_count)) {
DN_Str8 func_name = it.data->name;
DN_AssertF(func_name.count && func_name.data[func_name.count] == 0, "Function name must be set and null-terminated");
void *func_ptr = GetProcAddress(handle, func_name.data);
all_good &= (func_ptr != NULL);
}
// NOTE: If all functions can be loaded, then mutate the user's `dll` struct
if (all_good) {
result = DN_OsW32DllLoadFunctionsResult_Ok;
for (DN_ForItSize(it, DN_OsW32DllFunction, dll->functions, dll->functions_count)) {
DN_Str8 func_name = it.data->name;
it.data->func_ptr = GetProcAddress(handle, func_name.data);
}
// NOTE: Cleanup the old handle
if (dll->handle)
FreeLibrary(DN_Cast(HMODULE) dll->handle);
dll->handle = handle;
DN_StackTraceReloadSymbols();
} else {
FreeLibrary(handle);
result = DN_OsW32DllLoadFunctionsResult_FunctionMissing;
}
}
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Errors
DN_API DN_Str16 DN_Os_W32Str16FromErrorCodeToMessageW32Alloc(DN_U32 error_code)
{
DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
void *module_to_get_errors_from = NULL;
if (error_code >= 12000 && error_code <= 12175) {
flags |= FORMAT_MESSAGE_FROM_HMODULE;
module_to_get_errors_from = GetModuleHandleA("winhttp.dll");
}
wchar_t *result16 = NULL;
DWORD count = FormatMessageW(/*DWORD dwFlags */ flags | FORMAT_MESSAGE_ALLOCATE_BUFFER,
/*LPCVOID lpSource */ module_to_get_errors_from,
/*DWORD dwMessageId */ error_code,
/*DWORD dwLanguageId*/ 0,
/*LPWSTR lpBuffer */ (LPWSTR)&result16,
/*DWORD nSize */ 0,
/*va_list *Arguments */ NULL);
DN_Str16 result = DN_ZeroInit;
result.data = result16;
result.count = count;
return result;
}
DN_API DN_OsW32Error DN_Os_W32ErrorFromErrorCodeAllocator(DN_Allocator allocator, DN_U32 error_code)
{
DN_OsW32Error result = DN_ZeroInit;
result.code = error_code;
if (allocator.type != DN_AllocatorType_Nil) {
DN_Str16 error16 = DN_Os_W32Str16FromErrorCodeToMessageW32Alloc(error_code);
if (error16.count)
result.msg = DN_Os_W32Str8FromStr16Allocator(allocator, error16);
if (error16.data)
LocalFree(error16.data);
}
return result;
}
DN_API DN_OsW32Error DN_Os_W32ErrorFromLastErrorAllocator(DN_Allocator allocator)
{
DN_OsW32Error result = DN_Os_W32ErrorFromErrorCodeAllocator(allocator, GetLastError());
return result;
}
DN_API DN_OsW32Error DN_Os_W32ErrorFromLastErrorArena(DN_Arena *arena)
{
DN_Allocator allocator = DN_AllocatorFromArena(arena);
DN_OsW32Error result = DN_Os_W32ErrorFromErrorCodeAllocator(allocator, GetLastError());
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Windows Str8 <-> Str16
DN_API int DN_Os_W32Str16FromStr8Buffer(DN_Str8 src, wchar_t *dest, int dest_size)
{
int result = 0;
if (src.count == 0)
return result;
result = MultiByteToWideChar(CP_UTF8, 0 /*dwFlags*/, src.data, DN_Cast(int) src.count, NULL /*dest*/, 0 /*dest size*/);
if (result <= 0 || result > dest_size || !dest)
return result;
result = MultiByteToWideChar(CP_UTF8, 0 /*dwFlags*/, src.data, DN_Cast(int) src.count, dest, DN_Cast(int) dest_size);
dest[DN_Min(result, dest_size - 1)] = 0;
return result;
}
DN_API DN_Str16 DN_Os_W32Str16FromStr8Allocator(DN_Allocator allocator, DN_Str8 src)
{
DN_Str16 result = DN_ZeroInit;
if (allocator.type == DN_AllocatorType_Nil || src.count == 0)
return result;
int required_size = DN_Os_W32Str16FromStr8Buffer(src, NULL, 0);
if (required_size <= 0)
return result;
wchar_t *buffer = DN_AllocatorNewArray(allocator, wchar_t, required_size + 1, DN_ZMem_No);
if (!buffer)
return result;
int chars_written = MultiByteToWideChar(CP_UTF8, 0 /*dwFlags*/, src.data, DN_Cast(int) src.count, buffer, required_size);
DN_Assert(chars_written == required_size);
if (chars_written == required_size) {
result.data = buffer;
result.count = chars_written;
result.data[result.count] = 0;
} else {
DN_AllocatorDealloc(allocator, buffer, required_size + 1);
}
return result;
}
DN_API DN_Str16 DN_Os_W32Str16FromStr8Arena(DN_Arena *arena, DN_Str8 src)
{
DN_Allocator allocator = DN_AllocatorFromArena(arena);
DN_Str16 result = DN_Os_W32Str16FromStr8Allocator(allocator, src);
return result;
}
DN_API int DN_Os_W32Str8FromStr16Buffer(DN_Str16 src, char *dest, int dest_size)
{
int result = 0;
if (src.count == 0)
return result;
int src_size = DN_SaturateCastISizeToInt(src.count);
if (src_size <= 0)
return result;
result = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/, src.data, src_size, NULL /*dest*/, 0 /*dest size*/, NULL, NULL);
if (result <= 0 || result > dest_size || !dest)
return result;
result = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/, src.data, src_size, dest, DN_Cast(int) dest_size, NULL, NULL);
dest[DN_Min(result, dest_size - 1)] = 0;
return result;
}
DN_API DN_Str8 DN_Os_W32Str8FromStr16Allocator(DN_Allocator allocator, DN_Str16 src)
{
DN_Str8 result = DN_ZeroInit;
if (src.count == 0)
return result;
int src_size = DN_SaturateCastISizeToInt(src.count);
if (src_size <= 0)
return result;
int required_size = DN_Os_W32Str8FromStr16Buffer(src, NULL, 0);
if (required_size <= 0)
return result;
DN_Str8 buffer = DN_Str8AllocAllocator(required_size, DN_ZMem_No, allocator);
if (!buffer.data)
return result;
int chars_written = WideCharToMultiByte(CP_UTF8, 0 /*dwFlags*/, src.data, src_size, buffer.data, DN_Cast(int) buffer.count, NULL, NULL);
DN_Assert(chars_written == required_size);
if (chars_written == required_size) {
result = buffer;
result.data[result.count] = 0;
} else {
DN_AllocatorDealloc(allocator, buffer.data, buffer.count + 1);
buffer = DN_Literal(DN_Str8)DN_ZeroInit;
}
return result;
}
DN_API DN_Str8 DN_Os_W32Str8FromStr16Arena(DN_Arena *arena, DN_Str16 src)
{
DN_Allocator allocator = DN_AllocatorFromArena(arena);
DN_Str8 result = DN_Os_W32Str8FromStr16Allocator(allocator, src);
return result;
}
////////////////////////////////////////////////////////////////////////////////////////////////////
// NOTE: Path navigation
DN_API DN_Str16 DN_Os_W32ExePathW(DN_Arena *arena)
{
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str16 result = DN_ZeroInit;
DN_USize module_size = 0;
wchar_t *module_path = NULL;
do {
module_size += 256;
module_path = DN_ArenaNewArray(&scratch.arena, wchar_t, module_size, DN_ZMem_No);
if (!module_path) {
DN_TcScratchEnd(&scratch);
return result;
}
module_size = DN_Cast(DN_USize) GetModuleFileNameW(NULL /*module*/, module_path, DN_Cast(int) module_size);
} while (GetLastError() == ERROR_INSUFFICIENT_BUFFER);
DN_USize index_of_last_slash = 0;
for (DN_USize index = module_size - 1; !index_of_last_slash && index < module_size; index--)
index_of_last_slash = module_path[index] == '\\' ? index : 0;
result.data = DN_ArenaNewArray(arena, wchar_t, module_size + 1, DN_ZMem_No);
result.count = module_size;
DN_Memcpy(result.data, module_path, sizeof(wchar_t) * result.count);
result.data[result.count] = 0;
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_Str16 DN_Os_W32ExeDirW(DN_Arena *arena)
{
// TODO(doyle): Implement a DN_Str16_BinarySearchReverse
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str16 result = DN_ZeroInit;
DN_USize module_size = 0;
wchar_t *module_path = NULL;
do {
module_size += 256;
module_path = DN_ArenaNewArray(&scratch.arena, wchar_t, module_size, DN_ZMem_No);
if (!module_path) {
DN_TcScratchEnd(&scratch);
return result;
}
module_size = DN_Cast(DN_USize) GetModuleFileNameW(NULL /*module*/, module_path, DN_Cast(int) module_size);
} while (GetLastError() == ERROR_INSUFFICIENT_BUFFER);
DN_USize index_of_last_slash = 0;
for (DN_USize index = module_size - 1; !index_of_last_slash && index < module_size; index--)
index_of_last_slash = module_path[index] == '\\' ? index : 0;
result.data = DN_ArenaNewArray(arena, wchar_t, index_of_last_slash + 1, DN_ZMem_No);
result.count = index_of_last_slash;
DN_Memcpy(result.data, module_path, sizeof(wchar_t) * result.count);
result.data[result.count] = 0;
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_Str8 DN_Os_W32WorkingDir(DN_Arena *arena, DN_Str8 suffix)
{
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
DN_Str16 suffix16 = DN_Os_W32Str16FromStr8Arena(&scratch.arena, suffix);
DN_Str16 dir16 = DN_Os_W32WorkingDirW(&scratch.arena, suffix16);
DN_Str8 result = DN_Os_W32Str8FromStr16Arena(arena, dir16);
DN_TcScratchEnd(&scratch);
return result;
}
DN_API DN_Str16 DN_Os_W32WorkingDirW(DN_Arena *arena, DN_Str16 suffix)
{
DN_Assert(suffix.count >= 0);
DN_Str16 result = DN_ZeroInit;
// NOTE: required_size is the size required *including* the null-terminator
DN_TcScratch scratch = DN_TcScratchBeginArena(&arena, 1);
unsigned long required_size = GetCurrentDirectoryW(0, NULL);
unsigned long desired_size = required_size + DN_Cast(unsigned long) suffix.count;
wchar_t *scratch_w_path = DN_ArenaNewArray(&scratch.arena, wchar_t, desired_size, DN_ZMem_No);
if (!scratch_w_path) {
DN_TcScratchEnd(&scratch);
return result;
}
unsigned long bytes_written_wo_null_terminator = GetCurrentDirectoryW(desired_size, scratch_w_path);
if ((bytes_written_wo_null_terminator + 1) != required_size) {
// TODO(dn): Error
DN_TcScratchEnd(&scratch);
return result;
}
wchar_t *w_path = DN_ArenaNewArray(arena, wchar_t, desired_size, DN_ZMem_No);
if (!w_path) {
DN_TcScratchEnd(&scratch);
return result;
}
if (suffix.count) {
DN_Memcpy(w_path, scratch_w_path, sizeof(*scratch_w_path) * bytes_written_wo_null_terminator);
DN_Memcpy(w_path + bytes_written_wo_null_terminator, suffix.data, sizeof(suffix.data[0]) * suffix.count);
w_path[desired_size] = 0;
}
result = DN_Literal(DN_Str16){w_path, DN_Cast(DN_USize)(desired_size - 1)};
DN_TcScratchEnd(&scratch);
return result;
}
DN_API bool DN_Os_W32DirWIterate(DN_Str16 path, DN_OsW32FolderIteratorW *it)
{
WIN32_FIND_DATAW find_data = DN_ZeroInit;
if (it->handle) {
if (FindNextFileW(it->handle, &find_data) == 0) {
FindClose(it->handle);
return false;
}
} else {
it->handle = FindFirstFileExW(path.data, /*LPCWSTR lpFileName,*/
FindExInfoStandard, /*FINDEX_INFO_LEVELS fInfoLevelId,*/
&find_data, /*LPVOID lpFindFileData,*/
FindExSearchNameMatch, /*FINDEX_SEARCH_OPS fSearchOp,*/
NULL, /*LPVOID lpSearchFilter,*/
FIND_FIRST_EX_LARGE_FETCH /*unsigned long dwAdditionalFlags)*/);
if (it->handle == INVALID_HANDLE_VALUE)
return false;
}
it->file_name_buf[0] = 0;
it->file_name = DN_Literal(DN_Str16){it->file_name_buf, 0};
do {
if (find_data.cFileName[0] == '.' || (find_data.cFileName[0] == '.' && find_data.cFileName[1] == '.'))
continue;
it->file_name.count = DN_CStr16Count(find_data.cFileName);
DN_Assert(it->file_name.count < (DN_ArrayCountU(it->file_name_buf) - 1));
DN_Memcpy(it->file_name.data, find_data.cFileName, it->file_name.count * sizeof(wchar_t));
it->file_name_buf[it->file_name.count] = 0;
break;
} while (FindNextFileW(it->handle, &find_data) != 0);
bool result = it->file_name.count > 0;
if (!result)
FindClose(it->handle);
return result;
}