Assembly 'Segmentation Fault' When Trying to Print Decimal Number - linux

I am trying to create a macro that will print a decimal number for me. My idea was to divide the number by ten, convert the remainder to ASCII and push it into the stack until the the ratio is 0. I then print the digits one by one but for some reason I get a 'Segmentation fault'.
I am using Linux, nasm, and a x86_64 processor.
%macro printInt 1
mov rax, %1
mov rbx, 0
%%loop1: ;Convert all digits to ascii
inc rbx ;Count of the digits in number
mov rdx, 0
div rax
add rdx, 48 ;Convert remainder to ascii
push rdx ;Push remainder into stack
cmp rax, 0 ;Compare ratio to 0
jne %%loop1
%%loop2: ;Print the number digit by digit
dec rbx
mov rax, 1 ;Sys_Write
mov rdi, 1 ;STDOUT
pop rsi ;Pop digit
mov rdx, 1
syscall
cmp rbx, 0
jne %%loop2
%endmacro
section .data
number1 db 123
section .text
global _start
_start:
printInt number1
mov rax, 60
mov rdi, 0
syscall
Any help is appreciated, thanks in advance!

First mistake:
number1 db 123
number1 is defined as BYTE, but will be treated as QUADWORD (mov rax, %1). Change it to
number1 dq 123
Second mistake:
printInt number1
The macro gets the argument as string. So, mov rax, %1 will be solved to mov rax, number1. In NASM, RAX will get the address of number1, not the value. Change it to
printInt [number1]
Third mistake:
div rax
means: Divide RDX:RAX by RAX, store the result in RAX and the remainder in RDX. This will always result in RAX=1 and RDX=0. Use another register with the value 10.
Fourth mistake:
pop rsi
The SYSCALL/RAX=1 routine of the kernel expects a pointer in RSI, not a number. There are several ways to address the problem. I leave that to your imagination.

Related

How do I print out two-digit integers in ASM, ( Linux NASM x86_64 )

This is how to print out a number, but how do I print out 2 digit numbers?
section .data
num: db 9,10
section .text
global _start
_start:
mov rax,[num]
add rax,48
mov [num],al
mov rax,1
mov rdi,1
mov rsi,num
mov rdx,2
syscall
mov rax,60
mov rdi,0
syscall
This simply prints out 9, but if I make num 12 it gives me a '<'.
I believe it is printing out the ascii character for 60, which is '<'.
mov rax,[num]
Because num just holds a byte, better not read this as a qword. Use the movzx eax, byte [num] instruction. You don't need the movzx rax, byte [num] instruction because all writing to a dword register already zeroes the high dword anyway.
but how do I print out 2 digit numbers?
Next code can do just that, printing numbers from the range [10,99].
Note that there's a placeholder right in front of the newline.
section .data
num: db 12, 0, 10
section .text
global _start
_start:
movzx eax, byte [num] ; Value LT 100
xor edx, edx
mov ebx, 10
div ebx ; Quotient in EAX, Remainder in EDX
mov ah, dl
add ax, '00' ; Convert to ASCII
mov [num], ax ; Stores 'tens' followed by 'ones'
mov rax, 1
mov rdi, 1
mov rsi, num
mov rdx, 3 ; 3 instead of 2
syscall
For a general approach you could first study Displaying numbers with DOS. It explains the methodology, but of course you'll need to adapt the code to 64-bit.
Even better info is at https://stackoverflow.com/a/46301894.

Displaying a number in x86-64 assembly with only Linux system calls [duplicate]

