Created
June 18, 2022 04:15
-
-
Save shepgoba/ca73134920a31bd740491c1ae3344fdf to your computer and use it in GitHub Desktop.
Small implementation of cat on linux (with minimal assembly)
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
#define stdin 0 | |
#define stdout 1 | |
#define stderr 2 | |
#define O_READ 0 | |
#define BUF_SIZE 2097152 | |
typedef unsigned char u8; | |
typedef unsigned short u16; | |
typedef unsigned int u32; | |
typedef unsigned long long u64; | |
typedef char s8; | |
typedef short s16; | |
typedef int s32; | |
typedef long long s64; | |
struct stat { | |
u64 st_dev; | |
u64 st_ino; | |
u32 st_mode; | |
u64 st_nlink; | |
u32 st_uid; | |
u32 st_gid; | |
u64 st_rdev; | |
u64 st_size; | |
u64 st_blksize; | |
u64 st_blocks; | |
u64 st_atime; | |
u64 st_mtime; | |
u64 st_ctime; | |
}; | |
extern int sys_read(int fd, void *buf, int count); | |
extern void sys_write(int fd, const void *buf, int count); | |
extern int sys_open(const char *path, int flags, int mode); | |
extern void sys_close(int fd); | |
extern void sys_fstat(int fd, struct stat *statbuf); | |
int main(int argc, char *args) | |
{ | |
if (argc < 2) { | |
sys_write(stdout, "Usage: ./smolcat <file>\n", 24); | |
return 1; | |
} | |
char *file = args; | |
while (*file != '\0') | |
file++; | |
file++; | |
int fd = sys_open(file, O_READ, 0); | |
if (fd < 0) { | |
sys_write(stdout, "Error: could not open file\n", 27); | |
return 1; | |
} | |
struct stat data; | |
sys_fstat(fd, &data); | |
int size = data.st_size; | |
char buf[BUF_SIZE]; | |
while (size > 0) { | |
int count; | |
if (size < BUF_SIZE) | |
count = size; | |
else | |
count = BUF_SIZE; | |
sys_read(fd, buf, count); | |
sys_write(stdout, buf, count); | |
size -= count; | |
} | |
sys_close(fd); | |
return 0; | |
} |
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
global _start | |
global sys_read | |
global sys_write | |
global sys_open | |
global sys_close | |
global sys_fstat | |
global uid | |
extern main | |
section .text | |
_start: | |
mov rdi, [rsp] | |
mov rsi, [rsp + 0x8] | |
call main | |
mov edi, eax | |
exit: | |
mov eax, 60 | |
syscall | |
sys_read: | |
xor eax, eax | |
syscall | |
ret | |
sys_write: | |
xor eax, eax | |
inc eax | |
syscall | |
ret | |
sys_open: | |
mov eax, 2 | |
syscall | |
ret | |
sys_close: | |
mov eax, 3 | |
syscall | |
ret | |
sys_fstat: | |
mov eax, 5 | |
syscall | |
ret |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment