Skip to content
This repository was archived by the owner on Oct 12, 2022. It is now read-only.

Commit 20963f9

Browse files
kinkeGeod24
authored andcommitted
GC: Sanitize isLowOnMem() for Windows
1 parent 899f4e5 commit 20963f9

File tree

1 file changed

+18
-26
lines changed
  • src/core/internal/gc

1 file changed

+18
-26
lines changed

src/core/internal/gc/os.d

Lines changed: 18 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -213,46 +213,38 @@ else
213213
Returns:
214214
true if memory is scarce
215215
*/
216-
// TOOD: get virtual mem sizes and current usage from OS
216+
// TODO: get virtual mem sizes and current usage from OS
217217
// TODO: compare current RSS and avail. physical memory
218-
version (Windows)
218+
bool isLowOnMem(size_t mapped) nothrow @nogc
219219
{
220-
bool isLowOnMem(size_t mapped) nothrow @nogc
220+
version (Windows)
221221
{
222-
version (D_LP64)
222+
import core.sys.windows.winbase : GlobalMemoryStatusEx, MEMORYSTATUSEX;
223+
224+
MEMORYSTATUSEX stat;
225+
stat.dwLength = stat.sizeof;
226+
const success = GlobalMemoryStatusEx(&stat) != 0;
227+
assert(success, "GlobalMemoryStatusEx() failed");
228+
if (!success)
223229
return false;
224-
else
225-
{
226-
import core.sys.windows.winbase : GlobalMemoryStatus, MEMORYSTATUS;
227-
MEMORYSTATUS stat;
228-
GlobalMemoryStatus(&stat);
229-
// Less than 5 % of virtual address space available
230-
return stat.dwAvailVirtual < stat.dwTotalVirtual / 20;
231-
}
230+
231+
// dwMemoryLoad is the 'approximate percentage of physical memory that is in use'
232+
// https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-memorystatusex
233+
const percentPhysicalRAM = stat.ullTotalPhys / 100;
234+
return (stat.dwMemoryLoad >= 95 && mapped > percentPhysicalRAM)
235+
|| (stat.dwMemoryLoad >= 90 && mapped > 10 * percentPhysicalRAM);
232236
}
233-
}
234-
else version (Darwin)
235-
{
236-
bool isLowOnMem(size_t mapped) nothrow @nogc
237+
else
237238
{
238239
enum GB = 2 ^^ 30;
239240
version (D_LP64)
240241
return false;
241-
else
242+
else version (Darwin)
242243
{
243244
// 80 % of available 4GB is used for GC (excluding malloc and mmap)
244245
enum size_t limit = 4UL * GB * 8 / 10;
245246
return mapped > limit;
246247
}
247-
}
248-
}
249-
else
250-
{
251-
bool isLowOnMem(size_t mapped) nothrow @nogc
252-
{
253-
enum GB = 2 ^^ 30;
254-
version (D_LP64)
255-
return false;
256248
else
257249
{
258250
// be conservative and assume 3GB

0 commit comments

Comments
 (0)