2010-07-16 20 views
1

我怎樣才能從堆棧寫入字符串(例如「Hello」)到標準輸出?沒有,數據段,也就是說。在Linux上的內聯彙編,從堆棧寫入字符串到標準輸出

void main() { 
    __asm__(
       "movl $0x4, %eax \n\t" 
       "movl $0x1, %ebx \n\t" 
      // put "Hello" on the stack and load its address into %ecx 
       "movl $0x5, %edx \n\t" 
       "int $0x80  \n\t" 

       "movl $0x1, %eax \n\t" 
       "movl $0x0, %ebx \n\t" 
       "int $0x80  \n\t" 
      ); 
} 

在此先感謝

回答

3

答1:

int main() 
{ 
    const char* string = "hello"; // string is not in a data segment, it's in the text segment 
    fputs(string, stdout); 
    return 0; 
} 

答2:

int main() 
{ 
    char[6] string = "hello"; // Space for string allocated on stack 
    fputs(string, stdout); 
    return 0; 
} 

用gcc第二應答似乎產生以下:

main:  
    leal 4(%esp), %ecx 
    andl $-16, %esp 
    pushl -4(%ecx) 
    pushl %ebp 
    movl %esp, %ebp 
    pushl %ecx 
    subl $36, %esp 
    movl $1819043176, -10(%ebp) ;<< hell 
    movw $111, -6(%ebp)   ;<< o\0 
    movl stdout, %eax 
    movl %eax, 4(%esp) 
    leal -10(%ebp), %eax 
    movl %eax, (%esp) 
    call fputs 
    movl $0, %eax 
    addl $36, %esp 
    popl %ecx 
    popl %ebp 
    leal -4(%ecx), %esp 

這清楚地僅使用堆棧。

0
int main() { 
     char *hello = "Hello world!\n"; 
     __asm__("\ 
       movl $4, %%eax\n\ 
       movl $0, %%ebx\n\ 
       push %0\n\ 
       pop %%ecx\n\ 
       movl $13,%%edx\n\ 
       int $0x80" : :"g"(hello)); 
     return 0; 
} 

我不明白堆棧的一部分。爲什麼不使用'movl%0,%% ecx'?

+0

因爲我不想將字符串存儲在其中一個數據段中,而是將它放在堆棧上。這幾乎是一個學術問題。 – guest 2010-07-16 10:24:48

0

我該如何寫一個字符串(例如「Hello」)到堆棧的標準輸出?沒有,數據段,也就是說。

東西沿着線:

  1. 在棧中分配緩衝器,說8個字節。 (請檢查GCC alloca()如何做到這一點。)
  2. 在緩衝區中創建字符串。 「Hello」按字節順序是48 65 6c 6c 6f 00 00 00(對齊,用零填充)。兩個32位常量 - 0x6c6c6548和0x0000006f - 應該足以表示字符串。
  3. 將緩衝區的地址傳遞給寫入系統調用。
  4. 將堆棧指針恢復到之前的位置(如果需要)。

不能更精確,因爲我對GCC內聯asm和x86 ABI並不是最新的。

+0

感謝您用'alloca()'提示!似乎正是我所期待的。但是,只是想知道,將字符串放入堆棧的最佳方法是什麼?目前我正在做類似'*(p + 0)='H'; *(p + 1)='e'; etc..'。 – guest 2010-07-16 10:22:35

+0

@gues:爲什麼是字節?正如我上面寫的,你可以使用32位常量和'mov'來填充緩衝區(沒有32位系統來查看正確的語法)。要生成常量,可以使用如下命令:'echo -n Hello | od -t x4'。 – Dummy00001 2010-07-16 10:49:36