我尝试将getpid系统调用的结果打印到stdout。
这是我的asm代码:
;getpid.asm
[SECTION .txt]
global _start
_start:
xor eax, eax ; clean eax
mov al, 20 ; syscall getpid
int 0x80 ; execute
push eax ; put the return of getpid on the stack
xor eax, eax ; clean
xor ebx,ebx ; clean
xor ecx, ecx ; clean
xor edx, edx ; clean
mov al, 4 ; syscall for write
mov bl, 1 ; stdout 1 in ebx
pop ecx ; put the value returned by getpid in ecx
mov dl, 5 ; len of return value
int 0x80 ; execute
xor eax, eax ; clean eax
xor ebx, ebx ; for exit (0)
mov al, 1 ; syscall for exit
int 0x80 ; execute
我编译:
nasm -f elf getpid.asm; ld -o getpid getpid.o
然后我用strace检查:
~# strace ./getpid
getpid() = 17890
write(1, 0X45e2, 5) = -1 EFAULT (Bad address)
_exit(O) = ?
17890d = 45e2h
实际上,我给出一个值而不是指向该值的指针。我不知道在这种情况下该怎么做:将getpid系统调用的结果放在变量中?然后影响这个变量的地址到ecx?
答案 0 :(得分:1)
我无法找到(或理解)将十六进制转换为字符串的好代码。但是,我通过使用C函数printf
找到了解决方案;getpid.asm
extern printf
SECTION .data
msg: db "PID= %d",10,0 ; 10 for \n, 0 and of the string, require for printf
SECTION .text
global main
main:
push ebp ; save ebp
mov ebp, esp ; put the old top of the stack to the bottom
sub esp, 100 ; increase the stack of 100 byte
xor eax, eax ; set eax to 0
mov al, 20 ; syscall getpid
int 0x80 ; execute
push eax ; put the return of the getpid on the stack
push dword msg ; put the string on the stack
call printf
add esp, 8 ; decrease esp of 8, 2 push
leave ; destroy the stack
xor eax, eax ;
xor ebx, ebx ; for exit (0)
mov al, 1 ; syscall for exit
int 0x80 ; execute
编译:
nasm -f elf getpid.asm
gcc -o getpid getpid.o