簡體   English   中英

syscall getpid,打印返回?

[英]syscall getpid, print the return?

我嘗試將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 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 syscall的結果放入變量中? 然后影響到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
gcc -o getpid getpid.o

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM