Task: Memory Protection
Let’s navigate to the labs/lab-03/tasks/memory-protection/, and enter the support/src/ directory.
Inspect the mem_prot.c source file. The file uses different access types for the data variable and the do_nothing function.
Build it:
student@os:~/.../memory-protection/support/$ make
gcc -g -Wall -Wextra -Werror -I../../../../../common/makefile/../utils -I../../../../../common/makefile/../utils/log -c -o mem_prot.o mem_prot.c
gcc mem_prot.o ../../../../../common/makefile/../utils/log/log.o -o mem_prot
student@os:~/.../memory-protection/support/$ ./mem_prot
reading from .data section
writing to .data section
reading from .text section
executing .text section
All current actions in the program are valid.
Let’s uncomment each commented line in the program and try again:
student@os:~/.../memory-protection/support/$ ./mem_prot
reading from .data section
writing to .data section
reading from .text section
executing .text section
executing .data section
Segmentation fault (core dumped)
We now receive the dreaded Segmentation fault message when we try to access a memory section with wrong permissions.
Permissions come into play when we control the memory address via pointers. But even for programming languages that don’t offer pointers (such as Python) issues may still arise.
In the str.py file, we look to modify str[1], but this fails:
student@os:~/.../memory-protection/support/$ ./str.py
n, 110, n
Traceback (most recent call last):
File "./str.py", line 5, in <module>
str[1] = 'z'
TypeError: 'str' object does not support item assignment
This fails because strings are, in Python, immutable. Once a string is being created, it can not be modified; you have to create a new string.
-
Add a variable named
rothat you define asconst. The variable will be placed on a read-only section (.rodata) such as that write and execution access would result in Segmentation fault.Access the
rovariable and show that, indeed, for write and execution access, Segmentation fault is issued.Check your work by running the
checker.shscript insupport/tests/.
If you’re having difficulties solving this exercise, go through this reading material.