This question already has answers here:
Why should EDX be 0 before using the DIV instruction?
(2 answers)
How do I print an integer in Assembly Level Programming without printf from the c library? (itoa, integer to decimal ASCII string)
(5 answers)
Closed 2 years ago.
Previous version of this question (that question originally had a different problem, even though the code there is now the same as the code in this question)
I am trying to make code to display a number on console in Linux 64 bit NASM, without the use of c/c++ functions (pure assembly). The code compiles and links fine but it will not give output...
It displays just newline for some time and then displays '7' forever. I am new to Assembly so I don't know what is wrong. Please help... Here is the code:
section .data
num: dq 102 ;my default number to get the reverse of (for now)
nl: db 0x0a
nlsize: equ $-nl
ten: dq 10
section .bss
rem: resq 1
remsize: equ $-rem
section .text
global _start
_start:
cmp qword [num], 0
jng _exit ;jump to _exit if num is not greater than 0
mov rax, [num] ;move the number to rax
mov rbx, [num] ;move the number to rbx as well so that i have original number in register to subtract and get the remainder
mov rcx, [ten] ;move 10 to rcx to be the divisor
div rcx ;divide number in rax by 10
mov [num], rax ;get the quotient to get the remaining number for quotient
mul rcx ;multiply number in rax by 10
sub rbx, rax ;subtract rbx - rax and store the value in rax (right?)
mov [rem], rbx ;get the remainder from rax. this must be done right after div (WHY??????????)
call _disprem ;call _disprem to display the remainder... call returns the flow back to the caller right?
jmp _start ;get to the loop again
_exit:
mov rax, 60
mov rdi, 0
syscall
_newl:
mov rax, 1
mov rdi, 1
mov rsi, nl
mov rdx, nlsize
syscall
ret
_disprem:
mov rax, 1
mov rdi, 1
add qword [rem], 0x0000000000000030 ;since the rem variable is quadword (64 bit)
mov rsi, rem ;for getting ascii value (48 is ascii 0 in decimal) to convert the rem to character
mov rdx, remsize
syscall
sub qword[rem], 0x0000000000000030 ;get me my original number back plz thanks
call _newl
ret

Displaying a number - assembly code not working Linux, x64 (NASM) [duplicate]

This question already has answers here:
Displaying a number in x86-64 assembly with only Linux system calls [duplicate]
How do I print an integer in Assembly Level Programming without printf from the c library? (itoa, integer to decimal ASCII string)
(5 answers)
Closed 2 years ago.
I am learning assembly on Linux (NASM) x64 machine (I don't have access to 32 or 16 bit machine), and I am trying to display number on screen (reverse of number according to code but that's a start).
Number is predefined in section .data -> num.
I am quite a newbie at assembly programming and due to the lack of material on x64 assembly (really, cant find much, and all I was able to find was quite confusing) I am unable to resolve the issue.
The issue is that the code compiles an links with no errors/warnings, but it just displays some spaces (not even newline). If I remove the call _newl code from _disprem, those spaces are also gone. There is not even segment fault or something.
By the way, algorithm to get the remainder (to get the digits in a number) is num - (num / 10) * 10
section .data
num: dq 102 ;my default number to get the reverse of (for now)
nl: db 0x0a
nlsize: equ $-nl
ten: dq 10
section .bss
rem: resq 1
remsize: equ $-rem
section .text
global _start
_start:
cmp qword [num], 0
jng _exit ;jump to _exit if num is not greater than 0
mov rax, [num] ;move the number to rax
mov rbx, [num] ;move the number to rbx as well so that i have original number in register to subtract and get the remainder
mov rcx, [ten] ;move 10 to rcx to be the divisor
div rcx ;divide number in rax by 10
mov [num], rax ;get the quotient to get the remaining number for quotient
mul rcx ;multiply number in rax by 10
sub rbx, rax ;subtract rbx - rax and store the value in rax (right?)
mov [rem], rbx ;get the remainder from rax. this must be done right after div (WHY??????????)
call _disprem ;call _disprem to display the remainder... call returns the flow back to the caller right?
jmp _start ;get to the loop again
_exit:
mov rax, 60
mov rdi, 0
syscall
_newl:
mov rax, 1
mov rdi, 1
mov rsi, nl
mov rdx, nlsize
syscall
ret
_disprem:
mov rax, 1
mov rdi, 1
add qword [rem], 0x0000000000000030 ;since the rem variable is quadword (64 bit)
mov rsi, rem
mov rdx, remsize
syscall
sub qword [rem], 0x0000000000000030 ;get me my original number back plz thanks
call _newl
ret

Linux Intel 64bit Assembly Division

