w1coding.comAll tutorials

Assembly Call

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Interrupts and System Calls in Assembly

Interrupts and system calls allow programs to interact with the operating system or hardware. In assembly, you can invoke these by using the int instruction for software interrupts or using dedicated system call mechanisms.

1. What Are Interrupts?

An interrupt is a mechanism that allows a process or program to temporarily halt execution and pass control to a special function called an interrupt handler. Interrupts can be triggered by hardware or software.

There are two types of interrupts:

  • Hardware Interrupts: Triggered by hardware devices (e.g., keyboard input, timer). The CPU halts its current task and switches to handle the interrupt.
  • Software Interrupts: Triggered by software to request services from the OS, like performing I/O or memory allocation.

2. Using the int Instruction

To invoke a software interrupt, the int instruction is used:

int 0x80            ; Trigger interrupt 0x80, used for system calls
    

3. System Calls in Linux Assembly

System calls in Linux are invoked via interrupt 0x80. Each system call is identified by a number, and parameters are passed through registers:

  • eax: System call number.
  • ebx, ecx, edx: Arguments to the system call.
  • eax: Return value from the system call.

Example: Writing to standard output using the write system call (syscall number 4):

mov eax, 4          ; sys_write
mov ebx, 1          ; file descriptor (stdout)
mov ecx, msg        ; message to print
mov edx, msg_len    ; message length
int 0x80            ; make the system call

section .data
msg db 'Hello, world!', 0xA
msg_len equ $ - msg
    

4. Handling Interrupts

Interrupt handling is done by setting up an interrupt descriptor table (IDT) and linking interrupt numbers to handler functions. This process is often done at the kernel level and not within user-space programs.

5. Key System Calls

Some common system calls include:

  • sys_exit (1): Exits the program.
  • sys_fork (2): Creates a new process.
  • sys_read (3): Reads data from a file or device.
  • sys_write (4): Writes data to a file or device.

Key Notes

  • Interrupts provide a mechanism for responding to events, like hardware signals or system calls.
  • System calls are the primary way programs interact with the operating system for tasks like input/output, process management, and memory allocation.