How to compile this program with inline asm?

I can not compile this program, taken from a textbook. He should print "Hello World."

void main() { __asm__("jmp forward\n\t" "backward:\n\t" "popl %esi\n\t" "movl $4, %eax\n\t" "movl $2, %ebx\n\t" "movl %esi, %ecx\n\t" "movl $12, %edx\n\t" "int $0x80\n\t" "int3\n\t" "forward:\n\t" "call backward\n\t" ".string \"Hello World\\n\"" ); } 

gcc 4.7 under Linux gives me the following error:

 gcc hello.c -o hello hello.c: Assembler messages: hello.c:5: Error: invalid instruction suffix for `pop' 

Is there a way to avoid specifying double quotes for each line?

Also, I would like to know how to change the program to use libc call printf instead of the kernel service.

+6
source share
1 answer

Q :

 hello.c: Assembler messages: hello.c:5: Error: invalid instruction suffix for `pop' 

A : popl is available on x86-32, but not on x86-64 (instead it has popq ). You either need to adapt your build code to work on x86-64, or you need to call GCC to generate x86-32 binary output.

Assuming you want to generate x86-32, use the -m32 command line -m32 .

Q :

Is there a way to avoid specifying double quotes for each line?

A : No. This is because __asm__() is a pseudo-function that takes string arguments, so the string follows the C syntax. The contents of the string are passed to the assembler with little or no processing.

Note that in C, when strings are matched, they are concatenated. For example, "a" "b" matches "ab" .

Note that in assembly language (GAS) syntax, you can separate statements using a newline or semicolon, for example: "movl xxx; call yyy" or "movl xxx \n call yyy" .

Q :

how to change the program to use the libc printf call

A. Follow the calling convention for C on x86 . Press the arguments from right to left, call the function, then clear the stack. Example:

 pushl $5678 /* Second number */ pushl $1234 /* First number */ pushl $fmtstr call printf addl $12, %esp /* Pop 3 arguments of 4 bytes each */ /* Put this away from the code */ fmtstr: .string "Hello %d %d\n" /* The \n needs to be double-backslashed in C */ 
+9
source

Source: https://habr.com/ru/post/951442/


All Articles