Assembly (Intel's) code (32bit) doesn't behave as expected, reading command line arguments and using C code

67 Views Asked by At

I try to first see If I can recognize all the arguments that have -i and -o prefixes and merely print '-i' or '-o' to stdout when I recognize one. For the input: ./encoder -i -iewqfra -ods asr I would want the following code to print:

-i
-i
-o

this way, it will give me the indication that i successfuly managed to read the arguments properly. What I get is a segmentation fault without any print.

I have this function written in C which is linked with the assembly:

/*
The strncmp() function is similar to strcmp, 
except it only compares the first (at most) n characters of s1 and s2.
*/
int strncmp(const char* str1, const char* str2, unsigned int n)
{
    while(n--)
    {
        if(*str1++!=*str2++)
        {
            return *(unsigned char*)(str1 - 1) - *(unsigned char*)(str2 - 1);
        }
    }
    return 0;
}

And then in a different file comes the assembly code:

linefeed:dd 10
input_syntax : dd "-i"
output_syntax: dd "-o"

extern strncmp
global _start
global Infile: db 0
global Outfile: db 1

_start:
    pop    dword ecx    ; ecx = argc
    push dword ecx
    mov    esi,esp      ; esi = argv

 
    jmp load_in_out
    cont1:

    mov eax, 1
    mov ebx , 0
    int 0x80 ; sys_call exit

load_in_out:
   
    pop dword eax ; argc
   
    loop2:
        cmp dword eax ,0
        jz end
       
        sub dword eax, 1
        pop dword ebx ; char * arg1
        push dword eax; push argc
        push dword ebx;
        mov dword eax, input_syntax
        mov dword ecx, 2

        push dword ecx
        push dword ebx
        push dword eax
        call strncmp
        cmp dword eax, 0
        je success_input_syntax
        return_from_success_input_syntax:
       
        pop dword ebx
        mov dword eax, output_syntax
        mov dword ecx, 2
       
        push dword ecx
        push dword ebx
        push dword eax
        call strncmp
        cmp dword eax, 0
        je success_output_syntax
        return_from_success_output_syntax:

        pop dword eax;
        jmp loop2
       
   
       
    success_input_syntax:
        mov dword eax, input_syntax
        mov ebx, 2
        call print_word
        jmp return_from_success_input_syntax
    success_output_syntax:
        mov dword eax, output_syntax
        mov dword ebx, 2
        call print_word
        jmp return_from_success_output_syntax

    try:
         mov dword eax, example
         mov dword ebx, 2
         call print_word
         ret
    end:
        jmp cont1

print_word: ;eax = char * word , ebx =length
   
    mov dword ecx, eax ; ecx = word
    mov dword edx ,ebx; edx = length
    mov dword eax, 4
    mov dword ebx, 1
    int 0x80

    mov dword eax, 4
    mov dword ebx, 1
    mov dword ecx, linefeed
    mov dword edx, 1
    int 0x80

    ret
0

There are 0 best solutions below