2013-11-14 26 views
3

這段代碼打印Hello屏幕上ASM的printf怪異的行爲

.data 
    hello: .string "Hello\n" 
    format: .string "%s" 
.text 
    .global _start 
    _start: 

    push $hello 
    push $format 
    call printf 

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

但如果我刪除你好字符串 '\ N',像這樣:

.data 
    hello: .string "Hello" 
    format: .string "%s" 
.text 
    .global _start 
    _start: 

    push $hello 
    push $format 
    call printf 

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

程序不能正常工作。有什麼建議麼?

+1

定義_「沒有按不工作「。 – Michael

+1

它不打印「你好」 – Dima

+0

你確定它不會被shell的提示覆蓋嗎?如果你使用一個非常長的字符串(但仍然沒有'\ n')會怎樣? – Michael

回答

6

退出系統調用(相當於C中的_exit)不刷新標準輸出緩衝區。

輸出一個換行符會導致線路緩衝流上的刷新,如果stdout指向一個終端,則該輸出會被刷新。

如果你願意在libc中調用printf,那麼以同樣的方式調用exit應該不會感覺不好。在你的程序中有一個int $0x80不會讓你成爲一個裸機。

退出前至少需要push stdout;call fflush。或push $0;call fflush。 (fflush(NULL)刷新所有的輸出流)

3

你需要清理你傳遞給printf的參數,然後刷新輸出緩衝區,因爲你沒有在字符串中的新行:

.data 
    hello: .string "Hello" 
    format: .string "%s" 
.text 
    .global _start 
    _start: 

    push $hello 
    push $format 
    call printf 
    addl $8, %esp 
    pushl stdout 
    call fflush 
    addl $4, %esp 
    movl $1, %eax #exit 
    movl $0, %ebx 
    int $0x80