I'm trying to learn x86 assembly. The book I'm using is Assembly Language - Step by Step, Programming With Linux
(and I'd have to say it's pretty good). I've learned a lot so far, but I feel as though I should also be challenging myself to stay ahead in many respects so I can learn faster through doing (I can do follow along, top-down learning, but I find it tediously slow).
So, I figured it would be a cool idea to try and multiply two registers (32-bit) and then output the data to the console.
The problem is that when I execute the program (I'm using NASM, just as the book does - no Insight debugger though), I receive a segmentation fault. I've done a fair amount of debugging in gdb with this little hammer out, but for whatever reason I can't seem to figure out what the issue is.
I'd like to know why I'm receiving a segmentation fault, and what a good way would be to reprimand the issue. Also, if the comments I've made in the code don't match up with what exactly is happening, I'd be grateful if anyone could correct me on that.
Here's my code so far (it's well commented)
Thanks.
teh codez
section .data
;TODO
section .bss
valueToPrint: resb 4 ;alloc 4 bytes of data in 'valueToPrint'
section .text
global _start
_mul:
mov eax, 0x2A ;store 42 in eax
mov edx, 0x2A ;store 42 in edx
mul eax
ret
_safe_exit:
mov eax, 1 ;initiate 'exit' syscall
mov ebx, 0 ;exit with error code 0
int 0x80 ;invoke kernel to do its bidding
_start:
nop ;used to keep gdb from complaining
call _mul ;multiply the values
mov [valueToPrint], eax ;store address of eax in the contents of valueToPrint
mov eax, 4 ;specify a system write call - aka syswrite
mov ebx, 1 ;direction used to make the syswrite call output to console - i.e. stdout
mov dword [ecx], valueToPrint ;store valueToPrint in ecx: ecx represents the syswrite register
int 0x80 ;invoke kernel based on the given parameters
call _safe_exit
Edit
Also, I'm running Arch Linux, if that makes a difference.
EDITIT! (forgot a cmp!)
To output value in base 10...
This line is causing the segmentation fault:
You're telling it to store
valueToPrint
in the memory location at addressecx
. You never initializeecx
(the kernel probably initializes it to 0 on program start for you), so when you dereference it, you're going to access an invalid memory location.The
write(2)
system call takes 3 parameters: the file descriptor number in registerebx
, a pointer to the string to write inecx
, and the number of bytes to write inedx
. So, if you want to just print the raw binary data of the result, you can pass the address ofvalueToPrint
, and tell it to print 4 bytes from that address. In this case,valueToPrint
is 1764 (0x6e4 in hex), so this code would print out the 4 bytese4 06 00 00
on x86, which is little-endian: