Skip to content

Instantly share code, notes, and snippets.

@zsrkmyn
Created August 22, 2019 08:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zsrkmyn/5809574e09142c10bf9d8ff3111bc968 to your computer and use it in GitHub Desktop.
Save zsrkmyn/5809574e09142c10bf9d8ff3111bc968 to your computer and use it in GitHub Desktop.
A simple read file function for x86_64 Linux implemented in asm
#include <sys/syscall.h>
#include <stddef.h>
#include <fcntl.h>
int readfile(const char *file, char *buf, size_t size)
{
int ret;
asm (
"mov %[mode], %%rsi \n\t"
"mov %[open], %%rax \n\t"
"syscall \n\t"
"cmp $0, %%rax \n\t"
"jl 100f \n\t"
"mov %%rax, %%rdi \n\t"
"mov %[buf], %%rsi \n\t"
"mov %[size], %%rdx \n\t"
"mov %[read], %%rax \n\t"
"syscall \n\t"
"100: \n\t"
: "=a"(ret)
: [file]"D"(file), [buf]"r"(buf), [size]"r"(size), [open]"i"(__NR_open), [read]"i"(__NR_read), [mode]"i"(O_RDONLY)
: "memory"
);
return ret;
}
// test
#include <stdio.h>
int main()
{
char buf[128];
buf[0] = 0;
int ret = readfile("test_file", buf, 128);
printf("%s\n", buf);
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment