1
votes

I was reading wikipedia on Segmentation Faults and come through following code and statements.

int main(void)
 {
     char *s = "hello world";
     *s = 'H';
 }

When the program containing this code is compiled, the string "hello world" is placed in the section of the program executable file marked as read-only; when loaded, the operating system places it with other strings and constant data in a read-only segment of memory. When executed, a variable, s, is set to point to the string's location, and an attempt is made to write an H character through the variable into the memory, causing a segmentation fault. Compiling such a program with a compiler that does not check for the assignment of read-only locations at compile time.

My question is on file permission i.e, when executables marked as read-only and when read and write and so on ?

I want to know all about file permissions.Can we change the file permission explicitly?

2
When it says file, does it mean stack over here?noMAD
File access permissions and memory access permissions within a running program are not related. Marking an executable program as writable will not cause its text pages to be mapped read/write; conversely, marking it read only will not cause its data pages to be unexpectedly mapped read only.geekosaur
I'm not sure how file permissions are relevant -- the wiki article is referring to permissions of pages of memory. It may be possible to change page permissions in a system-specific way, such as mprotect() on POSIX systems.FatalError
here file is executable file.IndieProgrammer

2 Answers

5
votes

"hello world" is stored in a read-only section of memory. The ability to write to a given part of an executable's memory is not related to the ability to write to the executable on disk.

2
votes

There are 3 unrelated concepts you are talking in this question:

  • file attributes (supported by some OS, i.e. Windows) - one of them is read-only. Manages how normally files will be opened, user with permissions to modify file can change file attributes at will.
  • file permissions (supported by most OS). If given user have permission to access/modify, and in some systems execute the file.
  • memory protection attributes on pages of memory. Supported by most OS that implement virtual memory. Each page (i.e. 4Kb block) of memory gets set of attributes (i.e. read, write, execute) that are set and enforced by memeory management part of OS together with CPU. Most modern CPUs directly use this page attribute to verify memory operations.

I.e. on Windows you can use VirtualProtect function to specify what attributes given memory block allocated in your program's address space should have.