I am battling to understand why my division is not working, below is my current code, which simply takes in two single digits and attempts to divide them:
STDIN equ 0
SYS_READ equ 0
STDOUT equ 1
SYS_WRITE equ 1
segment .data
num1 dq 0
num2 dq 0
quot dq 0
rem dq 0
segment .text
global _start
_start:
mov rax, SYS_READ
mov rdi, STDIN
mov rsi, num1
mov rdx, 2
syscall
mov rax, SYS_READ
mov rdi, STDIN
mov rsi, num2
mov rdx, 2
syscall
mov rax, [num1]
sub rax, '0'
mov rbx, [num2]
sub rbx, '0'
xor rdx, rdx
div rbx
add rax, '0'
mov [quot], rax
mov [rem], rdx
mov rax, SYS_WRITE
mov rdi, STDOUT
mov rsi, quot
mov rdx, 1
syscall
mov rax, 60
xor rdi, rdi
syscall
Now as far as I understand when dividing the assembler will divide RDX:RAX by the operand RBX. I can only assume this is where the problem is coming in, the fact that I am dividing a 128bit value by a 64bit value. Whenever I enter something such as 8 / 2 or something similar, I receive the value 1 as the quotient. What am I missing here? Any help would be greatly appreciated.
You read 2 bytes for the operands, but it seems you ignore the 2nd, when you shouldn't.
Assuming you type 8 and 2 and one line each, you will read "8\n" and "2\n". You then subtract '0', but you leave the '\n', so your operands will be 0x08 0x0A and 0x02 0x0A, which are 2568 and 2562. And 2568 / 2562 = 1.

x86-64 Bit Assembly Linux Input

