Created
August 22, 2019 08:34
-
-
Save zsrkmyn/5809574e09142c10bf9d8ff3111bc968 to your computer and use it in GitHub Desktop.
A simple read file function for x86_64 Linux implemented in asm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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