Advertisement
Guest User

Untitled

a guest
Sep 21st, 2017
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ; Compilation
  2. ; nasm -f elf thisfile.asm
  3. ; ld thisfile.o
  4. ; ./a.out
  5.  
  6. section .data
  7.     buflen:     dw  8192 ; 4 byte integer with value 8192
  8.     error:      db  "Error opening the file, does the file exist?", 10 ; Error-string + \n
  9.     errorlen:   equ $-error ; Length of the error string
  10. section .bss
  11.     buf resb    8192        ; 8192 bytes of unallocated space
  12. section .text
  13.     global _start           ; Tell the linker where the program starts
  14.  
  15. _start:
  16.     pop     ebx         ; Pop first argument from stack to register ebx (argc)
  17.     pop     ebx         ; Pop second (argv[0])
  18.     pop     ebx         ; Third argument is argv[1], store to ebx
  19.  
  20.     mov     eax, 5 ; sys_open   ; Store kernel call code of open() to eax
  21.                         ; ebx has the filename (second argument)
  22.     mov     ecx, 0 ; O_RDONLY   ; Third argument is O_RDONLY, it is declared as 0
  23.     int     0x80            ; Call the kernel (open()) (stores file descriptor to eax)
  24.  
  25.     test    eax, eax        ; Test the return value
  26.     jg  print           ; If return value > 0, jump to print
  27.  
  28.     push    eax         ; If not, store the error value
  29.     mov eax, 4          ; write()
  30.     mov ebx, 1          ; stdout
  31.     mov ecx, error      ; Address of error string
  32.     mov edx, errorlen       ; Error string length
  33.     int 0x80            ; Call kernel (write())
  34.  
  35.     pop eax         ; Pop error value from stack
  36.     mov ebx, eax        ; Set error value to first argument
  37.     mov eax, 1          ; Exit()
  38.     int 0x80            ; Call kernel (exit())
  39.     ; Program end (if wrong arguments)
  40.  
  41. print:
  42.     mov ebx, eax        ; Get file descriptor from eax
  43.     mov eax, 3          ; read()
  44.                     ; ebx already has the file descriptor (first argument)
  45.     mov ecx, buf        ; Address of buffer as a second argument
  46.     mov edx, buflen     ; Buffer length. Third argument
  47.     int 0x80            ; Call kernel (read())
  48.  
  49.     mov edx, eax        ; Store eax value (read bytes) to edx
  50.     mov eax, 4          ; write() again
  51.     mov ebx, 1          ; stdout (to screen)
  52.     ; ecx is already buffer
  53.     ; edx is the read bytes (assigned at line 48)
  54.     int 0x80            ; Call kernel (write)
  55.  
  56.     mov eax, 1          ; exit()
  57.     mov ebx, 0          ; With value 0
  58.     int 0x80            ; Call kernel (exit(0))
  59.     ; Program end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement