Inline Assembler - Example of A System Call

Example of A System Call

Calling an operating system directly is generally impossible in the presence of protected memory. The OS runs at a more privileged level (kernel mode) than the user (user mode); a (software) interrupt is used to make requests to the operating system. This is rarely a feature in a higher-level language, and so wrapper functions for system calls are written using inline assembler.

The following C code are samples including a system call wrapper in AT&T assembler syntax with the GNU Assembler. They are normally written with the aid of macros; the full code is included for clarity.

The format of basic inline assembly is very much straightforward. Its basic form is

asm("assembly code");

Example:

asm("movl %ecx, %eax"); /* moves the contents of ecx to eax */

OR

__asm__("movb %bh, (%eax)"); /* moves the byte from bh to the memory pointed by eax */

Both asm and __asm__ are valid. __asm__ can be used if the keyword asm conflicts with something in your program.

extern int errno; int funcname(int arg1, int *arg2, int arg3) { int res; __asm__ volatile( "int $0x80" /* make the request to the OS */ : "=a" (res), /* return result in eax ("a") */ "+b" (arg1), /* pass arg1 in ebx ("b") */ "+c" (arg2), /* pass arg2 in ecx ("c") */ "+d" (arg3) /* pass arg3 in edx ("d") */ : "a" (128) /* pass system call number in eax ("a") */ : "memory", "cc"); /* announce to the compiler that the memory and condition codes have been modified */ /* The operating system will return a negative value on error; * wrappers return -1 on error and set the errno global variable */ if (-125 <= res && res < 0) { errno = -res; res = -1; } return res; }

Read more about this topic:  Inline Assembler

Famous quotes containing the words system and/or call:

    In nothing was slavery so savage and relentless as in its attempted destruction of the family instincts of the Negro race in America. Individuals, not families; shelters, not homes; herding, not marriages, were the cardinal sins in that system of horrors.
    Fannie Barrier Williams (1855–1944)

    How prone we are to come to the consideration of every question with heads and hearts pre-occupied! How prone to shrink from any opinion, however reasonable, if it be opposed to any, however unreasonable, of our own! How disposed are we to judge, in anger, those who call upon us to think, and encourage us to enquire! To question our prejudices seems nothing less than sacrilege; to break the chains of our ignorance, nothing short of impiety!
    Frances Wright (1795–1852)