My program calls function 183 (getcwd) of interrupt 80h which copies an absolute pathname of the current working directory to the memory location pointed to by buff, which is of length 4096. Returned absolute pathname length is usually less than 4096 bytes so i want to get its true length. How can i do that?
%define LF 0Ah ; Line feed ASCII code.
%define STDOUT_FILENO 1 ; Standard output stream.
%define SYS_exit 1
%define SYS_write 4
%define SYS_getcwd 183
SECTION .bss
buff resb 4096
SECTION .text
global _start
_start:
mov eax, SYS_getcwd ; getcwd
mov ebx, buff
mov ecx, 4096
int 80h
mov eax, SYS_write ; print result to stdout
mov ebx, STDOUT_FILENO
mov ecx, buff
mov edx, 4096
int 80h
mov eax, SYS_exit ; exit
mov ebx, 0
int 80h
I add code to find length of null terminated string to my program as following and it works:
%define LF 0Ah ; Line feed ASCII code.
%define STDOUT_FILENO 1 ; Standard output stream.
%define SYS_exit 1
%define SYS_write 4
%define SYS_getcwd 183
SECTION .data
mesg1 db "Can't not find string length.",LF
mesg1_l db $-mesg1
SECTION .bss
buff resb 4096
SECTION .text
global _start
_start:
mov eax, SYS_getcwd ; getcwd
mov ebx, buff
mov ecx, 4096
int 80h
mov al, 0 ; find string length with scasb
mov edi, buff
cld
repne scasb
jne error1
sub ecx, 4096
neg ecx
mov edx,ecx
print: mov byte [buff + ecx],LF
mov byte [buff + ecx + 1], 0
inc edx
mov eax, SYS_write ; print result to stdout
mov ebx, STDOUT_FILENO
mov ecx, buff
int 80h
jmp exit
error1: mov eax, SYS_write
mov ebx, STDOUT_FILENO
mov ecx, error1
mov edx, mesg1_l
int 80h
exit: mov eax, SYS_exit ; exit
mov ebx, 0
int 80h
Q: How do I find the length of a string (e.g. the string returned by “getcwd()”)?
A: The same way the standard library function “strlen()” would do it: parse the string until you find a ‘\0’ delimiter, then return that position as the string length.
PS:
I’d strongly urge you to consider using Gnu Assembler “gas” instead of “nasm”. As soon as you start playing with assemblers other than x86, the “bass-ackwards” Intel syntax gets really annoying.
IMHO …