Skip to content

Instantly share code, notes, and snippets.

@skeeto
Last active April 7, 2024 14:04
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 skeeto/606aa3ef258f78bb450c08977be14011 to your computer and use it in GitHub Desktop.
Save skeeto/606aa3ef258f78bb450c08977be14011 to your computer and use it in GitHub Desktop.
x86-64 Linux buffered "hello world"
// x86-64 Linux buffered "hello world"
// $ cc example.c && ./a.out
// Ref: https://old.reddit.com/r/C_Programming/comments/1bxvs3u
// Ref: https://thecoder08.github.io/hello-world.html
// Ref: https://nullprogram.com/blog/2023/02/13/
#include <stddef.h>
#include <string.h>
ptrdiff_t xwrite(int fd, void *buf, ptrdiff_t len)
{
enum { SYS_write = 1 };
asm volatile (
"syscall"
: "=a"(len)
: "a"(SYS_write), "D"(fd), "S"(buf), "d"(len)
: "rcx", "r11", "memory"
);
return len;
}
typedef struct {
char buf[1<<12];
int len;
int fd;
int err;
} xbuf;
xbuf xstdout[1] = {{.fd = 1}};
void xflush(xbuf *b)
{
if (b->err) return;
for (int off = 0; off < b->len;) {
int r = xwrite(b->fd, b->buf+off, b->len-off);
if (r < 1) {
b->err = 1;
return;
}
off += r;
}
b->len = 0;
}
void xprint(xbuf *b, char *buf, ptrdiff_t len)
{
for (ptrdiff_t off = 0; !b->err && off < len;) {
int avail = (int)sizeof(b->buf) - b->len;
int count = avail<len-off ? avail : len-off;
memcpy(b->buf+b->len, buf+off, count);
off += count;
b->len += count;
if (b->len == (int)sizeof(b->buf)) {
xflush(b);
}
}
}
void xputs(char *s)
{
xprint(xstdout, s, strlen(s));
xprint(xstdout, "\n", 1);
}
int main(void)
{
xputs("hello world");
xflush(xstdout);
return xstdout->err;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment