Skip to content

Instantly share code, notes, and snippets.

@fntlnz
Created April 23, 2024 09:21
Show Gist options
  • Save fntlnz/42ad3aa4e6d4b80a9c250f950d3ce86b to your computer and use it in GitHub Desktop.
Save fntlnz/42ad3aa4e6d4b80a9c250f950d3ce86b to your computer and use it in GitHub Desktop.
input output no libc
Compile with gcc
gcc -nostdlib main.c
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/syscall.h>
#include <sys/stat.h>
#define BUFSIZ (1 << 12)
int my_open(const char *filename, int flags, mode_t mode)
{
int ret;
asm volatile(
"syscall"
: "=a"(ret)
: "a"(SYS_open), "D"(filename), "S"(flags), "d"(mode)
: "rcx", "r11", "memory");
if (ret < 0)
{
return -1;
}
return ret;
}
ssize_t my_read(int fd, void *buf, size_t count)
{
ssize_t ret;
asm volatile(
"syscall"
: "=a"(ret)
: "a"(SYS_read), "D"(fd), "S"(buf), "d"(count)
: "rcx", "r11", "memory");
if (ret < 0)
{
return -1;
}
return ret;
}
ssize_t my_write(int fd, const void *buf, size_t count)
{
ssize_t ret;
asm volatile(
"syscall"
: "=a"(ret)
: "a"(SYS_write), "D"(fd), "S"(buf), "d"(count)
: "rcx", "r11", "memory");
if (ret < 0)
{
return -1;
}
return ret;
}
int my_close(int fd)
{
int ret;
asm volatile(
"syscall"
: "=a"(ret)
: "a"(SYS_close), "D"(fd)
: "rcx", "r11", "memory");
if (ret < 0)
{
return -1;
}
return ret;
}
int _start()
{
const char input_file[] = "/tmp/inputfile";
const char output_file[] = "/tmp/outputfile";
int fd_input, fd_output;
ssize_t bytes_read, bytes_written;
fd_input = my_open(input_file, O_RDONLY, 0);
if (fd_input == -1)
{
return 1;
}
fd_output = my_open(output_file, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR);
if (fd_output == -1)
{
my_close(fd_input);
return 1;
}
char buffer[BUFSIZ];
while ((bytes_read = my_read(fd_input, buffer, BUFSIZ)) > 0)
{
bytes_written = my_write(fd_output, buffer, bytes_read);
if (bytes_written != bytes_read)
{
my_close(fd_input);
my_close(fd_output);
return 1;
}
}
if (bytes_read == -1)
{
my_close(fd_input);
my_close(fd_output);
return 1;
}
if (my_close(fd_input) == -1)
{
return 1;
}
if (my_close(fd_output) == -1)
{
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment