Does macOS automatically erase freed memory (to prevent leakage of information left in freed memory)?

Solution 1:

Your question is a bit vague and therefore hard to answer.

Contrary to what you write, Linux does not automatically erase every bit of freed memory on the system. To answer your question #1, macOS does not do this either.

I think your misconception about Linux comes from the fact that Linux can clear freed kernel memory, if configured to do so. On normal systems that is only a small fraction of the total system memory.

If you look at user space applications on macOS, the developer can set it up so that memory is cleared or poisoned on free. For performance reasons, this is mostly done with parts of memory where secrets can be leaked (such as for example cryptographic keys).

If you're interesting purely in the kernel itself, then the macOS kernel also has features related to zeroing and poisoning freed memory. The kernel includes a zone allocator, where zones can be setup to be zeroed, poisoned (i.e. 0xdeadbeef written all over) or merely canaried (i.e. a canary - specific data bytes - is written to the start and end of the allocation - primarily to catch bugs).

The kernel by default enables instant poisoning for very small alloocations (up to the size of the CPU's cache line size - depends on the CPU, but could for example be 64 bytes). For larger allocations, freed memory is periodically poisoned with a frequency depending on the size of the allocation. Instant poisoning of very large allocations comes with a performance impact, so this reduces or at least spreads out that impact.

You can find the source code for the zone allocator here:

https://github.com/apple/darwin-xnu/blob/main/osfmk/kern/zalloc.c

Looking back at the version history, I can see that memory poisoning was included as an option back in 2009 - this would place it just before Mac OS X Snow Leopard.

As far as I know, memory poisoning was included in iOS 2 (at the time called iPhone OS), which means that it was probably implemented by Apple in 2008. The public source dump for the macOS kernel includes this in 2009. It seems to me that it was introduced as a feature in Linux in 2009 in this patch:

https://lwn.net/Articles/321595/

In addition to the generic VM feature, the macOS kernel also features a system similar to the Linux Kernel Address Sanitizer (KASAN) that also does memory poisoning. As far as I know, it was introduced in 2017.

You can find the source code for the feature here:

https://github.com/apple/darwin-xnu/tree/main/san