🤙Linux System Call
Như các bài trước các bạn đã thấy một vài instruction có cú pháp là: int 0x80
. Thì đó bạn có thể hiểu là 1 system call. Đối với từng cấu trúc x86_32 với x86_64 thì sẽ có các system call và giá trị khác nhau. Ví dụ ở 32 bits thì syswrite = 0x4, nhưng ở 64 bits, syswrite = 0x1. Vậy nên bạn cần chú ý về vấn đề này trước khi bắt tay vào thực hiện.
Ở đây tôi sẽ lấy 1 vài ví dụ cơ bản của system call như:
SysWrite:
mov edx,4 ; message length
mov ecx,msg ; message to write
mov ebx,1 ; file descriptor (stdout)
mov eax,4 ; system call number (sys_write)
int 0x80 ; call kernel
SysRead:
mov edx,4 ; message to read length
mov ecx,buffer ; where to read
mov ebx,0 ; file descriptor (stdin)
mov eax,3 ; system call number (sys_read)
int 0x80 ; call kernel
SysExit:
mov eax,1 ; system call number (sys_exit)as
int 0x80 ; call kernel
Để hiểu tường tận hơn về 1 chương trình hoàn chỉnh sử dụng các loại syscall thì tôi có chương trình sau đây:
section .data
userMsg db 'Please enter a number: ' ;Ask the user to enter a number
lenUserMsg equ $-userMsg ;The length of the message
dispMsg db 'You have entered: '
lenDispMsg equ $-dispMsg
section .bss ;Uninitialized data
num resb 5 ; num has 5 bytes
section .text ;Code Segment
global _start
_start: ;User prompt
mov eax, 4
mov ebx, 1
mov ecx, userMsg
mov edx, lenUserMsg
int 80h
;Read and store the user input
mov eax, 3
mov ebx, 2
mov ecx, num
mov edx, 5 ;5 bytes (numeric + "\n") -> numeric has 4 bytes
int 80h ;SYS_READ
;Output the message 'The entered number is: '
mov eax, 4
mov ebx, 1
mov ecx, dispMsg
mov edx, lenDispMsg
int 80h ;SYS_WRITE
;Output the number entered
mov eax, 4
mov ebx, 1
mov ecx, num
mov edx, 5
int 80h ; SYS_WRITE
; Exit code
mov eax, 1
mov ebx, 0
int 80h
*resb: là câu lệnh giúp máy có thể biết được cần dành bao nhiêu byte cho biến được khởi tạo.
Và đầu ra của chương trình trên sẽ là:

Vậy là cơ bản là bài hôm nay dừng tạm ở đây. Nếu khó hiểu quá thì làm thêm bài tập bên dưới này để hiểu rõ hơn nha hoặc đọc lại blog 1 lần nữa xem sao 😁
Nhập tên của bạn và chương trình sẽ trả lại Hello <name> như ảnh minh họa dưới đây:

Bạn nên tự mình giải quyết nó trước khi xem code mẫu của tôi.
section .data
name_req db "Nhập Họ và Tên: "
name_len equ $-name_req
hello db "Xin chào, "
hello_len equ $-hello
section .bss
name resb 30
section .text
global _start
_start:
mov eax, 0x4
mov ebx, 0x1
mov ecx, name_req
mov edx, name_len
int 0x80
mov eax, 0x3
mov ebx, 0x0
mov ecx, name
mov edx, 30
int 0x80
mov eax, 0x4
mov ebx, 0x1
mov ecx, hello
mov edx, hello_len
int 0x80
mov eax, 0x4
mov ebx, 0x1
mov ecx, name
mov edx, 30
int 0x80
mov eax, 1
mov ebx, 0
int 80h
Last updated