Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ; Compilation
- ; nasm -f elf thisfile.asm
- ; ld thisfile.o
- ; ./a.out
- section .data
- buflen: dw 8192 ; 4 byte integer with value 8192
- error: db "Error opening the file, does the file exist?", 10 ; Error-string + \n
- errorlen: equ $-error ; Length of the error string
- section .bss
- buf resb 8192 ; 8192 bytes of unallocated space
- section .text
- global _start ; Tell the linker where the program starts
- _start:
- pop ebx ; Pop first argument from stack to register ebx (argc)
- pop ebx ; Pop second (argv[0])
- pop ebx ; Third argument is argv[1], store to ebx
- mov eax, 5 ; sys_open ; Store kernel call code of open() to eax
- ; ebx has the filename (second argument)
- mov ecx, 0 ; O_RDONLY ; Third argument is O_RDONLY, it is declared as 0
- int 0x80 ; Call the kernel (open()) (stores file descriptor to eax)
- test eax, eax ; Test the return value
- jg print ; If return value > 0, jump to print
- push eax ; If not, store the error value
- mov eax, 4 ; write()
- mov ebx, 1 ; stdout
- mov ecx, error ; Address of error string
- mov edx, errorlen ; Error string length
- int 0x80 ; Call kernel (write())
- pop eax ; Pop error value from stack
- mov ebx, eax ; Set error value to first argument
- mov eax, 1 ; Exit()
- int 0x80 ; Call kernel (exit())
- ; Program end (if wrong arguments)
- print:
- mov ebx, eax ; Get file descriptor from eax
- mov eax, 3 ; read()
- ; ebx already has the file descriptor (first argument)
- mov ecx, buf ; Address of buffer as a second argument
- mov edx, buflen ; Buffer length. Third argument
- int 0x80 ; Call kernel (read())
- mov edx, eax ; Store eax value (read bytes) to edx
- mov eax, 4 ; write() again
- mov ebx, 1 ; stdout (to screen)
- ; ecx is already buffer
- ; edx is the read bytes (assigned at line 48)
- int 0x80 ; Call kernel (write)
- mov eax, 1 ; exit()
- mov ebx, 0 ; With value 0
- int 0x80 ; Call kernel (exit(0))
- ; Program end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement