Defrag memory with NT API
The memory fragmentation is inevitable when the system is running, this can affect the system performance, so it is necessary to defrag the memory at the proper time.
Most of the memory defragmentation tools on the market today achieve the goal through allocating as many memory blocks as possible from the system to squeeze as many memory blocks as possible into the swap file before releasing them. I do not think this is an elegant approach, because it requires that your tool must be running in Native mode instead of the WoW compatibility layer, for example, if your tool is 32-bit it can only request up to 4GB of memory from the system, which is not enough to achieve your goal. And since you are forcing the system to squeeze memory blocks into the swap file, it is not efficient and has a significant negative impact on the scheduling mechanism.
So, this article proposes a new way of memory defragmentation by calling the NT API to inform the kernel to move the memory blocks to the swap file automatically, so the process is very fast and has minimal impact on the scheduling mechanism.
Read here for the Chinese version of this article if you are not good at English. (Translation: 如果你不擅长英文,可以点击本段话中的链接阅读中文版)
Inspiration source
When I used the features in the Empty menu from RAMMap tool in Sysinternals Suite, I found we can defrag memory efficiently with the proper operations.
So I used IDA Pro to analyze the features related to the RAMMap tool, and summarize my conclusions and write this article with examples.
Operation method
You need to run your binary as administrator.
First enable the SeProfileSingleProcessPrivilege privilege for the current process, then call NtSetSystemInformation and pass MemoryEmptyWorkingSets, MemoryFlushModifiedList and MemoryPurgeStandbyList to SystemMemoryListInformation to perform memory defragmentation.
Code example
The following example rely on the NT API definitions from https://github.com/Chuyu-Team/MINT created by myself.
1 |
|
See also
Windows Research NotesUnless otherwise stated, all articles in this blog follow the CC BY-NC-ND 4.0 license, please indicate the source for reprinting!