简体   繁体   中英

Linux x86 assembly printing problems

I wrote this to print argv[0] in x86:

.section .data
    newline: .int 0xa, 0

.section .text
    .globl _start
    _start:
        sub %al, %al
        movl 4(%esp), %edi /* Pointer to argv[0]. */
        sub %ecx, %ecx    /* Set %ecx to 0.*/
        not %ecx          /* Set %ecx to -1.*/
        repne scasb       /* Search for %al over and over.*/
        not %ecx          /* Set %ecx to |%ecx| - 1.*/
        dec %ecx
        movl %ecx, %edx   /* Move the strlen of argv[0] into %edx.*/

        movl $4, %eax
        movl $1, %ebx
        movl 4(%esp), %ecx
        int $0x80

        movl $newline, %ecx
        movl $1, %edx
        int $0x80

        movl $1, %eax
        movl $0, %ebx
        int $0x80

When I run this file ("print"), the output is this:

[08:27 assembly]$ ./print test
./print[08:30 assembly]$ 

When I ran this through gdb, the actual string length held in edx is 27, and the string it's checking is "/home/robert/assembly/print", not "./print". So I changed the %esp offsets to 8, to check argv[1] . With the same command as before, the output is this:

test
[08:33 assembly]$

Why does checking argv[0] cause the strange output, when argv[1] does as expected?

I think gdb is "helping" you by adding the full path to argv[0] . After printing, %eax holds the number of characters printed, so you'll want to reload %eax for sys_write again to print the $newline ( %ebx should still be okay) - by luck, "test" is the right length. Lord knows what system call you're getting with that longer string!

I'd say you're doing good! (might be a good idea to check argc to make sure argv[1] is there before you try to print it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM