2013-03-24 210 views
2

溢出,GCC:內聯彙編中的putchar(char)

如何使用內聯彙編實現putchar(char)過程?我想在x86-64程序集中做到這一點。我這樣做的原因是實現我自己的標準庫(或至少它的一部分)。這裏是我到目前爲止有:

void putchar(char c) 
{ 
    /* your code here: print character c on stdout */ 
    asm(...); 
} 

void _start() 
{ 
    /* exit system call */ 
    asm("mov $1,%rax;" 
     "xor %rbx,%rbx;" 
     "int $0x80" 
    ); 
} 

我與編譯:

gcc -nostdlib -o putchar putchar.c 

感謝您幫助我!

+2

什麼操作系統/環境?你試過什麼了?你必須比這更精確。 – Mat 2013-03-24 09:02:11

+0

感謝您的快速回復,它是x86-64上的Linux。我試圖用%eax,0x04調用中斷0x80。但我不知道如何在inline-assembly中訪問/轉發putchar(char)的函數參數。 – dubbaluga 2013-03-24 09:15:35

+0

http://stackoverflow.com/questions/7048422/printing-range-of-ascii-characters-from-registers-in-x86-assembly – Mat 2013-03-24 09:17:23

回答

4

以下是GCC x86-64內聯彙編中的示例my_putchar(在Intel語法中,轉換爲AT & T應該是微不足道的)。

與編譯:

 
gcc -ggdb -masm=intel -o gcc_asm_putchar gcc_asm_putchar.c 

編輯:rdi從破壞的寄存器失蹤。固定。

下面的代碼:

int main(void) 
{ 
    char my_char; 

    for (my_char = 'a'; my_char <= 'z'; my_char++) 
      my_putchar(my_char); 

    my_char = '\n'; 
    my_putchar(my_char); 
    return 0; 
} 

void my_putchar(char my_char) 
{ 
    int dword_char; 
    dword_char = (int)my_char; 
    asm volatile(
        ".intel_syntax noprefix;" 
        "mov r10,rsp;" // save rsp. 
        "sub rsp,8;"  // space for buffer, align by 8. 
        "mov [rsp],al;" // store the character into buffer. 
        "mov edi,1;"  // STDOUT. 
        "mov rsi,rsp;" // pointer to buffer. 
        "mov edx,1;"  // string length in bytes. 
        "mov eax,1;"  // WRITE. 
        "syscall;"  // clobbers rcx & r11. 
        "mov rsp,r10;" // restore rsp. 
        ".att_syntax prefix;" 
        /* outputs */ 
        : 
        /* inputs: eax */ 
        : "a"(dword_char) 
        /* clobbered regs */ 
        : "rcx", "rdx", "rsi", "rdi", "r10", "r11" 
       ); 
} 
+0

謝謝 - 正是我正在尋找的東西。 :-) – dubbaluga 2013-03-24 13:03:13

+0

不爲我編譯。 :(說:gcc_asm_putchar.c:36:未定義的引用'rbp' – 2017-10-10 17:14:45

1

注意getchar(3)/putchar(3)是宏(性能),它與在FILE結構複雜的數據更動爲stdin/stdout,具體處理緩衝和其它。由nrz的答案只是1文件write(3)文件描述符1,非常不同。