4 Writing to a file

In a Linux system call table, system call number 4 is labeled write or sys_write. This is the system call that performs write operations. To find out how a C program uses write, one can read the man page by “man 2 write”.

The way system call number 4 works is similar to number 3, except the content pointed to by ecx is written to the specified file.

The following program is the “Hello, World!” of assembly language programs:

.text 
Hello: 
  .ascii ”Hello,_World!” # the string 
  .byte 10               # the linefeed character 
  HelloLen = . - Hello   # the number of characters in the string 
.global _start 
_start: 
  movl $4,%eax           # system call 4 
  movl $1,%ebx           # stdout 
  movl $Hello,%ecx       # where in memory to write from 
  movl $HelloLen,%edx    # the number of characters to write 
  int  $0x80             # request the OS to do it 
  movl $1,%eax           # system call 1 
  movl $0,%ebx           # exit code 0 
  int  $0x80             # request the OS to do it

The tricky part is how HelloLen is defined. Because the period symbol (.) is the next memory available for allocation, subtracting the address of the beginning of the string yields the length of the string, including the linefeed character. Note that the escape sequence “\n” does not work in assembly language programs, hence the extra .byte line.

Note that system call 4 also returns a value in eax. This return value, according to the man page of write, is the number of bytes actually written. This means that sometimes the number of characters written can be less the requested amount.