NASM - The Netwide Assembler
NASM Forum => Programming with NASM => Topic started by: Medussa on November 13, 2013, 07:15:49 PM
-
hello ;) i want to know if there is any chance to make a buffer with dynamic amount of bytes
Thanks
-
Hi!
You can allocate memory using C function, like malloc.
Demo:
section .bss use32
pointer: resd 1
section .code use32
; ...
push dword 2048
call malloc
cmp eax,dword (0)
jne .gotMemory
; ...
.gotMemory:
mov dword [pointer],eax
; use your pointer
Example code allocates 2048 bytes of mem.
Encryptor256!
-
The .bss section is used to contain uninitialized data. The sizes of data and buffers contained there will not make the on-disk size of your executable larger as the memory is allocated by the OS when your program is loaded.
However, you mention dynamically sized memory buffers. This is the function of the heap routines which you can call into the OS to obtain or use such library functions as malloc() and friends . They will provide you dynamic memory allocations from the free heap space that you can then read from and write to.
-
Hi!
Right now, im programming something, so,
few seconds ago, i created a procedure that allocates dynamic (zero) buffer.
x64
; -----------------------------------------------------------;
;
; Procedure: sysAllocateMemory
;
; Usage:
; mov rcx,qword (2048)
; call sysAllocateMemory
; jc .quitError
;
; mov rcx,rax
; call free
;
;
; Returns a pointer to buffer into RAX.
; Set's carry flag on error.
; Clear's carry flag on success.
;
; -----------------------------------------------------------;
sysAllocateMemory:
; Check incoming argument
cmp rcx,qword (0)
jg .goodArg
stc
ret
.goodArg:
; Create stack
push rbp
mov rbp,rsp
push rbx
lea rsp,[rsp-(8*5)]
; Save "byte count" into RBX
mov rbx,rcx
; Allocate memory
; rcx remains set
call malloc
; Check for error
cmp rax,qword (0)
jne .gotMemory
stc
jmp .quit
.gotMemory:
; Restore "byte count" into r8
mov r8,rbx
; Save mem pointer into RBX
mov rbx,rax
; Init memory
mov rcx,rax
xor rdx,rdx
; r8 remains set
call memset
; Set return value, restore mem pointer from RBX
mov rax,rbx
; Set success
clc
; Clean stack n quit
.quit:
lea rsp,[rsp+(8*5)]
pop rbx
pop rbp
ret
Byte!
Encryptor256!!!
-
Neat! Thanks, Encryptor256! I think Medussa is using Linux. The 32-bit version should work pretty much the same - push the size and call malloc. The 64-bit version, however... at a minimum, we need to use rdi for the size, not rcx. Stack management may differ, too. Bless their little black hearts that they did that to us!
We also have the option of sys_brk or sys_mmap (sys_mmap2 ?) to do it with system calls. We can get as big a buffer as we want in section .bss, but it'll be a fixed size - determined at assemble-time, not dynamic. Depends on what you need to do...
Best,
Frank