-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmalloc.asm
More file actions
65 lines (52 loc) · 1.58 KB
/
malloc.asm
File metadata and controls
65 lines (52 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
format ELF64
public _start
extrn free
extrn malloc
extrn printf
extrn sleep
section '.data' writeable
fail_msg db "Failed to allocate memory.", 0xA, 0x0
free_msg db "Freed memory.",0xA,0x0
int_msg db "value: %d", 0xA, 0
eax_msg db "eax: %d", 0xA, 0
mem dd ? ; no init
section '.text' executable
_start:
mov rdi, 2 ; Allocate 2 bytes
call malloc
or eax, eax ; test for error
jz _malloc_fail ; failed to allocate
mov [mem], eax ; save address > [mem]
jmp _malloc_success
_malloc_fail:
mov rdi, fail_msg
call printf ; indicate failure.
jmp _exit
_malloc_success: ; Write something > [mem]
mov eax, [mem]
mov ebx, 10 ; mem [0] = 10
mov [eax], ebx
mov ebx, 5 ; mem [1] = 5
mov [eax+4], ebx
mov eax, [mem] ; Print 1st value :
mov rdi, int_msg
mov esi, [eax]
call printf
mov rdi, eax_msg ; See what's in [eax]
call printf ; Some random numbers => 12823192
mov eax, [mem] ; Print 2nd value :
mov rdi, int_msg
mov esi, [eax+4]
call printf
mov edi, 2
call sleep
mov edi, [mem] ; <- Actually Free Memory
call free ; Unlike many other languages.
mov rdi, free_msg ; Free Message + wait 10 secs :
call printf
mov edi, 10
call sleep
_exit:
mov rdi, 0 ; error_code
mov rax, 60 ; syscall_exit
syscall