0

I'm trying to allocate memory with sys_brk and here is the program:

BYTES_TO_ALLOCATE equ 0x08

section .text
    global _start

_start:
    mov rax, 12 ;sys_brk number
    mov rdi, BYTES_TO_ALLOCATE
    syscall

    mov cl, 0x00 ;setting the value I need
    mov [rax], byte 0x01 ;SegFault
    mov rax, 60
    syscall

As specified in the linux manual

sbrk() increments the program's data space by increment bytes. Calling sbrk() with an increment of 0 can be used to find the current location of the program break.

I segfaulted when runnning the program. The register content before the segfaulted mov was:

rax            0x401000 4198400
rbx            0x0      0
rcx            0x40008c 4194444 

I also tried to decrement the rax value as follows:

BYTES_TO_ALLOCATE equ 0x08

_start:
    mov rax, 12 ;sys_brk number
    mov rdi, BYTES_TO_ALLOCATE
    syscall

    mov rbx, rax
    dec rbx
    mov [rbx], byte 0x01 ;Again SegFault
    mov rax, 60
    syscall

Now, I'm kind of confused how to use sys_brk return value. I took it from here. I also tried to use value in rcx but segfaulted anyway.

St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • RCX is not part of the return value from the syscall. [SYSCALL](http://www.felixcloutier.com/x86/SYSCALL.html) instruction itself clobbers RCX and R11 (RCX happens to contain the address of the instruction after the SYSCALL and R11 is a copy of RFLAGS. Using RCX is pretty useless. – Michael Petch Dec 27 '17 at 21:07
  • [The value in `rcx` = RIP, which you already know from my answer to your previous question](https://stackoverflow.com/questions/47983371/why-do-x86-64-linux-system-calls-modify-rcx-and-what-does-the-value-mean). Your program text is in a read-only page, so of course a store to `[rcx]` segfaulted. RAX is the return value, and RCX + R11 are clobbered, stop worrying about what's in RCX. – Peter Cordes Dec 27 '17 at 21:07
  • 1
    `sys_brk` *sets* the program break, it doesn't *increment* it. See [the only good answer on the linked duplicate](https://stackoverflow.com/a/44876873/224132). Your system call with a small integer as the pointer arg may have unmapped all heap pages (at least the ones in the brk area), if there were any to start with. – Peter Cordes Dec 27 '17 at 21:11
  • When single-stepping, look at `/proc/PID/smaps` to see what regions are mapped before/after the system call. – Peter Cordes Dec 27 '17 at 21:14
  • @PeterCordes Understood, many thanks! – St.Antario Dec 27 '17 at 22:25

0 Answers0