内核将内存归零? [英] Kernel zeroes memory?

查看:19
本文介绍了内核将内存归零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Debian 挤压并注意到内存总是归零.这是 linux 发行版中的新功能吗?前段时间,我相信我可以使用 puts() 并且会输出垃圾.

I am using Debian squeeze and have noticed that memory is always zeroed. Is this new in linux distributions ? Some time ago, I believe I could use puts() and garbage would be output.

我多次运行此测试程序,但注释结果始终相同.(我在 sysctl.conf 中有 randomize_va_space=2 所以我知道每次运行时都在使用不同位置的内存.)

I run this test program many times but the commented results are always the same. (I have randomize_va_space=2 in sysctl.conf so I know that memory in different locations is being used at each run.)


char *a = malloc(50000000);
a[49999999] = '';
puts(a); // it outputs nothing since all are zeroes
printf("%p
", a);
if(a[5000] == '') // this condition is always true
{
    puts("It is a nul char.");
}

是否可以使系统不为零内存?这个 Debian 挤压安装有哪些选项可以激活总是零内存?

Is it possible to make the system not zero memory ? What options could this Debian squeeze installation have activated that always zero memory ?

推荐答案

在任何现代操作系统上,新获得的内存将包含非零值的唯一方法是,之前由程序释放的内存是否被 malloc代码>.当从操作系统(内核)获得新内存时,它最初是纯虚拟.它没有物理存在;相反,它被映射为一个充满 0 字节的共享内存页面的写时复制映射.第一次尝试写入时,内核将捕获写入,分配新的物理内存页面,将原始页面的内容(在本例中均为 0 字节)复制到新页面,然后恢复你的程序.如果内核知道新分配的物理内存已经被零填充,它甚至可以优化复制步骤.

On any modern operating system, the only way newly obtained memory will contain nonzero values is if memory previously freed by your program got reused by malloc. When new memory is obtained from the operating system (kernel), it is initially purely virtual. It has no physical existence; instead it is mapped as copy-on-write mappings of a single shared memory page that's full of 0 bytes. The first time you attempt to write to it, the kernel will trap the write, allocate a new page of physical memory, copy the contents of the original page (which in this case are all 0 bytes) to the new page, and then resume your program. If the kernel knows the newly allocated physical memory is already zero-filled, it might even be able to optimize out the copy step.

这个过程既必要又有效.这是必要的,因为将可能包含来自内核或其他用户进程的私有数据的内存移交给您的进程将是一个严重的安全漏洞.它是高效的,因为在分配时不执行归零;零填充"页面只是对共享零页面的引用.

This procedure is both necessary and efficient. It's necessary because handing over memory that might contain private data from the kernel or another user's processes to your process would be a critical security breach. It's efficient because no zeroing is performed at allocation time; the "zero-filled" pages are just reference to a shared zero page.

这篇关于内核将内存归零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