Linux syscall getpid,打印返回?
我尝试将getpid syscall的结果打印到stdout 这是我的asm代码:Linux syscall getpid,打印返回?,linux,assembly,x86,Linux,Assembly,X86,我尝试将getpid syscall的结果打印到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 ea
;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
nasm -f elf getpid.asm
gcc -o getpid getpid.o
然后我使用strace检查:
~# strace ./getpid
getpid() = 17890
write(1, 0X45e2, 5) = -1 EFAULT (Bad address)
_exit(O) = ?
17890d = 45e2h
事实上,我给出的是一个值,而不是指向该值的指针。我不知道在这种情况下该怎么做:将getpid系统调用的结果放入一个变量中?然后影响这个变量到ecx的地址?我找不到(或理解)一个将十六进制转换为字符串的好代码。然而,我通过使用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; ld -o getpid getpid.o
nasm -f elf getpid.asm
gcc -o getpid getpid.o
是的,将pid放入内存(可以是堆栈)并传递该地址。请注意,它将是二进制格式,如果你想让人可读,你当然必须先将其转换为文本。谢谢Jester!你能告诉我密码吗?今天下午我开始学习ASM编程,我不知道如何传递堆栈的地址?在文本中转换?您可以找到许多转换为文本的示例,不幸的是,在汇编中确实需要一些努力。如果您对二进制结果满意,只需执行如下操作:
mov ecx,esp
而不是pop ecx
,并写入4个字节。