Skip to content

Instantly share code, notes, and snippets.

@eli-rich
Last active July 2, 2022 09:10
Show Gist options
  • Save eli-rich/8383c0d51ee9279cfe4c01cd77f496de to your computer and use it in GitHub Desktop.
Save eli-rich/8383c0d51ee9279cfe4c01cd77f496de to your computer and use it in GitHub Desktop.
Trying to learn NASM
global _main
extern _printf
section .data
display: db "Enter a string: "
display_length: equ $ - display
out_str: db "Length: "
out_str_length equ $ - out_str
newline: db 10
fmt: db "%d", 0
section .bss
in_word: resw 40
fword: resb 100
w_len: resb 100
section .text
_main:
%define SYS_WRITE 0x2000004
%define SYS_READ 0x2000003
%define SYS_EXIT 0x2000001
mov rax, SYS_WRITE
mov rdi, 1
mov rsi, display
mov rdx, display_length
syscall
mov rax, SYS_READ
mov rdi, 0
mov rsi, in_word
mov rdx, 40
syscall
mov rax, SYS_WRITE
mov rdi, 1
mov rsi, out_str
mov rdx, out_str_length
syscall
; everything up until this point works
mov rdi, in_word ; set rdi to first char in the input word
call strlen
mov rsi, rax ; copy rax into rsi (AKA second parameter)
mov rdi, fmt ; load fmt into rdi (first parameter)
xor rax, rax ; clear rax
sub rsp, 8
call _printf ; call printf
add rsp, 8
; somewhere in printf the program segfaults, LLDB gives this info:
; Process 44720 stopped
; * thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
; frame #0: 0x00007ff819804a37 libsystem_c.dylib`__vfprintf + 53
; libsystem_c.dylib`__vfprintf:
; -> 0x7ff819804a37 <+53>: movdqa %xmm0, -0x180(%rbp)
; 0x7ff819804a3f <+61>: movq 0x10(%rcx), %rcx
; 0x7ff819804a43 <+65>: movq %rcx, -0x170(%rbp)
; 0x7ff819804a4a <+72>: leaq -0x290(%rbp), %rcx
; mov rax, SYS_WRITE ; write newline
; mov rdi, 1
; mov rsi, newline
; mov rdx, 1
; syscall
mov rax, SYS_EXIT ; exit
xor rdi, rdi
syscall
strlen:
xor rax, rax ; set rax to 0
mov rax, 0 ; idk if this is necessary, but I wanted to be sure *inc* worked
strlen_step:
cmp byte [rdi], 0 ; check if byte is null terminator
je strlen_end ; if yes, jump to end of loop
inc rax ; else, increment the count
inc rdi ; also increment the character of the string
jmp strlen_step ; restart loop
strlen_end:
xor rdi, rdi ; clear rdi register as it's no longer needed
dec rax
ret ; return the value of rax
@eli-rich
Copy link
Author

eli-rich commented Jul 2, 2022

Just found out you can set lldb to use intel flavored syntax so here's that:

Process 45111 stopped
* thread #1, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    frame #0: 0x00007ff819804a37 libsystem_c.dylib`__vfprintf + 53
libsystem_c.dylib`__vfprintf:
->  0x7ff819804a37 <+53>: movdqa xmmword ptr [rbp - 0x180], xmm0
    0x7ff819804a3f <+61>: mov    rcx, qword ptr [rcx + 0x10]
    0x7ff819804a43 <+65>: mov    qword ptr [rbp - 0x170], rcx
    0x7ff819804a4a <+72>: lea    rcx, [rbp - 0x290]
Target 0: (show) stopped.```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment