Allocate memory (x64 assembly)

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.

Upvotes: 0

Views: 2059

Answers (3)

rcgldr
rcgldr

Reputation: 28836

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.

Upvotes: 0

Johannes Weiss
Johannes Weiss

Reputation: 54071

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.

Upvotes: 1

David Hoelzer
David Hoelzer

Reputation: 16351

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!

Upvotes: 0

Related Questions