Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active December 24, 2023 02:05
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 louisswarren/e0f38344fd1bbe84342d6b8e18639361 to your computer and use it in GitHub Desktop.
Save louisswarren/e0f38344fd1bbe84342d6b8e18639361 to your computer and use it in GitHub Desktop.
Fullwidth text conversion without libc
#include <sys/syscall.h>
#define EOF (-1)
static unsigned char buf[3 * 8192];
long
read(void)
{
long ret;
__asm__ volatile (
"syscall"
: "=a"(ret)
: "a"(SYS_read), "D"(0), "S"(buf), "d"(1)
: "rcx", "r11", "memory"
);
return ret;
}
long
write(long len)
{
long ret;
__asm__ volatile (
"syscall"
: "=a"(ret)
: "a"(SYS_write), "D"(1), "S"(buf), "d"(len)
: "rcx", "r11", "memory"
);
return ret;
}
void
fullwidth(long len)
{
unsigned char *x = buf + len;
unsigned char *y = buf + sizeof(buf);
do {
--x;
unsigned char d = *x & 0x1f;
if ((*x | 0x20) > 0x60 && d < 26) {
*(--y) = 0xa0 + d;
*(--y) = 0xbc;
*(--y) = 0xef;
} else {
*(--y) = *x;
}
} while (buf < x);
long written = 0;
do {
long writelen = sizeof(buf) - (y - buf);
__asm__ volatile (
"syscall"
: "=a"(written)
: "a"(SYS_write), "D"(1), "S"(y), "d"(writelen)
: "rcx", "r11", "memory"
);
y += written;
} while (written == -1);
}
void
_start(void)
{
long len;
while ((len = read())) {
if (len == -1)
continue;
fullwidth(len);
}
/* Exit */
__asm__ volatile (
"syscall"
:
: "a"(SYS_exit), "D"(0)
);
__builtin_unreachable();
}
CFLAGS = -ffreestanding -fno-stack-protector
LDFLAGS = -nostdlib -static
fullwidth-freestanding: fullwidth-freestanding.o
fullwidth-freestanding.o: fullwidth-freestanding.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment