Skip to content

Instantly share code, notes, and snippets.

@tai271828
Created January 29, 2020 16:48
Show Gist options
  • Save tai271828/7340e0f9daa6ae297cfdee8e462b7cd1 to your computer and use it in GitHub Desktop.
Save tai271828/7340e0f9daa6ae297cfdee8e462b7cd1 to your computer and use it in GitHub Desktop.
System calls
/*
* Description: output/input strings from stdout/stdin over Lunux system call
*
* Author: Taihsiang Ho (tai271828)
*
* Usage: gcc -g --static syscall.c
*
* Original source: shiwulo's os hw 3
*
* Also refer to the system call summary of Linux:
* http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/
*
*/
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv) {
char* str_to_output = "Hello, world!!\n";
long len_to_output = strlen(str_to_output) + 1; // long for int in 64-bit
long ret_output;
__asm__ volatile (
"mov $1, %%rax\n" // system call number, this is sys_write
"mov $2, %%rdi\n" // file descriptor number: stderr
"mov %1, %%rsi\n" //
"mov %2, %%rdx\n"
"syscall\n"
"mov %%rax, %0"
: "=m"(ret_output)
: "g" (str_to_output), "g" (len_to_output));
printf("return value: %ld\n", ret_output); // will be the number of all char output
// read 2 char from stdin
long len_from_stdin = 2;
char* str_from_stdin = malloc(sizeof(len_from_stdin));
long ret_input;
__asm__ volatile (
"mov $0, %%rax\n" // system call number, this is sys_read
"mov $0, %%rdi\n" // fd: stdin
"mov %1, %%rsi\n"
"mov %2, %%rdx\n"
"syscall\n"
"mov %%rax, %0"
: "=m"(ret_input)
: "g" (str_from_stdin), "g" (len_from_stdin));
printf("return value: %ld\n", ret_input); // will be the number of all char input
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment