0

How can I allocate memory in the Heap in x64 assembly. I want to store the value of the sidt function, but I can't seem to find a way on how to do so?

I use Visual studio 2012.

3 Answers3

1

You will have two options (assuming you're running in user space on top of an operating system).

  1. use whatever your operating system provides to map you some writable memory (in UNIX brk/sbrk/mmap)
  2. call the malloc library function in the C standard library (which will do (1) under the hood for you)

I'd go for number 2 as it's much simpler and kind of portable.

Something similar to the following should do the trick:

movq $0x10, %rdi
callq malloc
; %rax will now contain the pointer to the memory

Assuming ADM64 (System V AMD64 ABI) calling conventions, that'll call malloc(16) which should return you a pointer to a memory block with 16 bytes. The address should reside in the %rax register after the call returns (or 0 if not enough memory).

EDIT: Wikipedia says about the x86-64 calling conventions that Microsoft apparently uses a different calling convention (first register in RCX not RDI). So you'd need to modify movl $0x10, %rdi to movl $0x10, %rcx.

Johannes Weiss
  • 52,533
  • 16
  • 102
  • 136
  • My computer has an Intel processor. I tried calling malloc, but when I try to compile it, it says that it is an unknown symbol. – Dimitra Anastasopoulou May 06 '15 at 11:51
  • 1
    @FredericaBernkastel can you try `callq _malloc`. Depends a bit on your linker what exactly you'll have to do to call a `libc` function. You might also need to tell it to link `libc`. Maybe just make a C program where you call malloc, disassemble it and then you'll see what it takes. – Johannes Weiss May 06 '15 at 12:02
  • 1
    possibly also `.extern _malloc` or `.extern malloc` or whatever your assembler uses to mark an external symbol. – Johannes Weiss May 06 '15 at 12:05
0

Judging by your environment, I'm guessing that you're writing assembly code in Windows. You'll need to use the Windows equivelent to an sbrk system call. You may find this MSDN reference useful!

David Hoelzer
  • 15,862
  • 4
  • 48
  • 67
0

Write the code to call malloc in C, then have the compiler produce an assembly listing, which will show you the name used for malloc (probably _malloc in the case of Microsoft compilers), and how to call it.

Another option would be to allocate space from the stack with a subtract from esp, equal to the size of a structure that will hold the sidt information.

rcgldr
  • 27,407
  • 3
  • 36
  • 61