Re: Understanding Linux addr space, malloc, and heap

From: Kyle Moffett
Date: Fri Oct 21 2005 - 10:52:58 EST


On Oct 21, 2005, at 11:37:07, Vincent W. Freeh wrote:
The point of the code is to show that one can protect malloc code.

You may be able to protect malloced memory, but it's not reliable, it doesn't follow the standard, and if it breaks you get to keep both pieces. You tried to protect malloced memory, it wasn't reliable, it didn't follow the standard, therefore you get to keep both pieces.

But I can't mprotect the 66th page I malloc. And mprotect fails SILENTLY!
You must understand that malloc does not necessarily return a _page_. It returns a random hunk of memory aligned to a 16 byte boundary, which is *not* the same as aligned to a page boundary (usually 4096 bytes). Your code is buggy:

mprotect((void*)((unsigned)p & ~(pgsize-1)), 1024, PROT_NONE);

You malloced 1024 bytes (1024 != page size (usually 4096)). You then round down to a multiple of a page size, and mprotect that page (since you used a size < 1 page, it rounds up to a page). If malloc returns an offset 4080 bytes into a page (aligned on a 16-byte boundary), and you round down and protect that page, then only the first 16 bytes of the memory you got will be protected.

You *cannot* reliably expect to mprotect() the results of malloc(). If you want to mprotect() things, you _must_ do it on mmap()ed memory.

Cheers,
Kyle Moffett

--
Somone asked me why I work on this free (http://www.fsf.org/ philosophy/) software stuff and not get a real job. Charles Shultz had the best answer:

"Why do musicians compose symphonies and poets write poems? They do it because life wouldn't have any meaning for them if they didn't. That's why I draw cartoons. It's my life."
-- Charles Shultz


-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/