I'm trying to input into my program... All it does is run through and print a '0' to the screen. I'm pretty sure that the PRINTDECI function works, I made it a while ago and it works. Do I just have to loop over the input code and only exit when I enter a certain value? I'm not sure how I would do that... Unless it's by ACSII values which might suck.... Anyways, here's my code (Yasm(nasm clone), Intel Syntax):
GLOBAL _start
SECTION .text
PRINTDECI:
LEA R9,[NUMBER + 18] ; last character of buffer
MOV R10,R9 ; copy the last character address
MOV RBX,10 ; base10 divisor
DIV_BY_10:
XOR RDX,RDX ; zero rdx for div
DIV RBX ; rax:rdx = rax / rbx
ADD RDX,0x30 ; convert binary digit to ascii
TEST RAX,RAX ; if rax == 0 exit DIV_BY_10
JZ CHECK_BUFFER
MOV byte [R9],DL ; save remainder
SUB R9,1 ; decrement the buffer address
JMP DIV_BY_10
CHECK_BUFFER:
MOV byte [R9],DL
SUB R9,1
CMP R9,R10 ; if the buffer has data print it
JNE PRINT_BUFFER
MOV byte [R9],'0' ; place the default zero into the empty buffer
SUB R9,1
PRINT_BUFFER:
ADD R9,1 ; address of last digit saved to buffer
SUB R10,R9 ; end address minus start address
ADD R10,1 ; R10 = length of number
MOV RAX,1 ; NR_write
MOV RDI,1 ; stdout
MOV RSI,R9 ; number buffer address
MOV RDX,R10 ; string length
SYSCALL
RET
_start:
MOV RCX, SCORE ;Input into Score
MOV RDX, SCORELEN
MOV RAX, 3
MOV RBX, 0
SYSCALL
MOV RAX, [SCORE]
PUSH RAX ;Print Score
CALL PRINTDECI
POP RAX
MOV RAX,60 ;Kill the Code
MOV RDI,0
SYSCALL
SECTION .bss
SCORE: RESQ 1
SCORELEN EQU $-SCORE
Thanks for any help!
- Kyle
As a side note, the pointer in RCX goes to a insanely large number according to DDD... So I'm thinking I have to get it to pause and wait for me to type, but I have no idea how to do that...
The 'setup' to call syscall 0 (READ) on x86_64 system is:
#xenon:~$ syscalls_lookup read
read:
rax = 0 (0x0)
rdi = unsigned int fd
rsi = char *buf
rdx = size_t count
So your _start code should be something like:
_start:
mov rax, 0 ; READ
mov rdi, 0 ; stdin
mov rsi, SCORE ; buffer
mov rdx, SCORELEN ; length
syscall
The register conventions and syscall numbers for x86_64 are COMPLETELY different than those for i386.
Some conceptual issues you seem to have:
READ does not do ANY interpretation on what you type, you seem to be expecting it to let you type a number (say, 57) and have it return the value 57. Nope. It'll return '5', '7', 'ENTER', 'GARBAGE'... Your SCORELEN is probably 8 (length of resq 1), so you'll read, AT MOST, 8 bytes. or Characters, if you wish to call them that. And unless you type the EOF char (^D), you'll need to type those 8 characters before the READ call will return to your code.
You have to convert the characters you receive into a value... You can do it the easy way and link with ATOI() in the C library, or write your own parser to convert the characters into a value by addition and multiplication (it's not hard, see code below).
Used below, here as a reference:
#xenon:~$ syscalls_lookup write
write:
rax = 1 (0x1)
rdi = unsigned int fd
rsi = const char *buf
rdx = size_t count
Ugh.... So many... I'll just rewrite bits:
global _start
section .text
PRINTDECI:
; input is in RAX
lea r9, [NUMBER + NUMBERLEN - 1 ] ; + space for \n
mov r10, r9 ; save end position for later
mov [r9], '\n' ; store \n at end
dec r9
mov rbx, 10 ; base10 divisor
DIV_BY_10:
xor rdx, rdx ; zero rdx for div
div rbx : rax = rdx:rax / rbx, rdx = remainder
or dl, 0x30 ; make REMAINDER a digit
mov [r9], dl
dec r9
or rax, rax
jnz DIV_BY_10
PRINT_BUFFER:
sub r10, r9 ; get length (r10 - r9)
inc r9 ; make r9 point to initial character
mov rax, 1 ; WRITE (1)
mov rdi, 1 ; stdout
mov rsi, r9 ; first character in buffer
mov rdx, r10 ; length
syscall
ret
MAKEVALUE:
; RAX points to buffer
mov r9, rax ; save pointer
xor rcx, rcx ; zero value storage
MAKELOOP:
mov al, [r9] ; get a character
or al, al ; set flags
jz MAKEDONE ; zero byte? we're done!
and rax, 0x0f ; strip off high nybble and zero rest of RAX (we're lazy!)
add rcx, rcx ; value = value * 2
mov rdx, rcx ; save it
add rcx, rcx ; value = value * 4
add rcx, rcx ; value = value * 8
add rcx, rdx ; value = value * 8 + value * 2 (== value * 10)
add rcx, rax ; add new digit
jmp MAKELOOP ; do it again
MAKEDONE:
mov rax, rcx ; put value in RAX to return
ret
_start:
mov rax, 0 ; READ (0)
mov rdi, 0 ; stdin
mov rsi, SCORE ; buffer
mov rdx, SCORELEN ; length
syscall
; RAX contains HOW MANY CHARS we read!
; -OR-, -1 to indicate error, really
; should check for that, but that's for
; you to do later... right? (if RAX==-1,
; you'll get a segfault, just so you know!)
add rax, SCORE ; get position of last byte
movb [rax], 0 ; force a terminator at end
mov rax, SCORE ; point to beginning of buffer
call MAKEVALUE ; convert from ASCII to a value
; RAX now should have the VALUE of the string of characters
; we input above. (well, hopefully, right?)
mov [VALUE], rax ; store it, because we can!
; it's stored... pretend it's later... we need value of VALUE!
mov rax, [VALUE] ; get the VALUE
call PRINTDECI ; convert and display value
; all done!
mov rax, 60 ; EXIT (60/0x3C)
mov rdi, 0 ; exit code = 0
syscall
section .bss
SCORE: resb 11 ; 10 chars + zero terminator
SCORELEN equ $-SCORE
NUMBER: resb 19 ; 18 chars + CR terminator
NUMBERLEN equ $-NUMBER
I'm going to say that this should work first time, it's off-the-cuff for me, haven't tested it, but it should be good. We read up to 10 chars, terminate it with a zero, convert to a value, then convert to ascii and write it out.
To be more proper, you should save registers to the stack in each subroutine, well, certain ones, and really, only if you're going to interface with libraries... doing things yourself lets you have all the freedom you want to play with the registers, you just have to remember what you put where!
Yes, someone is going to say "why didn't you just multiply by 10 instead of weird adding?" ... uh... because it's easier on the registers and I don't have to set it all up in rdx:rax. Besides, it's just as readable and understandable, especially with the comments. Roll with it! This isn't a competition, it's learning!
Machine code is fun! Gotta juggle all the eggs in your head though... no help from the compiler here!
Technically, you should check return result (RAX) of the syscalls for READ and WRITE, handle errors appropriately, yadda yadda yadda.... learn to use your debugger (gdb or whatever).
Hope this helps.

Resources