Je Rog
Je Rog

Reputation: 6001

What's the protection flags of memory allocated by malloc?

According to this thread,memory allocated by malloc at least have PROT_READ | PROT_EXEC,otherwise the contaned function can't be executed .

man malloc doesn't mention anything about protection thus the question.

Upvotes: 7

Views: 6320

Answers (4)

John Vincent
John Vincent

Reputation: 731

The malloc() library function is specified by the C language standard, so it is the same on all operating systems. The memory protection is a function of the processor and operating system, so it is done differently on Windows, Linux, etc.

The way this works has changed over the years since malloc() was defined. I remember when most processors did not support a separate "executable" permission for memory - if it was readable, it was executable. Many embedded systems don't have any memory protection at all, all memory can be read, written, and executed. The malloc() function works the same way in all these cases.

Upvotes: 0

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215387

malloc is not the right tool for allocating memory for code. You should use mmap, and depending on the paranoid security policies on your system, you might need to use mprotect too for changing the permissions.

Among the reasons malloc is not the right tool:

  • Permissions are set only with page granularity, but memory obtained by malloc is unlikely to be page-aligned, and thus you'll end up setting permissions on adjacent memory too, possibly breaking things.
  • If you don't restore the old permissions before calling free, you might break malloc's internals.

Upvotes: 6

ninjalj
ninjalj

Reputation: 43718

malloc() will normally return memory with read and write permissions. Some architectures (e.g: older x86) may not allow disabling execute permission in a straightforward way, but that's just a defficiency of the platform.

If you want to execute code from memory you allocated, you'll have to give execute permissions explicitly, and possibly you'll have to remove write permissions, since having both write and execute permissions on the same memory is considered potentially dangerous on some systems (commonly referred as W^X).

There have been several other threads on executing code from memory allocated by the programmer:

Allocate executable ram in c on linux
Is it possible to execute code from the stack in standard C?

Upvotes: 6

Paul R
Paul R

Reputation: 213059

You may need to call mprotect to set the PROT_EXEC flag yourself, after the memory has been allocated.

$ man mprotect

Upvotes: 2

Related Questions