Hi,
I'm currently writing a little piece of code that extends the current bss segment of the program to make room for dynamically allocated data. I'm running 32-bit x86 Ubuntu. I use system call sys_brk to make room for the heap. Now my question is that should I modify stack base pointer and stack pointer in registers ebp and esp after the system call. According to my understanding sys_brk extends the bss segment towards stack meaning that if heap size is high enough my stack pointers end up pointing to some memory locations inside my heap area. This means I should move my stack pointers to point a memory locations outside the heap but in this part I bumped into a problem. I keep getting a segmentation fault and I have tracked the problem to the instructions in which I set stack pointer to point same location as stack base pointer. Should I even be doing this "stack adjustment" or is my functionality faulty?
Please don't pummel me to death if my source looks horrible. I started programming with assembly four days ago and there is quite a lot of stuff I don't know about assembly. Healthy criticism and improvement ideas are always welcome. I tried to use as much comments as I could to make the code even remotely understandable (at least I tend to forget what I was doing without them).
sys_brk: equ 45
; initializes heap of size specified in register ecx
; stack will be corrupted during this operation
global setupheap
; cleanups previously initialized heap
; stack will be corrupted during this operation
global cleanupheap
section .text
setupheap:
mov edx, ebp ; set stack base pointer to edx
; get brk location to eax
xor ebx, ebx
mov eax, sys_brk
int 0x80
sub edx, eax ; calculate difference of brk location and
; stack base pointer to edx = stack size
; extend bss section
mov [obrk], eax ; store original brk location to obrk
mov ebx, ecx ; put heap size to ebx from ecx
add ebx, eax ; calculate new brk location
mov eax, sys_brk
int 0x80
mov [cbrk], eax ; store new brk location to cbrk
pop eax ; store old value of eip to eax
; calculate new stack location
mov ebp, edx ; put stack size to ebp
add ebp, [cbrk] ; calculate new stack base pointer
mov esp, ebp ; set stack pointer to point to base of stack
push eax ; push old value of eip from eax to stack to
; allow corrent return
ret
cleanupheap:
mov edx, ebp ; set stack base pointer to edx
sub edx, [cbrk] ; calculate stack size
; shrink bss section back to it's original size
mov ebx, [obrk]
mov eax, sys_brk
int 0x80
mov [cbrk], eax ; store new brk location to cbrk
pop eax ; store old value of eip to eax
mov ebp, edx ; put stack size to ebp
add ebp, [cbrk] ; calculate new stack base pointer
mov esp, ebp ; set stack pointer to point to base of stack
push eax ; push old value of eip from eax to stack to
; allow corrent return
ret
section .bss
obrk: resb 4
cbrk: resb 4