2014-03-25 61 views
1

我想學習Linux上的彙編編程,所以我GOOGLE /創建了一個非常簡單的「貓」實現,但我的小程序不能用命令行參數(它說「 Colud't打開文件「)。當我取消註釋「fname」行時,它可以工作,所以文件I/O很好。所以我覺得堆疊部分破裂:/這是我的代碼:Linux AT&T的命令行參數

as pfile.S -o pfile.o 
    ld pfile.o -o pfile 

我的Linux發行版是:

Debian 3.2.41-2+deb7u2 

AS

.code32 

    .section .data 
msg_err_open: 
    .asciz "Colud't open the file.\n" 
msg_err_open_len: 
    .long . - msg_err_open 
fname: 
    .asciz "test.txt" 

.section .bss 
    .equ BUFSIZE, 1024 
    .lcomm buf, BUFSIZE 

.section .text 
    .globl _start 
    .align 4 

_start: 

# popl %ebx # argc 
# popl %ebx # argv[0] 
# popl %ebx # argv[1] (file) 

    # open 
    movl $5, %eax  # open(
# movl 8(%esp), %ebx # filename, ???????????????? 
    movl $fname, %ebx 
    movl $0, %ecx  # readonly 
    int $0x80  #) 

    test %eax, %eax  # megnyitás sikerült? 
    js err_open  # ha negatív 

    # read   
    movl %eax, %ebx  # file descriptor eax->ebx 
    movl $3, %eax  # read(fd (ebx), 
    movl $buf, %ecx  # buffer, 
    movl $BUFSIZE, %edx # size 
    int $0x80  #) 

    # close   
    movl $6, %eax  # close(fd (ebx) 
    int $0x80  #) 

    # write   
    movl $4, %eax  # write(
    movl $1, %ebx  # STDOUT, 
    movl $buf, %ecx  # buffer 
    int $0x80  #) 

    # exit 

    movl $1, %eax  # exit(
    movl $0, %ebx  # 0 
    int $0x80  #) 

err_open: 
    # write (msg_err_open)  
    movl $4, %eax 
    movl $1, %ebx 
    movl $msg_err_open, %ecx 
    movl $msg_err_open_len, %edx  # length 
    int $0x80 

    # exit(1) 
    movl $1, %eax 
    movl $1, %ebx 
    int $0x80 

我COMPLE這種方式/掛靠版本:

2.22 (x86_64-linux-gnu) 

我認爲解決方案是微不足道的,但我沒看到它。我希望它在32位模式下運行,現在x64對我來說非常困難。感謝您的時間!

+0

把你註釋掉的'movl 8(%esp),%ebx'放回來似乎在這裏工作得很好。 PS:在繼續學習使用調試器之前,它會有很大的幫助。 – Jester

+0

我評論說,因爲它不適合我,我知道,谷歌是我的朋友,但我發現「movl 8(%esp),%ebx」必須工作,但事實並非如此。我使用gdb,但我無法弄清楚:/ – g0mb4

回答

2

哦,我看到了問題。很高興你已經包括了你如何構建這個程序(+1)。 如果使用file命令檢查所生成的可執行文件,我敢打賭,它說64位:

$ file pfile 
pfile: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), statically linked, not stripped 

爲了讓你應該使用一個32位的程序:你可以做

$ as --32 pfile.S -o pfile.o 
$ ld -melf_i386 pfile.o -o pfile 
$ file pfile 
pfile: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, not stripped 
$ ./pfile pfile.S 
    .code32 

    .section .data 
... 

或者gcc -m32 -nostdlib pfile.S -o pfile

+0

它解決了它!謝謝! – g0mb4