diff --git a/drivers/console.cc b/drivers/console.cc
index 063df31398d149946974db3778a6d64fae09ec7b..d3238b7390efc48f03d64c49078e6cd156eaf014 100755
--- a/drivers/console.cc
+++ b/drivers/console.cc
@@ -24,14 +24,20 @@ void write(const char *msg, size_t len, bool lf)
 static int
 console_write(struct device *dev, struct uio *uio, int ioflag)
 {
-    if (uio->uio_iovcnt != 1)
-        return EINVAL;
-    const void *buf = uio->uio_iov->iov_base;
-    size_t count = uio->uio_iov->iov_len;
-    console::write(reinterpret_cast<const char *>(buf), count, false);
-
-    uio->uio_resid -= count;
-    uio->uio_offset += count;
+    while (uio->uio_resid > 0) {
+        struct iovec *iov = uio->uio_iov;
+
+	if (iov->iov_len) {
+            console::write(reinterpret_cast<const char *>(iov->iov_base),
+                           iov->iov_len, false);
+        }
+
+        uio->uio_iov++;
+        uio->uio_iovcnt--;
+        uio->uio_resid -= iov->iov_len;
+        uio->uio_offset += iov->iov_len;
+    }
+
     return 0;
 }
 
diff --git a/drivers/driver-factory.cc b/drivers/driver-factory.cc
index 1577247512eb00371ba16fb21fa67c0567b4e95b..eacf14ffb5b93210d9ff7a27456b75ce7682ecf0 100644
--- a/drivers/driver-factory.cc
+++ b/drivers/driver-factory.cc
@@ -40,6 +40,9 @@ DriverFactory::DumpDrivers() {
 
 void
 DriverFactory::Destroy() {
-    for (auto ii = _drivers.begin() ; ii != _drivers.end() ; ii++ )
-        delete *ii;
+    for (auto ii = _drivers.begin() ; ii != _drivers.end() ; ii++ ) {
+        Driver* del_me = *ii;
+        ii = _drivers.erase(ii);
+        delete del_me;
+    }
 }
diff --git a/drivers/driver.cc b/drivers/driver.cc
index 43daec46af3ccbcd606eb107b96aca9e0fffcd43..5ef9b5b604c704e82fcf374e6c785aa4ef368a99 100644
--- a/drivers/driver.cc
+++ b/drivers/driver.cc
@@ -34,6 +34,11 @@ bool Driver::isPresent() {
     return _present;
 }
 
+Driver::~Driver() {
+    //todo - Better change the Bar allocation to live in the stack
+    for (int i=0;i<6;i++) if (_bars[i]) delete _bars[i];
+}
+
 void
 Driver::setPresent(u8 bus, u8 slot, u8 func) {
     _present = true;
diff --git a/drivers/driver.hh b/drivers/driver.hh
index 4013136373949be6f2af15983726858244f90e0f..fd0dde49ac0b2517c64c779085f21398e5faae79 100644
--- a/drivers/driver.hh
+++ b/drivers/driver.hh
@@ -40,7 +40,7 @@ class Driver {
 public:
     Driver(u16 vid, u16 id) :_id(id), _vid(vid), _present(false), _bus(0), _slot(0), _func(0)\
            {for (int i=0;i<6;i++) _bars[i] = nullptr;};
-    virtual ~Driver() {for (int i=0;i<6;i++) if (_bars[i]) delete _bars[i];}
+    virtual ~Driver();
 
     bool isPresent();
     void setPresent(u8 bus, u8 slot, u8 func);
diff --git a/drivers/virtio-net.cc b/drivers/virtio-net.cc
index d47c9808a79cb82618b965c394ce7264f116156a..a3b3f3d99e2e97b054a715466c94271962920ece 100644
--- a/drivers/virtio-net.cc
+++ b/drivers/virtio-net.cc
@@ -15,7 +15,6 @@ namespace virtio {
 
     virtio_net::~virtio_net()
     {
-        set_dev_status(0);
     }
 
     bool virtio_net::Init(Device *d)
diff --git a/drivers/virtio.cc b/drivers/virtio.cc
index 28289bd6febe8b91a5ff1d93b135badbf57e0b49..634730f114264fe8bc4883b330ce803943706b2d 100644
--- a/drivers/virtio.cc
+++ b/drivers/virtio.cc
@@ -22,7 +22,6 @@ namespace virtio {
     virtio_driver::~virtio_driver()
     {
         reset_host_side();
-
         for (int i=0; i < max_virtqueues_nr; i++) {
             if (NULL != _queues[i]) {
                 delete (_queues[i]);
@@ -31,6 +30,8 @@ namespace virtio {
     }
 
     void virtio_driver::reset_host_side() {
+        if (!isPresent()) return;
+
         set_dev_status(0);
         pci_conf_write(VIRTIO_PCI_QUEUE_PFN,(u32)0);
     }
diff --git a/fs/vfs/main.c b/fs/vfs/main.c
index 774c182a09a439aa82fda37b74f20fd4c2201421..a9897cba66ca0f753d73d3e9880c28abaa619533 100755
--- a/fs/vfs/main.c
+++ b/fs/vfs/main.c
@@ -284,19 +284,24 @@ ssize_t writev(int fd, const struct iovec *iov, int iovcnt)
 	return pwritev(fd, iov, iovcnt, -1);
 }
 
-#if 0
-static int
-fs_ioctl(struct task *t, struct ioctl_msg *msg)
+int ioctl(int fd, int request, unsigned long arg)
 {
 	struct task *t = main_task;
 	file_t fp;
+	int error;
 
-	if ((fp = task_getfp(t, msg->fd)) == NULL)
-		return EBADF;
+	error = EBADF;
+	if ((fp = task_getfp(t, fd)) == NULL)
+		goto out_errno;
 
-	return sys_ioctl(fp, msg->request, msg->buf);
+	error = sys_ioctl(fp, request, (void *)arg);
+	if (error)
+		goto out_errno;
+	return 0;
+out_errno:
+	errno = error;
+	return -1;
 }
-#endif
 
 int fsync(int fd)
 {
diff --git a/libc/build.mak b/libc/build.mak
index b62fce5ad3e6dead2faaaad926dac578d8986e8e..9277a1a87c7bf1ee8eb317ec945522438aa38dff 100644
--- a/libc/build.mak
+++ b/libc/build.mak
@@ -1,5 +1,11 @@
 libc :=
 
+#libc += internal/floatscan.o
+libc += internal/intscan.o
+libc += internal/libc.o
+libc += internal/__lock.o
+libc += internal/shgetc.o
+
 libc += ctype/__ctype_b_loc.o
 libc += ctype/__ctype_get_mb_cur_max.o
 libc += ctype/__ctype_tolower_loc.o
@@ -129,6 +135,118 @@ libc += multibyte/wcstombs.o
 libc += multibyte/wctob.o
 libc += multibyte/wctomb.o
 
+libc += stdio/__fclose_ca.o
+libc += stdio/__fdopen.o
+libc += stdio/__fmodeflags.o
+libc += stdio/__fopen_rb_ca.o
+libc += stdio/__lockfile.o
+libc += stdio/__overflow.o
+libc += stdio/__stdio_close.o
+libc += stdio/__stdio_exit.o
+libc += stdio/__stdio_read.o
+libc += stdio/__stdio_seek.o
+libc += stdio/__stdio_write.o
+libc += stdio/__stdout_write.o
+libc += stdio/__string_read.o
+libc += stdio/__toread.o
+libc += stdio/__towrite.o
+libc += stdio/__uflow.o
+libc += stdio/asprintf.o
+libc += stdio/clearerr.o
+libc += stdio/dprintf.o
+libc += stdio/ext.o
+libc += stdio/ext2.o
+libc += stdio/fclose.o
+libc += stdio/feof.o
+libc += stdio/ferror.o
+libc += stdio/fflush.o
+libc += stdio/fgetc.o
+libc += stdio/fgetln.o
+libc += stdio/fgetpos.o
+libc += stdio/fgets.o
+libc += stdio/fgetwc.o
+libc += stdio/fgetws.o
+libc += stdio/fileno.o
+#libc += stdio/flockfile.o
+libc += stdio/fmemopen.o
+libc += stdio/fopen.o
+libc += stdio/fprintf.o
+libc += stdio/fputc.o
+libc += stdio/fputs.o
+libc += stdio/fputwc.o
+libc += stdio/fputws.o
+libc += stdio/fread.o
+libc += stdio/freopen.o
+libc += stdio/fscanf.o
+libc += stdio/fseek.o
+libc += stdio/fsetpos.o
+libc += stdio/ftell.o
+#libc += stdio/ftrylockfile.o
+#libc += stdio/funlockfile.o
+libc += stdio/fwide.o
+libc += stdio/fwprintf.o
+libc += stdio/fwrite.o
+libc += stdio/fwscanf.o
+libc += stdio/getc.o
+libc += stdio/getc_unlocked.o
+libc += stdio/getchar.o
+libc += stdio/getchar_unlocked.o
+libc += stdio/getdelim.o
+libc += stdio/getline.o
+libc += stdio/gets.o
+libc += stdio/getw.o
+libc += stdio/getwc.o
+libc += stdio/getwchar.o
+libc += stdio/open_memstream.o
+libc += stdio/open_wmemstream.o
+libc += stdio/perror.o
+libc += stdio/printf.o
+libc += stdio/putc.o
+libc += stdio/putc_unlocked.o
+libc += stdio/putchar.o
+libc += stdio/putchar_unlocked.o
+libc += stdio/puts.o
+libc += stdio/putw.o
+libc += stdio/putwc.o
+libc += stdio/putwchar.o
+libc += stdio/remove.o
+libc += stdio/rewind.o
+libc += stdio/scanf.o
+libc += stdio/setbuf.o
+libc += stdio/setbuffer.o
+libc += stdio/setlinebuf.o
+libc += stdio/setvbuf.o
+libc += stdio/snprintf.o
+libc += stdio/sprintf.o
+libc += stdio/sscanf.o
+libc += stdio/stderr.o
+libc += stdio/stdin.o
+libc += stdio/stdout.o
+libc += stdio/swprintf.o
+libc += stdio/swscanf.o
+libc += stdio/tempnam.o
+libc += stdio/tmpfile.o
+libc += stdio/tmpnam.o
+libc += stdio/ungetc.o
+libc += stdio/ungetwc.o
+libc += stdio/vasprintf.o
+libc += stdio/vdprintf.o
+libc += stdio/vfprintf.o
+libc += stdio/vfscanf.o
+libc += stdio/vfwprintf.o
+libc += stdio/vfwscanf.o
+libc += stdio/vprintf.o
+libc += stdio/vscanf.o
+libc += stdio/vsnprintf.o
+libc += stdio/vsprintf.o
+libc += stdio/vsscanf.o
+libc += stdio/vswprintf.o
+libc += stdio/vswscanf.o
+libc += stdio/vwprintf.o
+libc += stdio/vwscanf.o
+libc += stdio/wprintf.o
+libc += stdio/wscanf.o
+
 libc += string/bcmp.o
 libc += string/bcopy.o
 libc += string/bzero.o
@@ -227,10 +345,8 @@ libc += time/timegm.o
 libc += time/tzset.o
 libc += time/wcsftime.o
 
-libc += printf.o
 libc += pthread.o
 libc += dir.o
-libc += file.o
 libc += libc.o
 libc += dlfcn.o
 libc += time.o
diff --git a/libc/file.cc b/libc/file.cc
deleted file mode 100644
index 7fd4b2e93ddccf034890be14fb14ede175678e2a..0000000000000000000000000000000000000000
--- a/libc/file.cc
+++ /dev/null
@@ -1,80 +0,0 @@
-#include <stdio.h>
-#include <fcntl.h>
-#include <string.h>
-#include <algorithm>
-#include <dirent.h>
-#include "libc.hh"
-#include "fs/fs.hh"
-
-class std_file : public _IO_FILE {
-public:
-    explicit std_file(int fd);
-    ~std_file();
-};
-
-std_file* from_libc(FILE* file)
-{
-    return static_cast<std_file*>(file);
-}
-
-std_file::std_file(int fd)
-{
-    _fileno = fd;
-}
-
-std_file::~std_file()
-{
-    ::close(_fileno);
-}
-
-FILE* fopen(const char* fname, const char* fmode)
-{
-    static struct conv {
-        const char* fmode;
-        int mode;
-    } modes[] = {
-        { "r", O_RDONLY },
-        { "r+", O_RDWR },
-        { "w", O_WRONLY | O_CREAT | O_TRUNC },
-        { "w+", O_RDWR | O_CREAT | O_TRUNC },
-        { "a", O_WRONLY | O_APPEND | O_CREAT | O_TRUNC },
-        { "a+", O_RDWR | O_APPEND | O_CREAT | O_TRUNC },
-    };
-    auto p = std::find_if(modes, modes + 6,
-                 [=](conv c) { return strcmp(fmode, c.fmode) == 0; } );
-    if (p == modes + 6) {
-        return nullptr;
-    }
-    auto fd = ::open(fname, p->mode);
-    if (fd == -1) {
-        return nullptr;
-    }
-    return new std_file(fd);
-}
-
-char *fgets(char *s, int size, FILE *stream)
-{
-    char* orig = s;
-    while (size > 1) {
-        int r = ::read(stream->_fileno, s, 1);
-        assert(r != -1);
-        if (r == 0) {
-            break;
-        }
-        ++s;
-        --size;
-        if (s[-1] == '\n') {
-            break;
-        }
-    }
-    if (size) {
-        *s = '\0';
-    }
-    return s == orig ? nullptr : orig;
-}
-
-int fclose(FILE* fp)
-{
-    delete from_libc(fp);
-    return 0;
-}
diff --git a/libc/internal/__lock.c b/libc/internal/__lock.c
new file mode 100644
index 0000000000000000000000000000000000000000..97ba245cea2e75efb78015d34fd1c1fe9392aa1a
--- /dev/null
+++ b/libc/internal/__lock.c
@@ -0,0 +1,10 @@
+
+#include "libc.h"
+
+void __lock(volatile int *l)
+{
+}
+
+void __unlock(volatile int *l)
+{
+}
diff --git a/libc/internal/floatscan.c b/libc/internal/floatscan.c
new file mode 100644
index 0000000000000000000000000000000000000000..212e9a2e4520c1256bd8aa2d1e9dfa6781426ec3
--- /dev/null
+++ b/libc/internal/floatscan.c
@@ -0,0 +1,496 @@
+#include <stdint.h>
+#include <math.h>
+#include <float.h>
+#include <limits.h>
+#include <errno.h>
+#include <ctype.h>
+
+#include "../stdio/stdio.h"
+#include "../stdio/shgetc.h"
+#include "floatscan.h"
+
+#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
+
+#define LD_B1B_DIG 2
+#define LD_B1B_MAX 9007199, 254740991
+#define KMAX 128
+
+#else /* LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384 */
+
+#define LD_B1B_DIG 3
+#define LD_B1B_MAX 18, 446744073, 709551615
+#define KMAX 2048
+
+#endif
+
+#define MASK (KMAX-1)
+
+#define CONCAT2(x,y) x ## y
+#define CONCAT(x,y) CONCAT2(x,y)
+
+static long long scanexp(FILE *f, int pok)
+{
+	int c;
+	int x;
+	long long y;
+	int neg = 0;
+	
+	c = shgetc(f);
+	if (c=='+' || c=='-') {
+		neg = (c=='-');
+		c = shgetc(f);
+		if (c-'0'>=10U && pok) shunget(f);
+	}
+	if (c-'0'>=10U) {
+		shunget(f);
+		return LLONG_MIN;
+	}
+	for (x=0; c-'0'<10U && x<INT_MAX/10; c = shgetc(f))
+		x = 10*x + c-'0';
+	for (y=x; c-'0'<10U && y<LLONG_MAX/100; c = shgetc(f))
+		y = 10*y + c-'0';
+	for (; c-'0'<10U; c = shgetc(f));
+	shunget(f);
+	return neg ? -y : y;
+}
+
+
+static long double decfloat(FILE *f, int c, int bits, int emin, int sign, int pok)
+{
+	uint32_t x[KMAX];
+	static const uint32_t th[] = { LD_B1B_MAX };
+	int i, j, k, a, z;
+	long long lrp=0, dc=0;
+	long long e10=0;
+	int lnz = 0;
+	int gotdig = 0, gotrad = 0;
+	int rp;
+	int e2;
+	int emax = -emin-bits+3;
+	int denormal = 0;
+	long double y;
+	long double frac=0;
+	long double bias=0;
+	static const int p10s[] = { 10, 100, 1000, 10000,
+		100000, 1000000, 10000000, 100000000 };
+
+	j=0;
+	k=0;
+
+	/* Don't let leading zeros consume buffer space */
+	for (; c=='0'; c = shgetc(f)) gotdig=1;
+	if (c=='.') {
+		gotrad = 1;
+		for (c = shgetc(f); c=='0'; c = shgetc(f)) gotdig=1, lrp--;
+	}
+
+	x[0] = 0;
+	for (; c-'0'<10U || c=='.'; c = shgetc(f)) {
+		if (c == '.') {
+			if (gotrad) break;
+			gotrad = 1;
+			lrp = dc;
+		} else if (k < KMAX-3) {
+			dc++;
+			if (c!='0') lnz = dc;
+			if (j) x[k] = x[k]*10 + c-'0';
+			else x[k] = c-'0';
+			if (++j==9) {
+				k++;
+				j=0;
+			}
+			gotdig=1;
+		} else {
+			dc++;
+			if (c!='0') x[KMAX-4] |= 1;
+		}
+	}
+	if (!gotrad) lrp=dc;
+
+	if (gotdig && (c|32)=='e') {
+		e10 = scanexp(f, pok);
+		if (e10 == LLONG_MIN) {
+			if (pok) {
+				shunget(f);
+			} else {
+				shlim(f, 0);
+				return 0;
+			}
+			e10 = 0;
+		}
+		lrp += e10;
+	} else if (c>=0) {
+		shunget(f);
+	}
+	if (!gotdig) {
+		errno = EINVAL;
+		shlim(f, 0);
+		return 0;
+	}
+
+	/* Handle zero specially to avoid nasty special cases later */
+	if (!x[0]) return sign * 0.0;
+
+	/* Optimize small integers (w/no exponent) and over/under-flow */
+	if (lrp==dc && dc<10 && (bits>30 || x[0]>>bits==0))
+		return sign * (long double)x[0];
+	if (lrp > -emin/2) {
+		errno = ERANGE;
+		return sign * LDBL_MAX * LDBL_MAX;
+	}
+	if (lrp < emin-2*LDBL_MANT_DIG) {
+		errno = ERANGE;
+		return sign * LDBL_MIN * LDBL_MIN;
+	}
+
+	/* Align incomplete final B1B digit */
+	if (j) {
+		for (; j<9; j++) x[k]*=10;
+		k++;
+		j=0;
+	}
+
+	a = 0;
+	z = k;
+	e2 = 0;
+	rp = lrp;
+
+	/* Optimize small to mid-size integers (even in exp. notation) */
+	if (lnz<9 && lnz<=rp && rp < 18) {
+		if (rp == 9) return sign * (long double)x[0];
+		if (rp < 9) return sign * (long double)x[0] / p10s[8-rp];
+		int bitlim = bits-3*(int)(rp-9);
+		if (bitlim>30 || x[0]>>bitlim==0)
+			return sign * (long double)x[0] * p10s[rp-10];
+	}
+
+	/* Align radix point to B1B digit boundary */
+	if (rp % 9) {
+		int rpm9 = rp>=0 ? rp%9 : rp%9+9;
+		int p10 = p10s[8-rpm9];
+		uint32_t carry = 0;
+		for (k=a; k!=z; k++) {
+			uint32_t tmp = x[k] % p10;
+			x[k] = x[k]/p10 + carry;
+			carry = 1000000000/p10 * tmp;
+			if (k==a && !x[k]) {
+				a = (a+1 & MASK);
+				rp -= 9;
+			}
+		}
+		if (carry) x[z++] = carry;
+		rp += 9-rpm9;
+	}
+
+	/* Upscale until desired number of bits are left of radix point */
+	while (rp < 9*LD_B1B_DIG || (rp == 9*LD_B1B_DIG && x[a]<th[0])) {
+		uint32_t carry = 0;
+		e2 -= 29;
+		for (k=(z-1 & MASK); ; k=(k-1 & MASK)) {
+			uint64_t tmp = ((uint64_t)x[k] << 29) + carry;
+			if (tmp > 1000000000) {
+				carry = tmp / 1000000000;
+				x[k] = tmp % 1000000000;
+			} else {
+				carry = 0;
+				x[k] = tmp;
+			}
+			if (k==(z-1 & MASK) && k!=a && !x[k]) z = k;
+			if (k==a) break;
+		}
+		if (carry) {
+			rp += 9;
+			a = (a-1 & MASK);
+			if (a == z) {
+				z = (z-1 & MASK);
+				x[z-1 & MASK] |= x[z];
+			}
+			x[a] = carry;
+		}
+	}
+
+	/* Downscale until exactly number of bits are left of radix point */
+	for (;;) {
+		uint32_t carry = 0;
+		int sh = 1;
+		for (i=0; i<LD_B1B_DIG; i++) {
+			k = (a+i & MASK);
+			if (k == z || x[k] < th[i]) {
+				i=LD_B1B_DIG;
+				break;
+			}
+			if (x[a+i & MASK] > th[i]) break;
+		}
+		if (i==LD_B1B_DIG && rp==9*LD_B1B_DIG) break;
+		/* FIXME: find a way to compute optimal sh */
+		if (rp > 9+9*LD_B1B_DIG) sh = 9;
+		e2 += sh;
+		for (k=a; k!=z; k=(k+1 & MASK)) {
+			uint32_t tmp = x[k] & (1<<sh)-1;
+			x[k] = (x[k]>>sh) + carry;
+			carry = (1000000000>>sh) * tmp;
+			if (k==a && !x[k]) {
+				a = (a+1 & MASK);
+				i--;
+				rp -= 9;
+			}
+		}
+		if (carry) {
+			if ((z+1 & MASK) != a) {
+				x[z] = carry;
+				z = (z+1 & MASK);
+			} else x[z-1 & MASK] |= 1;
+		}
+	}
+
+	/* Assemble desired bits into floating point variable */
+	for (y=i=0; i<LD_B1B_DIG; i++) {
+		if ((a+i & MASK)==z) x[(z=(z+1 & MASK))-1] = 0;
+		y = 1000000000.0L * y + x[a+i & MASK];
+	}
+
+	y *= sign;
+
+	/* Limit precision for denormal results */
+	if (bits > LDBL_MANT_DIG+e2-emin) {
+		bits = LDBL_MANT_DIG+e2-emin;
+		if (bits<0) bits=0;
+		denormal = 1;
+	}
+
+	/* Calculate bias term to force rounding, move out lower bits */
+	if (bits < LDBL_MANT_DIG) {
+		bias = copysignl(scalbn(1, 2*LDBL_MANT_DIG-bits-1), y);
+		frac = fmodl(y, scalbn(1, LDBL_MANT_DIG-bits));
+		y -= frac;
+		y += bias;
+	}
+
+	/* Process tail of decimal input so it can affect rounding */
+	if ((a+i & MASK) != z) {
+		uint32_t t = x[a+i & MASK];
+		if (t < 500000000 && (t || (a+i+1 & MASK) != z))
+			frac += 0.25*sign;
+		else if (t > 500000000)
+			frac += 0.75*sign;
+		else if (t == 500000000) {
+			if ((a+i+1 & MASK) == z)
+				frac += 0.5*sign;
+			else
+				frac += 0.75*sign;
+		}
+		if (LDBL_MANT_DIG-bits >= 2 && !fmodl(frac, 1))
+			frac++;
+	}
+
+	y += frac;
+	y -= bias;
+
+	if ((e2+LDBL_MANT_DIG & INT_MAX) > emax-5) {
+		if (fabs(y) >= CONCAT(0x1p, LDBL_MANT_DIG)) {
+			if (denormal && bits==LDBL_MANT_DIG+e2-emin)
+				denormal = 0;
+			y *= 0.5;
+			e2++;
+		}
+		if (e2+LDBL_MANT_DIG>emax || (denormal && frac))
+			errno = ERANGE;
+	}
+
+	return scalbnl(y, e2);
+}
+
+static long double hexfloat(FILE *f, int bits, int emin, int sign, int pok)
+{
+	uint32_t x = 0;
+	long double y = 0;
+	long double scale = 1;
+	long double bias = 0;
+	int gottail = 0, gotrad = 0, gotdig = 0;
+	long long rp = 0;
+	long long dc = 0;
+	long long e2 = 0;
+	int d;
+	int c;
+
+	c = shgetc(f);
+
+	/* Skip leading zeros */
+	for (; c=='0'; c = shgetc(f)) gotdig = 1;
+
+	if (c=='.') {
+		gotrad = 1;
+		c = shgetc(f);
+		/* Count zeros after the radix point before significand */
+		for (rp=0; c=='0'; c = shgetc(f), rp--) gotdig = 1;
+	}
+
+	for (; c-'0'<10U || (c|32)-'a'<6U || c=='.'; c = shgetc(f)) {
+		if (c=='.') {
+			if (gotrad) break;
+			rp = dc;
+			gotrad = 1;
+		} else {
+			gotdig = 1;
+			if (c > '9') d = (c|32)+10-'a';
+			else d = c-'0';
+			if (dc<8) {
+				x = x*16 + d;
+			} else if (dc < LDBL_MANT_DIG/4+1) {
+				y += d*(scale/=16);
+			} else if (d && !gottail) {
+				y += 0.5*scale;
+				gottail = 1;
+			}
+			dc++;
+		}
+	}
+	if (!gotdig) {
+		shunget(f);
+		if (pok) {
+			shunget(f);
+			if (gotrad) shunget(f);
+		} else {
+			shlim(f, 0);
+		}
+		return sign * 0.0;
+	}
+	if (!gotrad) rp = dc;
+	while (dc<8) x *= 16, dc++;
+	if ((c|32)=='p') {
+		e2 = scanexp(f, pok);
+		if (e2 == LLONG_MIN) {
+			if (pok) {
+				shunget(f);
+			} else {
+				shlim(f, 0);
+				return 0;
+			}
+			e2 = 0;
+		}
+	} else {
+		shunget(f);
+	}
+	e2 += 4*rp - 32;
+
+	if (!x) return sign * 0.0;
+	if (e2 > -emin) {
+		errno = ERANGE;
+		return sign * LDBL_MAX * LDBL_MAX;
+	}
+	if (e2 < emin-2*LDBL_MANT_DIG) {
+		errno = ERANGE;
+		return sign * LDBL_MIN * LDBL_MIN;
+	}
+
+	while (x < 0x80000000) {
+		if (y>=0.5) {
+			x += x + 1;
+			y += y - 1;
+		} else {
+			x += x;
+			y += y;
+		}
+		e2--;
+	}
+
+	if (bits > 32+e2-emin) {
+		bits = 32+e2-emin;
+		if (bits<0) bits=0;
+	}
+
+	if (bits < LDBL_MANT_DIG)
+		bias = copysignl(scalbn(1, 32+LDBL_MANT_DIG-bits-1), sign);
+
+	if (bits<32 && y && !(x&1)) x++, y=0;
+
+	y = bias + sign*(long double)x + sign*y;
+	y -= bias;
+
+	if (!y) errno = ERANGE;
+
+	return scalbnl(y, e2);
+}
+
+long double __floatscan(FILE *f, int prec, int pok)
+{
+	int sign = 1;
+	size_t i;
+	int bits;
+	int emin;
+	int c;
+
+	switch (prec) {
+	case 0:
+		bits = FLT_MANT_DIG;
+		emin = FLT_MIN_EXP-bits;
+		break;
+	case 1:
+		bits = DBL_MANT_DIG;
+		emin = DBL_MIN_EXP-bits;
+		break;
+	case 2:
+		bits = LDBL_MANT_DIG;
+		emin = LDBL_MIN_EXP-bits;
+		break;
+	default:
+		return 0;
+	}
+
+	while (isspace((c=shgetc(f))));
+
+	if (c=='+' || c=='-') {
+		sign -= 2*(c=='-');
+		c = shgetc(f);
+	}
+
+	for (i=0; i<8 && (c|32)=="infinity"[i]; i++)
+		if (i<7) c = shgetc(f);
+	if (i==3 || i==8 || (i>3 && pok)) {
+		if (i!=8) {
+			shunget(f);
+			if (pok) for (; i>3; i--) shunget(f);
+		}
+		return sign * INFINITY;
+	}
+	if (!i) for (i=0; i<3 && (c|32)=="nan"[i]; i++)
+		if (i<2) c = shgetc(f);
+	if (i==3) {
+		if (shgetc(f) != '(') {
+			shunget(f);
+			return NAN;
+		}
+		for (i=1; ; i++) {
+			c = shgetc(f);
+			if (c-'0'<10U || c-'A'<26U || c-'a'<26U || c=='_')
+				continue;
+			if (c==')') return NAN;
+			shunget(f);
+			if (!pok) {
+				errno = EINVAL;
+				shlim(f, 0);
+				return 0;
+			}
+			while (i--) shunget(f);
+			return NAN;
+		}
+		return NAN;
+	}
+
+	if (i) {
+		shunget(f);
+		errno = EINVAL;
+		shlim(f, 0);
+		return 0;
+	}
+
+	if (c=='0') {
+		c = shgetc(f);
+		if ((c|32) == 'x')
+			return hexfloat(f, bits, emin, sign, pok);
+		shunget(f);
+		c = '0';
+	}
+
+	return decfloat(f, c, bits, emin, sign, pok);
+}
diff --git a/libc/internal/floatscan.h b/libc/internal/floatscan.h
new file mode 100644
index 0000000000000000000000000000000000000000..e027fa08f107bf0893f3132df06200e0d2beb1c2
--- /dev/null
+++ b/libc/internal/floatscan.h
@@ -0,0 +1,8 @@
+#ifndef FLOATSCAN_H
+#define FLOATSCAN_H
+
+#include <stdio.h>
+
+long double __floatscan(FILE *, int, int);
+
+#endif
diff --git a/libc/internal/intscan.c b/libc/internal/intscan.c
new file mode 100644
index 0000000000000000000000000000000000000000..629610a111d8a05dfe1b2f02a28c95b548e7dc66
--- /dev/null
+++ b/libc/internal/intscan.c
@@ -0,0 +1,99 @@
+#include <limits.h>
+#include <errno.h>
+#include <ctype.h>
+#include "../stdio/shgetc.h"
+
+/* Lookup table for digit values. -1==255>=36 -> invalid */
+static const unsigned char table[] = { -1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1,
+-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
+25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
+-1,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,
+25,26,27,28,29,30,31,32,33,34,35,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
+};
+
+unsigned long long __intscan(FILE *f, unsigned base, int pok, unsigned long long lim)
+{
+	const unsigned char *val = table+1;
+	int c, neg=0;
+	unsigned x;
+	unsigned long long y;
+	if (base > 36) {
+		errno = EINVAL;
+		return 0;
+	}
+	while (isspace((c=shgetc(f))));
+	if (c=='+' || c=='-') {
+		neg = -(c=='-');
+		c = shgetc(f);
+	}
+	if ((base == 0 || base == 16) && c=='0') {
+		c = shgetc(f);
+		if ((c|32)=='x') {
+			c = shgetc(f);
+			if (val[c]>=16) {
+				shunget(f);
+				if (pok) shunget(f);
+				else shlim(f, 0);
+				return 0;
+			}
+			base = 16;
+		} else if (base == 0) {
+			base = 8;
+		}
+	} else {
+		if (base == 0) base = 10;
+		if (val[c] >= base) {
+			shunget(f);
+			shlim(f, 0);
+			errno = EINVAL;
+			return 0;
+		}
+	}
+	if (base == 10) {
+		for (x=0; c-'0'<10U && x<=UINT_MAX/10-1; c=shgetc(f))
+			x = x*10 + (c-'0');
+		for (y=x; c-'0'<10U && y<=ULLONG_MAX/10 && 10*y<=ULLONG_MAX-(c-'0'); c=shgetc(f))
+			y = y*10 + (c-'0');
+		if (c-'0'>=10U) goto done;
+	} else if (!(base & base-1)) {
+		int bs = "\0\1\2\4\7\3\6\5"[(0x17*base)>>5&7];
+		for (x=0; val[c]<base && x<=UINT_MAX/32; c=shgetc(f))
+			x = x<<bs | val[c];
+		for (y=x; val[c]<base && y<=ULLONG_MAX>>bs; c=shgetc(f))
+			y = y<<bs | val[c];
+	} else {
+		for (x=0; val[c]<base && x<=UINT_MAX/36-1; c=shgetc(f))
+			x = x*base + val[c];
+		for (y=x; val[c]<base && y<=ULLONG_MAX/base && base*y<=ULLONG_MAX-val[c]; c=shgetc(f))
+			y = y*base + val[c];
+	}
+	if (val[c]<base) {
+		for (; val[c]<base; c=shgetc(f));
+		errno = ERANGE;
+		y = lim;
+	}
+done:
+	shunget(f);
+	if (y>=lim) {
+		if (!(lim&1) && !neg) {
+			errno = ERANGE;
+			return lim-1;
+		} else if (y>lim) {
+			errno = ERANGE;
+			return lim;
+		}
+	}
+	return (y^neg)-neg;
+}
diff --git a/libc/internal/intscan.h b/libc/internal/intscan.h
new file mode 100644
index 0000000000000000000000000000000000000000..994c5e7deece936b76abd6c612514b85af59ff96
--- /dev/null
+++ b/libc/internal/intscan.h
@@ -0,0 +1,8 @@
+#ifndef INTSCAN_H
+#define INTSCAN_H
+
+#include <stdio.h>
+
+unsigned long long __intscan(FILE *, unsigned, int, unsigned long long);
+
+#endif
diff --git a/libc/internal/libc.c b/libc/internal/libc.c
new file mode 100644
index 0000000000000000000000000000000000000000..1037966852e68e5e8f5e619cb9bca4e1c59bd36c
--- /dev/null
+++ b/libc/internal/libc.c
@@ -0,0 +1,3 @@
+#include <libc.h>
+
+struct __libc __libc;
diff --git a/libc/internal/libc.h b/libc/internal/libc.h
index 2b9f203007e7637e1035651b5226953febdea860..6d48bcb0963ab7e925eddc89cfd820a311bde390 100644
--- a/libc/internal/libc.h
+++ b/libc/internal/libc.h
@@ -1,16 +1,50 @@
+#ifndef LIBC_H
+#define LIBC_H
 
-#undef weak_alias
-#define weak_alias(old, new) \
-	extern __typeof(old) new __attribute__((weak, alias(#old)))
+#include <stdlib.h>
+#include "stdio.h"
+
+/* as long as we use the glibc header we'll need this hack */
+#ifndef O_LARGEFILE
+#define O_LARGEFILE	0
+#endif
+
+struct __libc {
+	void *main_thread;
+	int threaded;
+//	int secure;
+//	size_t *auxv;
+//	int (*atexit)(void (*)(void));
+//	void (*fini)(void);
+//	void (*ldso_fini)(void);
+	volatile int threads_minus_1;
+//	int canceldisable;
+	FILE *ofl_head;
+	int ofl_lock[2];
+//	size_t tls_size;
+};
 
 #define ATTR_LIBC_VISIBILITY __attribute__((visibility("hidden")))
 
-/* TODO: add real locking */
-#define LOCK(x) ((void)(x))
-#define UNLOCK(x) ((void)(x))
+extern struct __libc __libc ATTR_LIBC_VISIBILITY;
+#define libc __libc
+
+/* Designed to avoid any overhead in non-threaded processes */
+void __lock(volatile int *) ATTR_LIBC_VISIBILITY;
+void __unlock(volatile int *) ATTR_LIBC_VISIBILITY;
+int __lockfile(FILE *) ATTR_LIBC_VISIBILITY;
+void __unlockfile(FILE *) ATTR_LIBC_VISIBILITY;
+#define LOCK(x) (libc.threads_minus_1 ? (__lock(x),1) : ((void)(x),1))
+#define UNLOCK(x) (libc.threads_minus_1 ? (__unlock(x),1) : ((void)(x),1))
+
+#undef weak_alias
+#define weak_alias(old, new) \
+	extern __typeof(old) new __attribute__((weak, alias(#old)))
 
 #undef LFS64_2
 #define LFS64_2(x, y) weak_alias(x, y)
 
 #undef LFS64
 #define LFS64(x) LFS64_2(x, x##64)
+
+#endif
diff --git a/libc/internal/pthread_stubs.h b/libc/internal/pthread_stubs.h
new file mode 100644
index 0000000000000000000000000000000000000000..6543db03347f845c608176c826e8d7d7c0e36139
--- /dev/null
+++ b/libc/internal/pthread_stubs.h
@@ -0,0 +1,9 @@
+
+
+/* until we get proper pthread cancellation support */
+#undef pthread_cleanup_push
+#define pthread_cleanup_push(c, f)	do { } while (0)
+
+#undef pthread_cleanup_pop
+#define pthread_cleanup_pop(n	)	do { } while (0)
+
diff --git a/libc/internal/shgetc.c b/libc/internal/shgetc.c
new file mode 100644
index 0000000000000000000000000000000000000000..0641c83527392b5bdecc7b9b63dc0ca612366b7d
--- /dev/null
+++ b/libc/internal/shgetc.c
@@ -0,0 +1,26 @@
+#include "../stdio/shgetc.h"
+
+void __shlim(FILE *f, off_t lim)
+{
+	f->shlim = lim;
+	f->shcnt = f->rend - f->rpos;
+	if (lim && f->shcnt > lim)
+		f->shend = f->rpos + lim;
+	else
+		f->shend = f->rend;
+}
+
+int __shgetc(FILE *f)
+{
+	int c;
+	if (f->shlim && f->shcnt >= f->shlim || (c=__uflow(f)) < 0) {
+		f->shend = 0;
+		return EOF;
+	}
+	if (f->shlim && f->rend - f->rpos > f->shlim - f->shcnt - 1)
+		f->shend = f->rpos + (f->shlim - f->shcnt - 1);
+	else
+		f->shend = f->rend;
+	if (f->rend) f->shcnt += f->rend - f->rpos + 1;
+	return c;
+}
diff --git a/libc/printf.cc b/libc/printf.cc
deleted file mode 100644
index 4251d37be4f0a596d6b9a1a63aa25e5ebe7adef2..0000000000000000000000000000000000000000
--- a/libc/printf.cc
+++ /dev/null
@@ -1,365 +0,0 @@
-#include <stdio.h>
-#include <stdarg.h>
-#include <string>
-#include <memory>
-#include <vector>
-#include <stdint.h>
-#include <cctype>
-#include <string.h>
-#include "debug.hh"
-
-namespace {
-
-// printf() is difficult because we must traverse the argument list
-// (va_list ap) linearly, while the format string may specify random
-// access using %4$d.
-//
-// our strategy is to parse the string and construct two vectors:
-//
-// args: objects of type 'arg' that are able to call the va_arg
-//       macro with the appropriate type, and place it into a member of
-//       'arg'.  'args' actually holds unique_ptr<>s to avoid leaks.
-// frags: function objects, that, when called, yield a string that is
-//        a fragment of the object being constructed.  Plaintext is
-//        converted to a function that yields the text, while conversions
-//        call more complicated functions.
-//
-// once we parse the format string, we iterate over args to read in the
-// arguments, then iterator over frags to generate the string.
-
-
-struct arg {
-    virtual ~arg() {}
-    virtual void consume(va_list ap) = 0;
-};
-
-struct arg_intx : arg {
-    intmax_t val;
-};
-
-struct arg_char : arg_intx {
-    virtual void consume(va_list ap) { val = va_arg(ap, int); }
-};
-
-struct arg_short : arg_intx {
-    virtual void consume(va_list ap) { val = va_arg(ap, int); }
-};
-
-struct arg_int : arg_intx {
-    virtual void consume(va_list ap) { val = va_arg(ap, int); }
-};
-
-struct arg_long : arg_intx {
-    virtual void consume(va_list ap) { val = va_arg(ap, long int); }
-};
-
-struct arg_longlong : arg_intx {
-    virtual void consume(va_list ap) { val = va_arg(ap, long long int); }
-};
-
-struct arg_uintx : arg {
-    uintmax_t val;
-};
-
-struct arg_uint : arg_uintx {
-    virtual void consume(va_list ap) { val = va_arg(ap, unsigned); }
-};
-
-struct arg_ulint : arg_uintx {
-    virtual void consume(va_list ap) { val = va_arg(ap, unsigned long); }
-};
-
-struct arg_ullint : arg_uintx {
-    virtual void consume(va_list ap) { val = va_arg(ap, unsigned long long); }
-};
-
-struct arg_ptr : arg {
-    void* val;
-    virtual void consume(va_list ap) { val = va_arg(ap, void*); }
-};
-
-struct arg_double : arg {
-    double val;
-    virtual void consume(va_list ap) { val = va_arg(ap, double); }
-};
-
-struct arg_str: arg {
-    const char* val;
-    virtual void consume(va_list ap) { val = va_arg(ap, const char*); }
-};
-
-enum intlen {
-    len_char,
-    len_short,
-    len_int,
-    len_long,
-    len_longlong,
-};
-
-void fill_right_to(std::string& str, char c, size_t len)
-{
-    while (str.length() < len) {
-        str.push_back(c);
-    }
-}
-
-std::string strprintf(const char* fmt, va_list ap)
-{
-    auto orig = fmt;
-    std::vector<std::unique_ptr<arg>> args;
-    std::vector<std::function<std::string ()>> frags;
-    unsigned lastpos = 0;
-    auto add_arg = [&] (int pos, arg* parg) {
-        args.resize(std::max(size_t(pos), args.size()));
-        args[pos-1] = std::unique_ptr<arg>(parg);
-    };
-    auto make_int_arg = [&] (int pos, intlen len = len_int) {
-        arg_intx* parg;
-        switch (len) {
-        case len_char: parg = new arg_char; break;
-        case len_short: parg = new arg_short; break;
-        case len_int: parg = new arg_int; break;
-        case len_long: parg = new arg_long; break;
-        case len_longlong: parg = new arg_longlong; break;
-        default: abort();
-        }
-        add_arg(pos, parg);
-        return parg;
-    };
-    while (*fmt) {
-        auto p = fmt;
-        while (*p && *p != '%') {
-            ++p;
-        }
-        if (p != fmt) {
-            frags.push_back([=] { return std::string(fmt, p); } );
-            fmt = p;
-        }
-        if (!*fmt) {
-            break;
-        }
-        // found '%'
-        ++fmt;
-        if (*fmt == '%') {
-            frags.push_back([] { return std::string("%"); });
-            continue;
-        } else if (!*fmt) {
-            break;
-        }
-        auto get_number = [&fmt] {
-            int pos = 0;
-            while (std::isdigit(*fmt)) {
-                pos = pos * 10 + (*fmt++ - '0');
-            }
-            return pos;
-        };
-        auto get_positional = [&fmt, &get_number, &lastpos] {
-            auto save = fmt;
-            auto pos = get_number();
-            if (pos == 0 || *fmt != '$') {
-                fmt = save;
-                pos = ++lastpos;
-            }
-            return pos;
-        };
-        unsigned pos = get_positional();
-        bool alt_form = false;
-        char pad_char = ' ';
-        bool left_adjust = false;
-        bool add_blank = false;
-        bool add_sign = false;
-        bool thousands = false;
-        bool alt_digits = false;
-        bool go = true;
-        while (go) {
-            switch (*fmt++) {
-            case '#': alt_form = true; break;
-            case '0': pad_char = '0'; break;
-            case '-': left_adjust = true; break;
-            case ' ': add_blank = true; break;
-            case '+': add_sign = true; break;
-            case '\'': thousands = true; break;
-            case 'I': alt_digits = true; break;
-            default: --fmt; go = false; break;
-            }
-        }
-        if (alt_form || left_adjust || add_blank || add_sign
-                || thousands || alt_digits) {
-            debug(boost::format("unimplemented format %1%") % orig);
-        }
-        int width = get_number();
-        std::function<int ()> width_fn = [=] { return width; };
-        if (!width && *fmt == '*') {
-            ++fmt;
-            auto arg = make_int_arg(get_positional());
-            width_fn = [=] { return int(arg->val); };
-        }
-        bool has_precision = *fmt == '.';
-        std::function<int ()> precision_fn;
-        if (has_precision) {
-            ++fmt;
-            auto precision = get_number();
-            precision_fn = [=] { return precision; };
-            if (!precision && *fmt == '*') {
-                ++fmt;
-                auto arg = make_int_arg(get_positional());
-                precision_fn = [=] { return int(arg->val); };
-            }
-        }
-        int hcount = 0, lcount = 0, Lcount = 0, jcount = 0, zcount = 0, tcount = 0;
-        go = true;
-        while (go) {
-            switch (*fmt++) {
-            case 'h': ++hcount; break;
-            case 'l': ++lcount; break;
-            case 'L': ++Lcount; break;
-            case 'j': ++jcount; break;
-            case 'z': ++zcount; break;
-            case 't': ++tcount; break;
-            default: --fmt; go = false; break;
-            }
-        }
-        auto int_size = [=] {
-            if (hcount >= 2) return len_char;
-            if (hcount == 1) return len_short;
-            if (lcount >= 2) return len_longlong;
-            if (lcount == 1) return len_long;
-            return len_int;
-        };
-        auto get_precision_or_default = [=] (int prec) -> std::function<int ()> {
-            if (!has_precision) {
-                return [=] { return prec; };
-            }
-            return precision_fn;
-        };
-        auto unsigned_conversion = [=, &frags] (unsigned base, const char* digits) {
-            auto precision_fn = get_precision_or_default(1);
-            auto arg = make_int_arg(pos, int_size());
-            frags.push_back([=] {
-                std::string ret;
-                uintmax_t val = arg->val;
-                while (val) {
-                    ret.push_back(digits[val % base]);
-                    val /= base;
-                }
-                fill_right_to(ret, '0', precision_fn());
-                fill_right_to(ret, pad_char, width_fn());
-                std::reverse(ret.begin(), ret.end());
-                return ret;
-            });
-        };
-        switch (*fmt++) {
-        case 'd':
-        case 'i': {
-            auto precision_fn = get_precision_or_default(1);
-            auto arg = make_int_arg(pos, int_size());
-            frags.push_back([=] {
-                std::string ret;
-                bool negative = arg->val < 0;
-                uintmax_t val = std::abs(arg->val);
-                while (val) {
-                    ret.push_back('0' + val % 10);
-                    val /= 10;
-                };
-                fill_right_to(ret, '0', precision_fn() - negative);
-                if (negative) {
-                    ret.push_back('-');
-                }
-                fill_right_to(ret, ' ', width_fn());
-                std::reverse(ret.begin(), ret.end());
-                return ret;
-            });
-            break;
-        }
-        case 'u':
-             unsigned_conversion(10u, "0123456789");
-             break;
-        case 'o':
-             unsigned_conversion(8u, "01234567");
-             break;
-        case 'x':
-             unsigned_conversion(16u, "0123456789abcdef");
-             break;
-        case 'X':
-             unsigned_conversion(16u, "0123456789ABCDEF");
-             break;
-        case 'f':
-        case 'F':
-        case 'g':
-        case 'G':
-        case 'a':
-        case 'A':
-            abort();
-        case 'c': {
-            if (lcount) {
-                debug("%lc conversion ignored");
-            }
-            auto arg = make_int_arg(pos);
-            frags.push_back([=] { char c = arg->val; return std::string(c, 1); });
-            break;
-        }
-        case 's': {
-            auto arg = new arg_str;
-            add_arg(pos, arg);
-            frags.push_back([=] { return std::string(arg->val); });
-            break;
-        }
-        default:
-            abort();
-        }
-    }
-    for (size_t i = 0; i < args.size(); ++i) {
-        args[i]->consume(ap);
-    }
-    std::string ret;
-    for (auto p : frags) {
-        ret += (p)();
-    }
-    return ret;
-}
-
-}
-
-int vsnprintf(char *str, size_t size, const char *format, va_list ap)
-{
-    auto out = strprintf(format, ap);
-    auto trunc = out.substr(0, size - 1);
-    auto last = std::copy(trunc.begin(), trunc.end(), str);
-    *last = '\0';
-    return out.length();
-}
-
-int sprintf(char* str, const char* format, ...)
-{
-    va_list ap;
-
-    va_start(ap, format);
-    auto out = strprintf(format, ap);
-    va_end(ap);
-    strcpy(str, out.c_str());
-    return out.length();
-}
-
-int snprintf(char* str, size_t n, const char* format, ...)
-{
-    va_list ap;
-
-    va_start(ap, format);
-    auto out = strprintf(format, ap);
-    va_end(ap);
-    std::string trunc = out.substr(0, n - 1);
-    strcpy(str, trunc.c_str());
-    return out.length();
-}
-
-int printf(const char* format, ...)
-{
-    va_list ap;
-
-    va_start(ap, format);
-    auto out = strprintf(format, ap);
-    va_end(ap);
-
-    debug(out);
-    return out.length();
-}
diff --git a/libc/stdio/__fclose_ca.c b/libc/stdio/__fclose_ca.c
new file mode 100644
index 0000000000000000000000000000000000000000..e0b12a15af79a310f45d5a618257de7fc3667745
--- /dev/null
+++ b/libc/stdio/__fclose_ca.c
@@ -0,0 +1,6 @@
+#include "stdio_impl.h"
+
+int __fclose_ca(FILE *f)
+{
+	return f->close(f);
+}
diff --git a/libc/stdio/__fdopen.c b/libc/stdio/__fdopen.c
new file mode 100644
index 0000000000000000000000000000000000000000..324e34625188d43f166ccaaee186fed66e97a803
--- /dev/null
+++ b/libc/stdio/__fdopen.c
@@ -0,0 +1,65 @@
+#include "stdio_impl.h"
+#include <stdlib.h>
+#include <termios.h>
+#include <sys/ioctl.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+
+FILE *__fdopen(int fd, const char *mode)
+{
+	FILE *f;
+	struct termios tio;
+
+	/* Check for valid initial mode character */
+	if (!strchr("rwa", *mode)) {
+		errno = EINVAL;
+		return 0;
+	}
+
+	/* Allocate FILE+buffer or fail */
+	if (!(f=malloc(sizeof *f + UNGET + BUFSIZ))) return 0;
+
+	/* Zero-fill only the struct, not the buffer */
+	memset(f, 0, sizeof *f);
+
+	/* Impose mode restrictions */
+	if (!strchr(mode, '+')) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
+
+	/* Apply close-on-exec flag */
+	if (strchr(mode, 'e')) fcntl(fd, F_SETFD, FD_CLOEXEC);
+
+	/* Set append mode on fd if opened for append */
+	if (*mode == 'a') {
+		int flags = fcntl(fd, F_GETFL);
+		fcntl(fd, F_SETFL, flags | O_APPEND);
+	}
+
+	f->fd = fd;
+	f->buf = (unsigned char *)f + sizeof *f + UNGET;
+	f->buf_size = BUFSIZ;
+
+	/* Activate line buffered mode for terminals */
+	f->lbf = EOF;
+	if (!(f->flags & F_NOWR) && !ioctl(fd, TCGETS, &tio))
+		f->lbf = '\n';
+
+	/* Initialize op ptrs. No problem if some are unneeded. */
+	f->read = __stdio_read;
+	f->write = __stdio_write;
+	f->seek = __stdio_seek;
+	f->close = __stdio_close;
+
+	if (!libc.threaded) f->lock = -1;
+
+	/* Add new FILE to open file list */
+	OFLLOCK();
+	f->next = libc.ofl_head;
+	if (libc.ofl_head) libc.ofl_head->prev = f;
+	libc.ofl_head = f;
+	OFLUNLOCK();
+
+	return f;
+}
+
+weak_alias(__fdopen, fdopen);
diff --git a/libc/stdio/__fmodeflags.c b/libc/stdio/__fmodeflags.c
new file mode 100644
index 0000000000000000000000000000000000000000..da9f23b633a0828a07cad171318d5d05132c2827
--- /dev/null
+++ b/libc/stdio/__fmodeflags.c
@@ -0,0 +1,16 @@
+#include <fcntl.h>
+#include <string.h>
+
+int __fmodeflags(const char *mode)
+{
+	int flags;
+	if (strchr(mode, '+')) flags = O_RDWR;
+	else if (*mode == 'r') flags = O_RDONLY;
+	else flags = O_WRONLY;
+	if (strchr(mode, 'x')) flags |= O_EXCL;
+	if (strchr(mode, 'e')) flags |= O_CLOEXEC;
+	if (*mode != 'r') flags |= O_CREAT;
+	if (*mode == 'w') flags |= O_TRUNC;
+	if (*mode == 'a') flags |= O_APPEND;
+	return flags;
+}
diff --git a/libc/stdio/__fopen_rb_ca.c b/libc/stdio/__fopen_rb_ca.c
new file mode 100644
index 0000000000000000000000000000000000000000..d9f43fcf7cf0c6b26aa6d5df643420febdc1c403
--- /dev/null
+++ b/libc/stdio/__fopen_rb_ca.c
@@ -0,0 +1,21 @@
+#include "stdio_impl.h"
+#include <fcntl.h>
+#include <string.h>
+
+FILE *__fopen_rb_ca(const char *filename, FILE *f, unsigned char *buf, size_t len)
+{
+	memset(f, 0, sizeof *f);
+
+	f->fd = open(filename, O_RDONLY|O_LARGEFILE|O_CLOEXEC, 0);
+	if (f->fd < 0) return 0;
+
+	f->flags = F_NOWR | F_PERM;
+	f->buf = buf + UNGET;
+	f->buf_size = len - UNGET;
+	f->read = __stdio_read;
+	f->seek = __stdio_seek;
+	f->close = __stdio_close;
+	f->lock = -1;
+
+	return f;
+}
diff --git a/libc/stdio/__lockfile.c b/libc/stdio/__lockfile.c
new file mode 100644
index 0000000000000000000000000000000000000000..dcd4186bf1c86a65162850f45c5f2fb85568a06d
--- /dev/null
+++ b/libc/stdio/__lockfile.c
@@ -0,0 +1,32 @@
+#include "stdio_impl.h"
+//#include "pthread_impl.h"
+
+int __lockfile(FILE *f)
+{
+#ifdef TODO
+	int owner, tid = __pthread_self()->tid;
+	if (f->lock == tid)
+		return 0;
+	while ((owner = a_cas(&f->lock, 0, tid)))
+		__wait(&f->lock, &f->waiters, owner, 1);
+#endif
+	return 1;
+}
+
+void __unlockfile(FILE *f)
+{
+#ifdef TODO
+	a_store(&f->lock, 0);
+
+	/* The following read is technically invalid under situations
+	 * of self-synchronized destruction. Another thread may have
+	 * called fclose as soon as the above store has completed.
+	 * Nonetheless, since FILE objects always live in memory
+	 * obtained by malloc from the heap, it's safe to assume
+	 * the dereferences below will not fault. In the worst case,
+	 * a spurious syscall will be made. If the implementation of
+	 * malloc changes, this assumption needs revisiting. */
+
+	if (f->waiters) __wake(&f->lock, 1, 1);
+#endif
+}
diff --git a/libc/stdio/__overflow.c b/libc/stdio/__overflow.c
new file mode 100644
index 0000000000000000000000000000000000000000..3bb37923abb847787878cf868d86bce570fb267e
--- /dev/null
+++ b/libc/stdio/__overflow.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+
+int __overflow(FILE *f, int _c)
+{
+	unsigned char c = _c;
+	if (!f->wend && __towrite(f)) return EOF;
+	if (f->wpos < f->wend && c != f->lbf) return *f->wpos++ = c;
+	if (f->write(f, &c, 1)!=1) return EOF;
+	return c;
+}
diff --git a/libc/stdio/__stdio_close.c b/libc/stdio/__stdio_close.c
new file mode 100644
index 0000000000000000000000000000000000000000..976e34ed96f1cb0202a646164e48e867a6b22ceb
--- /dev/null
+++ b/libc/stdio/__stdio_close.c
@@ -0,0 +1,7 @@
+#include <unistd.h>
+#include "stdio_impl.h"
+
+int __stdio_close(FILE *f)
+{
+	return close(f->fd);
+}
diff --git a/libc/stdio/__stdio_exit.c b/libc/stdio/__stdio_exit.c
new file mode 100644
index 0000000000000000000000000000000000000000..0fb3323489301651c14b0f516b94fb8f7b7bb3cf
--- /dev/null
+++ b/libc/stdio/__stdio_exit.c
@@ -0,0 +1,23 @@
+#include "stdio_impl.h"
+
+static FILE *const dummy_file = 0;
+weak_alias(dummy_file, __stdin_used);
+weak_alias(dummy_file, __stdout_used);
+weak_alias(dummy_file, __stderr_used);
+
+static void close_file(FILE *f)
+{
+	if (!f) return;
+	FFINALLOCK(f);
+	if (f->wpos > f->wbase) f->write(f, 0, 0);
+	if (f->rpos < f->rend) f->seek(f, f->rpos-f->rend, SEEK_CUR);
+}
+
+void __stdio_exit(void)
+{
+	FILE *f;
+	OFLLOCK();
+	for (f=libc.ofl_head; f; f=f->next) close_file(f);
+	close_file(__stdin_used);
+	close_file(__stdout_used);
+}
diff --git a/libc/stdio/__stdio_read.c b/libc/stdio/__stdio_read.c
new file mode 100644
index 0000000000000000000000000000000000000000..3abf4a61b306ae815cfa521e4ccb90bf17708342
--- /dev/null
+++ b/libc/stdio/__stdio_read.c
@@ -0,0 +1,41 @@
+#include "stdio_impl.h"
+#include <sys/uio.h>
+#include <pthread.h>
+
+#include "pthread_stubs.h"
+
+#if 0
+static void cleanup(void *p)
+{
+	FILE *f = p;
+	if (!f->lockcount) __unlockfile(f);
+}
+#endif
+
+size_t __stdio_read(FILE *f, unsigned char *buf, size_t len)
+{
+	struct iovec iov[2] = {
+		{ .iov_base = buf, .iov_len = len - !!f->buf_size },
+		{ .iov_base = f->buf, .iov_len = f->buf_size }
+	};
+	ssize_t cnt;
+
+	if (libc.main_thread) {
+		pthread_cleanup_push(cleanup, f);
+		cnt = readv(f->fd, iov, 2);
+		pthread_cleanup_pop(0);
+	} else {
+		cnt = readv(f->fd, iov, 2);
+	}
+	if (cnt <= 0) {
+		f->flags |= F_EOF ^ ((F_ERR^F_EOF) & cnt);
+		f->rpos = f->rend = 0;
+		return cnt;
+	}
+	if (cnt <= iov[0].iov_len) return cnt;
+	cnt -= iov[0].iov_len;
+	f->rpos = f->buf;
+	f->rend = f->buf + cnt;
+	if (f->buf_size) buf[len-1] = *f->rpos++;
+	return len;
+}
diff --git a/libc/stdio/__stdio_seek.c b/libc/stdio/__stdio_seek.c
new file mode 100644
index 0000000000000000000000000000000000000000..e51f4a1239d4b89fcf411f9e94be1d04b4d469bc
--- /dev/null
+++ b/libc/stdio/__stdio_seek.c
@@ -0,0 +1,7 @@
+#include <unistd.h>
+#include "stdio_impl.h"
+
+off_t __stdio_seek(FILE *f, off_t off, int whence)
+{
+	return lseek(f->fd, off, whence);
+}
diff --git a/libc/stdio/__stdio_write.c b/libc/stdio/__stdio_write.c
new file mode 100644
index 0000000000000000000000000000000000000000..523b72616a5574d7613ff7de0c2042a5930bbfc7
--- /dev/null
+++ b/libc/stdio/__stdio_write.c
@@ -0,0 +1,53 @@
+#include "stdio_impl.h"
+#include <sys/uio.h>
+#include <pthread.h>
+#include "pthread_stubs.h"
+
+#if 0
+static void cleanup(void *p)
+{
+	FILE *f = p;
+	if (!f->lockcount) __unlockfile(f);
+}
+#endif
+
+size_t __stdio_write(FILE *f, const unsigned char *buf, size_t len)
+{
+	struct iovec iovs[2] = {
+		{ .iov_base = f->wbase, .iov_len = f->wpos-f->wbase },
+		{ .iov_base = (void *)buf, .iov_len = len }
+	};
+	struct iovec *iov = iovs;
+	size_t rem = iov[0].iov_len + iov[1].iov_len;
+	int iovcnt = 2;
+	ssize_t cnt;
+	for (;;) {
+		if (libc.main_thread) {
+			pthread_cleanup_push(cleanup, f);
+			cnt = writev(f->fd, iov, iovcnt);
+			pthread_cleanup_pop(0);
+		} else {
+			cnt = writev(f->fd, iov, iovcnt);
+		}
+		if (cnt == rem) {
+			f->wend = f->buf + f->buf_size;
+			f->wpos = f->wbase = f->buf;
+			return len;
+		}
+		if (cnt < 0) {
+			f->wpos = f->wbase = f->wend = 0;
+			f->flags |= F_ERR;
+			return iovcnt == 2 ? 0 : len-iov[0].iov_len;
+		}
+		rem -= cnt;
+		if (cnt > iov[0].iov_len) {
+			f->wpos = f->wbase = f->buf;
+			cnt -= iov[0].iov_len;
+			iov++; iovcnt--;
+		} else if (iovcnt == 2) {
+			f->wbase += cnt;
+		}
+		iov[0].iov_base = (char *)iov[0].iov_base + cnt;
+		iov[0].iov_len -= cnt;
+	}
+}
diff --git a/libc/stdio/__stdout_write.c b/libc/stdio/__stdout_write.c
new file mode 100644
index 0000000000000000000000000000000000000000..b7f56843f8683d3e2a02be7af1a7e758123d67f4
--- /dev/null
+++ b/libc/stdio/__stdout_write.c
@@ -0,0 +1,12 @@
+#include "stdio_impl.h"
+#include <termios.h>
+#include <sys/ioctl.h>
+
+size_t __stdout_write(FILE *f, const unsigned char *buf, size_t len)
+{
+	struct termios tio;
+	f->write = __stdio_write;
+	if (!(f->flags & F_SVB) && ioctl(f->fd, TCGETS, &tio))
+		f->lbf = -1;
+	return __stdio_write(f, buf, len);
+}
diff --git a/libc/stdio/__string_read.c b/libc/stdio/__string_read.c
new file mode 100644
index 0000000000000000000000000000000000000000..7b50a7e1154224a40ddcbb204a429eb74380ffc9
--- /dev/null
+++ b/libc/stdio/__string_read.c
@@ -0,0 +1,16 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+size_t __string_read(FILE *f, unsigned char *buf, size_t len)
+{
+	char *src = f->cookie;
+	size_t k = len+256;
+	char *end = memchr(src, 0, k);
+	if (end) k = end-src;
+	if (k < len) len = k;
+	memcpy(buf, src, len);
+	f->rpos = (void *)(src+len);
+	f->rend = (void *)(src+k);
+	f->cookie = src+k;
+	return len;
+}
diff --git a/libc/stdio/__toread.c b/libc/stdio/__toread.c
new file mode 100644
index 0000000000000000000000000000000000000000..fe0168b1129d0a0316fa25d943cc8a1b9bf6c4ff
--- /dev/null
+++ b/libc/stdio/__toread.c
@@ -0,0 +1,24 @@
+#include "stdio_impl.h"
+
+int __toread(FILE *f)
+{
+	f->mode |= f->mode-1;
+	if (f->wpos > f->buf) f->write(f, 0, 0);
+	f->wpos = f->wbase = f->wend = 0;
+	if (f->flags & (F_EOF|F_NORD)) {
+		if (f->flags & F_NORD) f->flags |= F_ERR;
+		return EOF;
+	}
+	f->rpos = f->rend = f->buf;
+	return 0;
+}
+
+static const int dummy = 0;
+weak_alias(dummy, __towrite_used);
+
+void __stdio_exit(void);
+
+void __seek_on_exit()
+{
+	if (!__towrite_used) __stdio_exit();
+}
diff --git a/libc/stdio/__towrite.c b/libc/stdio/__towrite.c
new file mode 100644
index 0000000000000000000000000000000000000000..380ea396a133ca81ba230b2e45186aed5da2775f
--- /dev/null
+++ b/libc/stdio/__towrite.c
@@ -0,0 +1,27 @@
+#include "stdio_impl.h"
+
+int __towrite(FILE *f)
+{
+	f->mode |= f->mode-1;
+	if (f->flags & (F_NOWR)) {
+		f->flags |= F_ERR;
+		return EOF;
+	}
+	/* Clear read buffer (easier than summoning nasal demons) */
+	f->rpos = f->rend = 0;
+
+	/* Activate write through the buffer. */
+	f->wpos = f->wbase = f->buf;
+	f->wend = f->buf + f->buf_size;
+
+	return 0;
+}
+
+const int __towrite_used = 1;
+
+void __stdio_exit(void);
+
+void __flush_on_exit()
+{
+	__stdio_exit();
+}
diff --git a/libc/stdio/__uflow.c b/libc/stdio/__uflow.c
new file mode 100644
index 0000000000000000000000000000000000000000..e28922c2ff461a960c37501d6cbe298fe8ca68f4
--- /dev/null
+++ b/libc/stdio/__uflow.c
@@ -0,0 +1,11 @@
+#include "stdio_impl.h"
+
+/* This function will never be called if there is already data
+ * buffered for reading. Thus we can get by with very few branches. */
+
+int __uflow(FILE *f)
+{
+	unsigned char c;
+	if ((f->rend || !__toread(f)) && f->read(f, &c, 1)==1) return c;
+	return EOF;
+}
diff --git a/libc/stdio/asprintf.c b/libc/stdio/asprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..4ec83534e05827134f2ef3ce888bf76da2075972
--- /dev/null
+++ b/libc/stdio/asprintf.c
@@ -0,0 +1,13 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdarg.h>
+
+int asprintf(char **s, const char *fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vasprintf(s, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/clearerr.c b/libc/stdio/clearerr.c
new file mode 100644
index 0000000000000000000000000000000000000000..3bf94d30795d76d9d408000ac3f911f16090437f
--- /dev/null
+++ b/libc/stdio/clearerr.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+
+void clearerr(FILE *f)
+{
+	FLOCK(f);
+	f->flags &= ~(F_EOF|F_ERR);
+	FUNLOCK(f);
+}
+
+weak_alias(clearerr, clearerr_unlocked);
diff --git a/libc/stdio/dprintf.c b/libc/stdio/dprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..93082ee79cf9df348e40c3ba5b6ecf159b637beb
--- /dev/null
+++ b/libc/stdio/dprintf.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include <stdarg.h>
+
+int dprintf(int fd, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vdprintf(fd, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/ext.c b/libc/stdio/ext.c
new file mode 100644
index 0000000000000000000000000000000000000000..3baede74cb284636b96e6dfbe9d6c4c5f9961fdd
--- /dev/null
+++ b/libc/stdio/ext.c
@@ -0,0 +1,57 @@
+#define _GNU_SOURCE
+#include "stdio_impl.h"
+#include "stdio_ext.h"
+
+void _flushlbf(void)
+{
+	fflush(0);
+}
+
+int __fsetlocking(FILE *f, int type)
+{
+	return 0;
+}
+
+int __fwriting(FILE *f)
+{
+	return (f->flags & F_NORD) || f->wend;
+}
+
+int __freading(FILE *f)
+{
+	return (f->flags & F_NOWR) || f->rend;
+}
+
+int __freadable(FILE *f)
+{
+	return !(f->flags & F_NORD);
+}
+
+int __fwritable(FILE *f)
+{
+	return !(f->flags & F_NOWR);
+}
+
+int __flbf(FILE *f)
+{
+	return f->lbf >= 0;
+}
+
+size_t __fbufsize(FILE *f)
+{
+	return f->buf_size;
+}
+
+size_t __fpending(FILE *f)
+{
+	return f->wend ? f->wpos - f->wbase : 0;
+}
+
+int __fpurge(FILE *f)
+{
+	f->wpos = f->wbase = f->wend = 0;
+	f->rpos = f->rend = 0;
+	return 0;
+}
+
+weak_alias(__fpurge, fpurge);
diff --git a/libc/stdio/ext2.c b/libc/stdio/ext2.c
new file mode 100644
index 0000000000000000000000000000000000000000..f359be9af7622dbcadc42b2372839136970732a9
--- /dev/null
+++ b/libc/stdio/ext2.c
@@ -0,0 +1,24 @@
+#include "stdio_impl.h"
+
+size_t __freadahead(FILE *f)
+{
+	return f->rend - f->rpos;
+}
+
+const char *__freadptr(FILE *f, size_t *sizep)
+{
+	size_t size = f->rend - f->rpos;
+	if (!size) return 0;
+	*sizep = size;
+	return (const char *)f->rpos;
+}
+
+void __freadptrinc(FILE *f, size_t inc)
+{
+	f->rpos += inc;
+}
+
+void __fseterr(FILE *f)
+{
+	f->flags |= F_ERR;
+}
diff --git a/libc/stdio/fclose.c b/libc/stdio/fclose.c
new file mode 100644
index 0000000000000000000000000000000000000000..6879cd1e2ce1ac07ddcc03e0dc43e0f8f95da6b6
--- /dev/null
+++ b/libc/stdio/fclose.c
@@ -0,0 +1,26 @@
+#include <stdlib.h>
+#include "stdio_impl.h"
+
+int fclose(FILE *f)
+{
+	int r;
+	int perm;
+
+	FFINALLOCK(f);
+
+	if (!(perm = f->flags & F_PERM)) {
+		OFLLOCK();
+		if (f->prev) f->prev->next = f->next;
+		if (f->next) f->next->prev = f->prev;
+		if (libc.ofl_head == f) libc.ofl_head = f->next;
+		OFLUNLOCK();
+	}
+
+	r = fflush(f);
+	r |= f->close(f);
+
+	if (f->getln_buf) free(f->getln_buf);
+	if (!perm) free(f);
+	
+	return r;
+}
diff --git a/libc/stdio/feof.c b/libc/stdio/feof.c
new file mode 100644
index 0000000000000000000000000000000000000000..56da6b917c0af7913ec18f51288eccef822d763c
--- /dev/null
+++ b/libc/stdio/feof.c
@@ -0,0 +1,14 @@
+#include "stdio_impl.h"
+
+#undef feof
+
+int feof(FILE *f)
+{
+	FLOCK(f);
+	int ret = !!(f->flags & F_EOF);
+	FUNLOCK(f);
+	return ret;
+}
+
+weak_alias(feof, feof_unlocked);
+weak_alias(feof, _IO_feof_unlocked);
diff --git a/libc/stdio/ferror.c b/libc/stdio/ferror.c
new file mode 100644
index 0000000000000000000000000000000000000000..d692eed9418ea1f0cf36c948bacad20d6afc526c
--- /dev/null
+++ b/libc/stdio/ferror.c
@@ -0,0 +1,14 @@
+#include "stdio_impl.h"
+
+#undef ferror
+
+int ferror(FILE *f)
+{
+	FLOCK(f);
+	int ret = !!(f->flags & F_ERR);
+	FUNLOCK(f);
+	return ret;
+}
+
+weak_alias(ferror, ferror_unlocked);
+weak_alias(ferror, _IO_ferror_unlocked);
diff --git a/libc/stdio/fflush.c b/libc/stdio/fflush.c
new file mode 100644
index 0000000000000000000000000000000000000000..af7095033bca73c25a5488ebc2769207e5483666
--- /dev/null
+++ b/libc/stdio/fflush.c
@@ -0,0 +1,49 @@
+#include "stdio_impl.h"
+
+static int __fflush_unlocked(FILE *f)
+{
+	/* If writing, flush output */
+	if (f->wpos > f->wbase) {
+		f->write(f, 0, 0);
+		if (!f->wpos) return EOF;
+	}
+
+	/* If reading, sync position, per POSIX */
+	if (f->rpos < f->rend) f->seek(f, f->rpos-f->rend, SEEK_CUR);
+
+	/* Clear read and write modes */
+	f->wpos = f->wbase = f->wend = 0;
+	f->rpos = f->rend = 0;
+
+	return 0;
+}
+
+/* stdout.c will override this if linked */
+static FILE *const dummy = 0;
+weak_alias(dummy, __stdout_used);
+
+int fflush(FILE *f)
+{
+	int r;
+
+	if (f) {
+		FLOCK(f);
+		r = __fflush_unlocked(f);
+		FUNLOCK(f);
+		return r;
+	}
+
+	r = __stdout_used ? fflush(__stdout_used) : 0;
+
+	OFLLOCK();
+	for (f=libc.ofl_head; f; f=f->next) {
+		FLOCK(f);
+		if (f->wpos > f->wbase) r |= __fflush_unlocked(f);
+		FUNLOCK(f);
+	}
+	OFLUNLOCK();
+	
+	return r;
+}
+
+weak_alias(__fflush_unlocked, fflush_unlocked);
diff --git a/libc/stdio/fgetc.c b/libc/stdio/fgetc.c
new file mode 100644
index 0000000000000000000000000000000000000000..e122416406d8c8351b29b9bde71573dd355f894d
--- /dev/null
+++ b/libc/stdio/fgetc.c
@@ -0,0 +1,11 @@
+#include "stdio_impl.h"
+
+int fgetc(FILE *f)
+{
+	int c;
+	if (f->lock < 0 || !__lockfile(f))
+		return getc_unlocked(f);
+	c = getc_unlocked(f);
+	__unlockfile(f);
+	return c;
+}
diff --git a/libc/stdio/fgetln.c b/libc/stdio/fgetln.c
new file mode 100644
index 0000000000000000000000000000000000000000..a2e4bd3cc5bf1c1e9aa2bc927b88cdc02c02fba5
--- /dev/null
+++ b/libc/stdio/fgetln.c
@@ -0,0 +1,20 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+char *fgetln(FILE *f, size_t *plen)
+{
+	char *ret = 0, *z;
+	ssize_t l;
+	FLOCK(f);
+	ungetc(getc_unlocked(f), f);
+	if ((z=memchr(f->rpos, '\n', f->rend - f->rpos))) {
+		ret = (char *)f->rpos;
+		*plen = ++z - ret;
+		f->rpos = (void *)z;
+	} else if ((l = getline(&f->getln_buf, (size_t[]){0}, f)) > 0) {
+		*plen = l;
+		ret = f->getln_buf;
+	}
+	FUNLOCK(f);
+	return ret;
+}
diff --git a/libc/stdio/fgetpos.c b/libc/stdio/fgetpos.c
new file mode 100644
index 0000000000000000000000000000000000000000..c3fa0eb0af42982153d5222a7b76e51f941e941e
--- /dev/null
+++ b/libc/stdio/fgetpos.c
@@ -0,0 +1,11 @@
+#include "stdio_impl.h"
+
+int fgetpos(FILE *restrict f, fpos_t *restrict pos)
+{
+	off_t off = __ftello(f);
+	if (off < 0) return -1;
+	*(off_t *)pos = off;
+	return 0;
+}
+
+LFS64(fgetpos);
diff --git a/libc/stdio/fgets.c b/libc/stdio/fgets.c
new file mode 100644
index 0000000000000000000000000000000000000000..b01a4187037d81e6457e473c4e682e24787c9021
--- /dev/null
+++ b/libc/stdio/fgets.c
@@ -0,0 +1,44 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+#define MIN(a,b) ((a)<(b) ? (a) : (b))
+
+char *fgets(char *restrict s, int n, FILE *restrict f)
+{
+	char *p = s;
+	unsigned char *z;
+	size_t k;
+	int c;
+
+	if (n--<=1) {
+		if (n) return 0;
+		*s = 0;
+		return s;
+	}
+
+	FLOCK(f);
+
+	while (n) {
+		z = memchr(f->rpos, '\n', f->rend - f->rpos);
+		k = z ? z - f->rpos + 1 : f->rend - f->rpos;
+		k = MIN(k, n);
+		memcpy(p, f->rpos, k);
+		f->rpos += k;
+		p += k;
+		n -= k;
+		if (z || !n) break;
+		if ((c = getc_unlocked(f)) < 0) {
+			if (p==s || !feof(f)) s = 0;
+			break;
+		}
+		n--;
+		if ((*p++ = c) == '\n') break;
+	}
+	*p = 0;
+
+	FUNLOCK(f);
+
+	return s;
+}
+
+weak_alias(fgets, fgets_unlocked);
diff --git a/libc/stdio/fgetwc.c b/libc/stdio/fgetwc.c
new file mode 100644
index 0000000000000000000000000000000000000000..8626d54caa5dba9a5513da8ffaf180652443bf12
--- /dev/null
+++ b/libc/stdio/fgetwc.c
@@ -0,0 +1,52 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+#include <errno.h>
+
+wint_t __fgetwc_unlocked(FILE *f)
+{
+	mbstate_t st = { 0 };
+	wchar_t wc;
+	int c;
+	unsigned char b;
+	size_t l;
+
+	f->mode |= f->mode+1;
+
+	/* Convert character from buffer if possible */
+	if (f->rpos < f->rend) {
+		l = mbrtowc(&wc, (void *)f->rpos, f->rend - f->rpos, &st);
+		if (l+2 >= 2) {
+			f->rpos += l + !l; /* l==0 means 1 byte, null */
+			return wc;
+		}
+		if (l == -1) {
+			f->rpos++;
+			return WEOF;
+		}
+	} else l = -2;
+
+	/* Convert character byte-by-byte */
+	while (l == -2) {
+		b = c = getc_unlocked(f);
+		if (c < 0) {
+			if (!mbsinit(&st)) errno = EILSEQ;
+			return WEOF;
+		}
+		l = mbrtowc(&wc, (void *)&b, 1, &st);
+		if (l == -1) return WEOF;
+	}
+
+	return wc;
+}
+
+wint_t fgetwc(FILE *f)
+{
+	wint_t c;
+	FLOCK(f);
+	c = __fgetwc_unlocked(f);
+	FUNLOCK(f);
+	return c;
+}
+
+weak_alias(__fgetwc_unlocked, fgetwc_unlocked);
+weak_alias(__fgetwc_unlocked, getwc_unlocked);
diff --git a/libc/stdio/fgetws.c b/libc/stdio/fgetws.c
new file mode 100644
index 0000000000000000000000000000000000000000..195cb4355a14b10b05b0b50cf293456b5b7b4f75
--- /dev/null
+++ b/libc/stdio/fgetws.c
@@ -0,0 +1,28 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+wint_t __fgetwc_unlocked(FILE *);
+
+wchar_t *fgetws(wchar_t *restrict s, int n, FILE *restrict f)
+{
+	wchar_t *p = s;
+
+	if (!n--) return s;
+
+	FLOCK(f);
+
+	for (; n; n--) {
+		wint_t c = __fgetwc_unlocked(f);
+		if (c == WEOF) break;
+		*p++ = c;
+		if (c == '\n') break;
+	}
+	*p = 0;
+	if (ferror(f)) p = s;
+
+	FUNLOCK(f);
+
+	return (p == s) ? NULL : s;
+}
+
+weak_alias(fgetws, fgetws_unlocked);
diff --git a/libc/stdio/fileno.c b/libc/stdio/fileno.c
new file mode 100644
index 0000000000000000000000000000000000000000..ba7f9391b1ec9baa6023f9a66f569b46a1f85ba2
--- /dev/null
+++ b/libc/stdio/fileno.c
@@ -0,0 +1,13 @@
+#include "stdio_impl.h"
+
+int fileno(FILE *f)
+{
+	/* f->fd never changes, but the lock must be obtained and released
+	 * anyway since this function cannot return while another thread
+	 * holds the lock. */
+	FLOCK(f);
+	FUNLOCK(f);
+	return f->fd;
+}
+
+weak_alias(fileno, fileno_unlocked);
diff --git a/libc/stdio/flockfile.c b/libc/stdio/flockfile.c
new file mode 100644
index 0000000000000000000000000000000000000000..a196c1efe0af11663f5e0537a0de1db02c3982ef
--- /dev/null
+++ b/libc/stdio/flockfile.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+#include "pthread_impl.h"
+
+void flockfile(FILE *f)
+{
+	while (ftrylockfile(f)) {
+		int owner = f->lock;
+		if (owner) __wait(&f->lock, &f->waiters, owner, 1);
+	}
+}
diff --git a/libc/stdio/fmemopen.c b/libc/stdio/fmemopen.c
new file mode 100644
index 0000000000000000000000000000000000000000..67cabf5b7f38bd23d0b680f932b9e4d1bdd4764a
--- /dev/null
+++ b/libc/stdio/fmemopen.c
@@ -0,0 +1,121 @@
+#include "stdio_impl.h"
+#include <errno.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+struct cookie {
+	size_t pos, len, size;
+	unsigned char *buf;
+	int mode;
+};
+
+static off_t mseek(FILE *f, off_t off, int whence)
+{
+	ssize_t base;
+	struct cookie *c = f->cookie;
+	if (whence>2U) {
+fail:
+		errno = EINVAL;
+		return -1;
+	}
+	base = (size_t [3]){0, c->pos, c->len}[whence];
+	if (off < -base || off > (ssize_t)c->size-base) goto fail;
+	return c->pos = base+off;
+}
+
+static size_t mread(FILE *f, unsigned char *buf, size_t len)
+{
+	struct cookie *c = f->cookie;
+	size_t rem = c->len - c->pos;
+	if (c->pos > c->len) rem = 0;
+	if (len > rem) {
+		len = rem;
+		f->flags |= F_EOF;
+	}
+	memcpy(buf, c->buf+c->pos, len);
+	c->pos += len;
+	rem -= len;
+	if (rem > f->buf_size) rem = f->buf_size;
+	f->rpos = f->buf;
+	f->rend = f->buf + rem;
+	memcpy(f->rpos, c->buf+c->pos, rem);
+	c->pos += rem;
+	return len;
+}
+
+static size_t mwrite(FILE *f, const unsigned char *buf, size_t len)
+{
+	struct cookie *c = f->cookie;
+	size_t rem;
+	size_t len2 = f->wpos - f->wbase;
+	if (len2) {
+		f->wpos = f->wbase;
+		if (mwrite(f, f->wpos, len2) < len2) return 0;
+	}
+	if (c->mode == 'a') c->pos = c->len;
+	rem = c->size - c->pos;
+	if (len > rem) len = rem;
+	memcpy(c->buf+c->pos, buf, len);
+	c->pos += len;
+	if (c->pos > c->len) {
+		c->len = c->pos;
+		if (c->len < c->size) c->buf[c->len] = 0;
+		else if ((f->flags&F_NORD) && c->size) c->buf[c->size-1] = 0;
+	}
+	return len;
+}
+
+static int mclose(FILE *m)
+{
+	return 0;
+}
+
+FILE *fmemopen(void *restrict buf, size_t size, const char *restrict mode)
+{
+	FILE *f;
+	struct cookie *c;
+	int plus = !!strchr(mode, '+');
+	
+	if (!size || !strchr("rwa", *mode)) {
+		errno = EINVAL;
+		return 0;
+	}
+
+	if (!buf && size > SIZE_MAX-sizeof(FILE)-BUFSIZ-UNGET) {
+		errno = ENOMEM;
+		return 0;
+	}
+
+	f = calloc(sizeof *f + sizeof *c + UNGET + BUFSIZ + (buf?0:size), 1);
+	if (!f) return 0;
+	f->cookie = c = (void *)(f+1);
+	f->fd = -1;
+	f->lbf = EOF;
+	f->buf = (unsigned char *)(c+1) + UNGET;
+	f->buf_size = BUFSIZ;
+	if (!buf) buf = f->buf + BUFSIZ;
+
+	c->buf = buf;
+	c->size = size;
+	c->mode = *mode;
+	
+	if (!plus) f->flags = (*mode == 'r') ? F_NOWR : F_NORD;
+	if (*mode == 'r') c->len = size;
+	else if (*mode == 'a') c->len = c->pos = strnlen(buf, size);
+
+	f->read = mread;
+	f->write = mwrite;
+	f->seek = mseek;
+	f->close = mclose;
+
+	if (!libc.threaded) f->lock = -1;
+
+	OFLLOCK();
+	f->next = libc.ofl_head;
+	if (libc.ofl_head) libc.ofl_head->prev = f;
+	libc.ofl_head = f;
+	OFLUNLOCK();
+
+	return f;
+}
diff --git a/libc/stdio/fopen.c b/libc/stdio/fopen.c
new file mode 100644
index 0000000000000000000000000000000000000000..83452407b5ce82ef3849916c9691a967a20158d9
--- /dev/null
+++ b/libc/stdio/fopen.c
@@ -0,0 +1,32 @@
+#include "stdio_impl.h"
+#include <fcntl.h>
+#include <string.h>
+#include <unistd.h>
+#include <errno.h>
+
+FILE *fopen(const char *restrict filename, const char *restrict mode)
+{
+	FILE *f;
+	int fd;
+	int flags;
+
+	/* Check for valid initial mode character */
+	if (!strchr("rwa", *mode)) {
+		errno = EINVAL;
+		return 0;
+	}
+
+	/* Compute the flags to pass to open() */
+	flags = __fmodeflags(mode);
+
+	fd = open(filename, flags|O_LARGEFILE, 0666);
+	if (fd < 0) return 0;
+
+	f = __fdopen(fd, mode);
+	if (f) return f;
+
+	close(fd);
+	return 0;
+}
+
+LFS64(fopen);
diff --git a/libc/stdio/fprintf.c b/libc/stdio/fprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..948743f7c8b78821645f5eecb7a45f2285d3b78d
--- /dev/null
+++ b/libc/stdio/fprintf.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include <stdarg.h>
+
+int fprintf(FILE *restrict f, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfprintf(f, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/fputc.c b/libc/stdio/fputc.c
new file mode 100644
index 0000000000000000000000000000000000000000..92762c98f8ccf28312140d0df717441483e15e79
--- /dev/null
+++ b/libc/stdio/fputc.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+
+int fputc(int c, FILE *f)
+{
+	if (f->lock < 0 || !__lockfile(f))
+		return putc_unlocked(c, f);
+	c = putc_unlocked(c, f);
+	__unlockfile(f);
+	return c;
+}
diff --git a/libc/stdio/fputs.c b/libc/stdio/fputs.c
new file mode 100644
index 0000000000000000000000000000000000000000..1112b192c06b49528862fec0168f5af2527d1886
--- /dev/null
+++ b/libc/stdio/fputs.c
@@ -0,0 +1,11 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+int fputs(const char *restrict s, FILE *restrict f)
+{
+	size_t l = strlen(s);
+	if (!l) return 0;
+	return (int)fwrite(s, l, 1, f) - 1;
+}
+
+weak_alias(fputs, fputs_unlocked);
diff --git a/libc/stdio/fputwc.c b/libc/stdio/fputwc.c
new file mode 100644
index 0000000000000000000000000000000000000000..7b621dd2ff9a868cd08e3beeeff3f53887dc89d7
--- /dev/null
+++ b/libc/stdio/fputwc.c
@@ -0,0 +1,35 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+#include <limits.h>
+#include <ctype.h>
+
+wint_t __fputwc_unlocked(wchar_t c, FILE *f)
+{
+	char mbc[MB_LEN_MAX];
+	int l;
+
+	f->mode |= f->mode+1;
+
+	if (isascii(c)) {
+		c = putc_unlocked(c, f);
+	} else if (f->wpos + MB_LEN_MAX < f->wend) {
+		l = wctomb((void *)f->wpos, c);
+		if (l < 0) c = WEOF;
+		else f->wpos += l;
+	} else {
+		l = wctomb(mbc, c);
+		if (l < 0 || __fwritex((void *)mbc, l, f) < l) c = WEOF;
+	}
+	return c;
+}
+
+wint_t fputwc(wchar_t c, FILE *f)
+{
+	FLOCK(f);
+	c = __fputwc_unlocked(c, f);
+	FUNLOCK(f);
+	return c;
+}
+
+weak_alias(__fputwc_unlocked, fputwc_unlocked);
+weak_alias(__fputwc_unlocked, putwc_unlocked);
diff --git a/libc/stdio/fputws.c b/libc/stdio/fputws.c
new file mode 100644
index 0000000000000000000000000000000000000000..5723cbcd7a573a2879f25339be378dc817388025
--- /dev/null
+++ b/libc/stdio/fputws.c
@@ -0,0 +1,24 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+int fputws(const wchar_t *restrict ws, FILE *restrict f)
+{
+	unsigned char buf[BUFSIZ];
+	size_t l=0;
+
+	FLOCK(f);
+
+	f->mode |= f->mode+1;
+
+	while (ws && (l = wcsrtombs((void *)buf, (void*)&ws, sizeof buf, 0))+1 > 1)
+		if (__fwritex(buf, l, f) < l) {
+			FUNLOCK(f);
+			return -1;
+		}
+
+	FUNLOCK(f);
+
+	return l; /* 0 or -1 */
+}
+
+weak_alias(fputws, fputws_unlocked);
diff --git a/libc/stdio/fread.c b/libc/stdio/fread.c
new file mode 100644
index 0000000000000000000000000000000000000000..c461256c3b0de4d6af84c0df426710fa121ddc06
--- /dev/null
+++ b/libc/stdio/fread.c
@@ -0,0 +1,38 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+#define MIN(a,b) ((a)<(b) ? (a) : (b))
+
+size_t fread(void *restrict destv, size_t size, size_t nmemb, FILE *restrict f)
+{
+	unsigned char *dest = destv;
+	size_t len = size*nmemb, l = len, k;
+
+	/* Never touch the file if length is zero.. */
+	if (!l) return 0;
+
+	FLOCK(f);
+
+	if (f->rend - f->rpos > 0) {
+		/* First exhaust the buffer. */
+		k = MIN(f->rend - f->rpos, l);
+		memcpy(dest, f->rpos, k);
+		f->rpos += k;
+		dest += k;
+		l -= k;
+	}
+	
+	/* Read the remainder directly */
+	for (; l; l-=k, dest+=k) {
+		k = __toread(f) ? 0 : f->read(f, dest, l);
+		if (k+1<=1) {
+			FUNLOCK(f);
+			return (len-l)/size;
+		}
+	}
+
+	FUNLOCK(f);
+	return nmemb;
+}
+
+weak_alias(fread, fread_unlocked);
diff --git a/libc/stdio/freopen.c b/libc/stdio/freopen.c
new file mode 100644
index 0000000000000000000000000000000000000000..8ae1e992b50837884ec150b0a51905b08b1c2a38
--- /dev/null
+++ b/libc/stdio/freopen.c
@@ -0,0 +1,55 @@
+#include "stdio_impl.h"
+#include <stdlib.h>
+#include <fcntl.h>
+
+/* The basic idea of this implementation is to open a new FILE,
+ * hack the necessary parts of the new FILE into the old one, then
+ * close the new FILE. */
+
+/* Locking IS necessary because another thread may provably hold the
+ * lock, via flockfile or otherwise, when freopen is called, and in that
+ * case, freopen cannot act until the lock is released. */
+
+int dup3(int, int, int);
+
+FILE *freopen(const char *restrict filename, const char *restrict mode, FILE *restrict f)
+{
+	int fl = __fmodeflags(mode);
+	FILE *f2;
+
+	FLOCK(f);
+
+	fflush(f);
+
+	if (!filename) {
+		if (fl&O_CLOEXEC)
+			fcntl(f->fd, F_SETFD, FD_CLOEXEC);
+		fl &= ~(O_CREAT|O_EXCL|O_CLOEXEC);
+		if (fcntl(f->fd, F_SETFL, fl) < 0)
+			goto fail;
+	} else {
+		f2 = fopen(filename, mode);
+		if (!f2) goto fail;
+		if (f2->fd == f->fd) f2->fd = -1; /* avoid closing in fclose */
+		else if (dup3(f2->fd, f->fd, fl&O_CLOEXEC)<0) goto fail2;
+
+		f->flags = (f->flags & F_PERM) | f2->flags;
+		f->read = f2->read;
+		f->write = f2->write;
+		f->seek = f2->seek;
+		f->close = f2->close;
+
+		fclose(f2);
+	}
+
+	FUNLOCK(f);
+	return f;
+
+fail2:
+	fclose(f2);
+fail:
+	fclose(f);
+	return NULL;
+}
+
+LFS64(freopen);
diff --git a/libc/stdio/fscanf.c b/libc/stdio/fscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..f8530dd329c8f770ca64a18dc253905ec1f9e622
--- /dev/null
+++ b/libc/stdio/fscanf.c
@@ -0,0 +1,12 @@
+#include "stdio_impl.h"
+#include <stdarg.h>
+
+int fscanf(FILE *restrict f, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfscanf(f, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/fseek.c b/libc/stdio/fseek.c
new file mode 100644
index 0000000000000000000000000000000000000000..b160b74edca0db9eeb8599a268a9ffc469d1aeb3
--- /dev/null
+++ b/libc/stdio/fseek.c
@@ -0,0 +1,43 @@
+#include "stdio_impl.h"
+
+int __fseeko_unlocked(FILE *f, off_t off, int whence)
+{
+	/* Adjust relative offset for unread data in buffer, if any. */
+	if (whence == SEEK_CUR) off -= f->rend - f->rpos;
+
+	/* Flush write buffer, and report error on failure. */
+	if (f->wpos > f->wbase) {
+		f->write(f, 0, 0);
+		if (!f->wpos) return -1;
+	}
+
+	/* Leave writing mode */
+	f->wpos = f->wbase = f->wend = 0;
+
+	/* Perform the underlying seek. */
+	if (f->seek(f, off, whence) < 0) return -1;
+
+	/* If seek succeeded, file is seekable and we discard read buffer. */
+	f->rpos = f->rend = 0;
+	f->flags &= ~F_EOF;
+	
+	return 0;
+}
+
+int __fseeko(FILE *f, off_t off, int whence)
+{
+	int result;
+	FLOCK(f);
+	result = __fseeko_unlocked(f, off, whence);
+	FUNLOCK(f);
+	return result;
+}
+
+int fseek(FILE *f, long off, int whence)
+{
+	return __fseeko(f, off, whence);
+}
+
+weak_alias(__fseeko, fseeko);
+
+LFS64(fseeko);
diff --git a/libc/stdio/fsetpos.c b/libc/stdio/fsetpos.c
new file mode 100644
index 0000000000000000000000000000000000000000..5d76c8cd5dee42c2b946774e6a0e456db7512a84
--- /dev/null
+++ b/libc/stdio/fsetpos.c
@@ -0,0 +1,8 @@
+#include "stdio_impl.h"
+
+int fsetpos(FILE *f, const fpos_t *pos)
+{
+	return __fseeko(f, *(const off_t *)pos, SEEK_SET);
+}
+
+LFS64(fsetpos);
diff --git a/libc/stdio/ftell.c b/libc/stdio/ftell.c
new file mode 100644
index 0000000000000000000000000000000000000000..82371e37b38316d8fdbdb5bf9bf69f8771f003e0
--- /dev/null
+++ b/libc/stdio/ftell.c
@@ -0,0 +1,35 @@
+#include "stdio_impl.h"
+#include <limits.h>
+#include <errno.h>
+
+off_t __ftello_unlocked(FILE *f)
+{
+	off_t pos = f->seek(f, 0, SEEK_CUR);
+	if (pos < 0) return pos;
+
+	/* Adjust for data in buffer. */
+	return pos - (f->rend - f->rpos) + (f->wpos - f->wbase);
+}
+
+off_t __ftello(FILE *f)
+{
+	off_t pos;
+	FLOCK(f);
+	pos = __ftello_unlocked(f);
+	FUNLOCK(f);
+	return pos;
+}
+
+long ftell(FILE *f)
+{
+	off_t pos = __ftello(f);
+	if (pos > LONG_MAX) {
+		errno = EOVERFLOW;
+		return -1;
+	}
+	return pos;
+}
+
+weak_alias(__ftello, ftello);
+
+LFS64(ftello);
diff --git a/libc/stdio/ftrylockfile.c b/libc/stdio/ftrylockfile.c
new file mode 100644
index 0000000000000000000000000000000000000000..eef4e2502e56af1a6ed1f8d9a08f898bab5ce856
--- /dev/null
+++ b/libc/stdio/ftrylockfile.c
@@ -0,0 +1,19 @@
+#include "stdio_impl.h"
+#include "pthread_impl.h"
+#include <limits.h>
+
+int ftrylockfile(FILE *f)
+{
+	int tid = pthread_self()->tid;
+	if (f->lock == tid) {
+		if (f->lockcount == LONG_MAX)
+			return -1;
+		f->lockcount++;
+		return 0;
+	}
+	if (f->lock < 0) f->lock = 0;
+	if (f->lock || a_cas(&f->lock, 0, tid))
+		return -1;
+	f->lockcount = 1;
+	return 0;
+}
diff --git a/libc/stdio/funlockfile.c b/libc/stdio/funlockfile.c
new file mode 100644
index 0000000000000000000000000000000000000000..f8a2a071e64596b00e52940d47d94ca7ec2bee80
--- /dev/null
+++ b/libc/stdio/funlockfile.c
@@ -0,0 +1,7 @@
+#include "stdio_impl.h"
+#include "pthread_impl.h"
+
+void funlockfile(FILE *f)
+{
+	if (!--f->lockcount) __unlockfile(f);
+}
diff --git a/libc/stdio/fwide.c b/libc/stdio/fwide.c
new file mode 100644
index 0000000000000000000000000000000000000000..48480685aa4b63a664ccc842548aa8f663c9b662
--- /dev/null
+++ b/libc/stdio/fwide.c
@@ -0,0 +1,12 @@
+#include "stdio_impl.h"
+
+#define SH (8*sizeof(int)-1)
+#define NORMALIZE(x) ((x)>>SH | -((-(x))>>SH))
+
+int fwide(FILE *f, int mode)
+{
+	FLOCK(f);
+	if (!f->mode) mode = f->mode = NORMALIZE(mode);
+	FUNLOCK(f);
+	return mode;
+}
diff --git a/libc/stdio/fwprintf.c b/libc/stdio/fwprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..9ce4f0102e1b57e7224c9c11c47a044373be2ac9
--- /dev/null
+++ b/libc/stdio/fwprintf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int fwprintf(FILE *restrict f, const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfwprintf(f, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/fwrite.c b/libc/stdio/fwrite.c
new file mode 100644
index 0000000000000000000000000000000000000000..d5f6542d6bebe32ec6dac9ac319e8eaf430dfcd4
--- /dev/null
+++ b/libc/stdio/fwrite.c
@@ -0,0 +1,38 @@
+#include "stdio_impl.h"
+#include <string.h>
+
+size_t __fwritex(const unsigned char *restrict s, size_t l, FILE *restrict f)
+{
+	size_t i=0;
+
+	if (!f->wend && __towrite(f)) return 0;
+
+	if (l > f->wend - f->wpos) return f->write(f, s, l);
+
+	if (f->lbf >= 0) {
+		/* Match /^(.*\n|)/ */
+		for (i=l; i && s[i-1] != '\n'; i--);
+		if (i) {
+			if (f->write(f, s, i) < i)
+				return i;
+			s += i;
+			l -= i;
+		}
+	}
+
+	memcpy(f->wpos, s, l);
+	f->wpos += l;
+	return l+i;
+}
+
+size_t fwrite(const void *restrict src, size_t size, size_t nmemb, FILE *restrict f)
+{
+	size_t k, l = size*nmemb;
+	if (!l) return l;
+	FLOCK(f);
+	k = __fwritex(src, l, f);
+	FUNLOCK(f);
+	return k==l ? nmemb : k/size;
+}
+
+weak_alias(fwrite, fwrite_unlocked);
diff --git a/libc/stdio/fwscanf.c b/libc/stdio/fwscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..2f30dab4718dfa7357f4665ff4d31d542f7b9424
--- /dev/null
+++ b/libc/stdio/fwscanf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int fwscanf(FILE *restrict f, const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfwscanf(f, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/getc.c b/libc/stdio/getc.c
new file mode 100644
index 0000000000000000000000000000000000000000..b3f351d1d7e45e5f4ef9ad91c868981e6aaf1929
--- /dev/null
+++ b/libc/stdio/getc.c
@@ -0,0 +1,13 @@
+#include "stdio_impl.h"
+
+int getc(FILE *f)
+{
+	int c;
+	if (f->lock < 0 || !__lockfile(f))
+		return getc_unlocked(f);
+	c = getc_unlocked(f);
+	__unlockfile(f);
+	return c;
+}
+
+weak_alias(getc, _IO_getc);
diff --git a/libc/stdio/getc_unlocked.c b/libc/stdio/getc_unlocked.c
new file mode 100644
index 0000000000000000000000000000000000000000..b38dad1672b8ae33bfeb1ee7d4a21e9d84c208ad
--- /dev/null
+++ b/libc/stdio/getc_unlocked.c
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+
+int (getc_unlocked)(FILE *f)
+{
+	return getc_unlocked(f);
+}
+
+weak_alias (getc_unlocked, fgetc_unlocked);
+weak_alias (getc_unlocked, _IO_getc_unlocked);
diff --git a/libc/stdio/getchar.c b/libc/stdio/getchar.c
new file mode 100644
index 0000000000000000000000000000000000000000..c10126581bf95d532e974fe30f6d2646a0ef8db6
--- /dev/null
+++ b/libc/stdio/getchar.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int getchar(void)
+{
+	return fgetc(stdin);
+}
diff --git a/libc/stdio/getchar_unlocked.c b/libc/stdio/getchar_unlocked.c
new file mode 100644
index 0000000000000000000000000000000000000000..355ac318d43d2371af6399bf7652d2baabf5d9b4
--- /dev/null
+++ b/libc/stdio/getchar_unlocked.c
@@ -0,0 +1,6 @@
+#include "stdio_impl.h"
+
+int getchar_unlocked(void)
+{
+	return getc_unlocked(stdin);
+}
diff --git a/libc/stdio/getdelim.c b/libc/stdio/getdelim.c
new file mode 100644
index 0000000000000000000000000000000000000000..0943b1e56dc058cdfc04e9c0b88087d87fdb41b2
--- /dev/null
+++ b/libc/stdio/getdelim.c
@@ -0,0 +1,65 @@
+#include "stdio_impl.h"
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+#include <errno.h>
+
+#define MIN(a,b) ((a)<(b) ? (a) : (b))
+
+ssize_t getdelim(char **restrict s, size_t *restrict n, int delim, FILE *restrict f)
+{
+	char *tmp;
+	unsigned char *z;
+	size_t k;
+	size_t i=0;
+	int c;
+
+	if (!n || !s) {
+		errno = EINVAL;
+		return -1;
+	}
+
+	if (!*s) *n=0;
+
+	FLOCK(f);
+
+	for (;;) {
+		z = memchr(f->rpos, delim, f->rend - f->rpos);
+		k = z ? z - f->rpos + 1 : f->rend - f->rpos;
+		if (i+k >= *n) {
+			if (k >= SIZE_MAX/2-i) goto oom;
+			*n = i+k+2;
+			if (*n < SIZE_MAX/4) *n *= 2;
+			tmp = realloc(*s, *n);
+			if (!tmp) {
+				*n = i+k+2;
+				tmp = realloc(*s, *n);
+				if (!tmp) goto oom;
+			}
+			*s = tmp;
+		}
+		memcpy(*s+i, f->rpos, k);
+		f->rpos += k;
+		i += k;
+		if (z) break;
+		if ((c = getc_unlocked(f)) == EOF) {
+			if (!i || !feof(f)) {
+				FUNLOCK(f);
+				return -1;
+			}
+			break;
+		}
+		if (((*s)[i++] = c) == delim) break;
+	}
+	(*s)[i] = 0;
+
+	FUNLOCK(f);
+
+	return i;
+oom:
+	FUNLOCK(f);
+	errno = ENOMEM;
+	return -1;
+}
+
+weak_alias(getdelim, __getdelim);
diff --git a/libc/stdio/getline.c b/libc/stdio/getline.c
new file mode 100644
index 0000000000000000000000000000000000000000..476d0b09617430764552052fc77827f14be8c8a1
--- /dev/null
+++ b/libc/stdio/getline.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+ssize_t getline(char **restrict s, size_t *restrict n, FILE *restrict f)
+{
+	return getdelim(s, n, '\n', f);
+}
diff --git a/libc/stdio/gets.c b/libc/stdio/gets.c
new file mode 100644
index 0000000000000000000000000000000000000000..6c4645e5640b7b9d4df8387346a02122dfc0f5ea
--- /dev/null
+++ b/libc/stdio/gets.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+#include <limits.h>
+#include <string.h>
+
+char *gets(char *s)
+{
+	char *ret = fgets(s, INT_MAX, stdin);
+	if (ret && s[strlen(s)-1] == '\n') s[strlen(s)-1] = 0;
+	return ret;
+}
diff --git a/libc/stdio/getw.c b/libc/stdio/getw.c
new file mode 100644
index 0000000000000000000000000000000000000000..73d2c0d5c6c0914322903e0c30e3f93c0f9336cc
--- /dev/null
+++ b/libc/stdio/getw.c
@@ -0,0 +1,8 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+
+int getw(FILE *f)
+{
+	int x;
+	return fread(&x, sizeof x, 1, f) ? x : EOF;
+}
diff --git a/libc/stdio/getwc.c b/libc/stdio/getwc.c
new file mode 100644
index 0000000000000000000000000000000000000000..a5008f0e5ce12b86e28392fe343dfce47bc2982e
--- /dev/null
+++ b/libc/stdio/getwc.c
@@ -0,0 +1,7 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+wint_t getwc(FILE *f)
+{
+	return fgetwc(f);
+}
diff --git a/libc/stdio/getwchar.c b/libc/stdio/getwchar.c
new file mode 100644
index 0000000000000000000000000000000000000000..bd89e0ec9411074489e847183b6f1aec4c6af2de
--- /dev/null
+++ b/libc/stdio/getwchar.c
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+wint_t getwchar(void)
+{
+	return fgetwc(stdin);
+}
+
+weak_alias(getwchar, getwchar_unlocked);
diff --git a/libc/stdio/open_memstream.c b/libc/stdio/open_memstream.c
new file mode 100644
index 0000000000000000000000000000000000000000..d0553d6f173a8021ef3d9b4d6003056b737cba72
--- /dev/null
+++ b/libc/stdio/open_memstream.c
@@ -0,0 +1,90 @@
+#include "stdio_impl.h"
+#include <errno.h>
+#include <limits.h>
+#include <stdlib.h>
+#include <string.h>
+
+struct cookie {
+	char **bufp;
+	size_t *sizep;
+	size_t pos;
+	char *buf;
+	size_t len;
+	size_t space;
+};
+
+static off_t ms_seek(FILE *f, off_t off, int whence)
+{
+	ssize_t base;
+	struct cookie *c = f->cookie;
+	if (whence>2U) {
+fail:
+		errno = EINVAL;
+		return -1;
+	}
+	base = (size_t [3]){0, c->pos, c->len}[whence];
+	if (off < -base || off > SSIZE_MAX-base) goto fail;
+	return c->pos = base+off;
+}
+
+static size_t ms_write(FILE *f, const unsigned char *buf, size_t len)
+{
+	struct cookie *c = f->cookie;
+	size_t len2 = f->wpos - f->wbase;
+	char *newbuf;
+	if (len2) {
+		f->wpos = f->wbase;
+		if (ms_write(f, f->wbase, len2) < len2) return 0;
+	}
+	if (len + c->pos >= c->space) {
+		len2 = 2*c->space+1 | c->pos+len+1;
+		newbuf = realloc(c->buf, len2);
+		if (!newbuf) return 0;
+		*c->bufp = c->buf = newbuf;
+		memset(c->buf + c->space, 0, len2 - c->space);
+		c->space = len2;
+	}
+	memcpy(c->buf+c->pos, buf, len);
+	c->pos += len;
+	if (c->pos >= c->len) c->len = c->pos;
+	*c->sizep = c->pos;
+	return len;
+}
+
+static int ms_close(FILE *f)
+{
+	return 0;
+}
+
+FILE *open_memstream(char **bufp, size_t *sizep)
+{
+	FILE *f;
+	struct cookie *c;
+	if (!(f=malloc(sizeof *f + sizeof *c + BUFSIZ))) return 0;
+	memset(f, 0, sizeof *f + sizeof *c);
+	f->cookie = c = (void *)(f+1);
+
+	c->bufp = bufp;
+	c->sizep = sizep;
+	c->pos = c->len = c->space = 0;
+	c->buf = 0;
+
+	f->flags = F_NORD;
+	f->fd = -1;
+	f->buf = (void *)(c+1);
+	f->buf_size = BUFSIZ;
+	f->lbf = EOF;
+	f->write = ms_write;
+	f->seek = ms_seek;
+	f->close = ms_close;
+
+	if (!libc.threaded) f->lock = -1;
+
+	OFLLOCK();
+	f->next = libc.ofl_head;
+	if (libc.ofl_head) libc.ofl_head->prev = f;
+	libc.ofl_head = f;
+	OFLUNLOCK();
+
+	return f;
+}
diff --git a/libc/stdio/open_wmemstream.c b/libc/stdio/open_wmemstream.c
new file mode 100644
index 0000000000000000000000000000000000000000..35370309d6fd2a8cdd8f91fea0c8820d57caedd7
--- /dev/null
+++ b/libc/stdio/open_wmemstream.c
@@ -0,0 +1,91 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+#include <errno.h>
+#include <limits.h>
+#include <string.h>
+
+struct cookie {
+	wchar_t **bufp;
+	size_t *sizep;
+	size_t pos;
+	wchar_t *buf;
+	size_t len;
+	size_t space;
+	mbstate_t mbs;
+};
+
+static off_t wms_seek(FILE *f, off_t off, int whence)
+{
+	ssize_t base;
+	struct cookie *c = f->cookie;
+	if (whence>2U) {
+fail:
+		errno = EINVAL;
+		return -1;
+	}
+	base = (size_t [3]){0, c->pos, c->len}[whence];
+	if (off < -base || off > SSIZE_MAX/4-base) goto fail;
+	memset(&c->mbs, 0, sizeof c->mbs);
+	return c->pos = base+off;
+}
+
+static size_t wms_write(FILE *f, const unsigned char *buf, size_t len)
+{
+	struct cookie *c = f->cookie;
+	size_t len2;
+	wchar_t *newbuf;
+	if (len + c->pos >= c->space) {
+		len2 = 2*c->space+1 | c->pos+len+1;
+		if (len2 > SSIZE_MAX/4) return 0;
+		newbuf = realloc(c->buf, len2*4);
+		if (!newbuf) return 0;
+		*c->bufp = c->buf = newbuf;
+		memset(c->buf + c->space, 0, 4*(len2 - c->space));
+		c->space = len2;
+	}
+	
+	len2 = mbsnrtowcs(c->buf+c->pos, (void *)&buf, len, c->space-c->pos, &c->mbs);
+	if (len2 == -1) return 0;
+	c->pos += len2;
+	if (c->pos >= c->len) c->len = c->pos;
+	*c->sizep = c->pos;
+	return len;
+}
+
+static int wms_close(FILE *f)
+{
+	return 0;
+}
+
+FILE *open_wmemstream(wchar_t **bufp, size_t *sizep)
+{
+	FILE *f;
+	struct cookie *c;
+	if (!(f=malloc(sizeof *f + sizeof *c))) return 0;
+	memset(f, 0, sizeof *f + sizeof *c);
+	f->cookie = c = (void *)(f+1);
+
+	c->bufp = bufp;
+	c->sizep = sizep;
+	c->pos = c->len = c->space = 0;
+	c->buf = 0;
+
+	f->flags = F_NORD;
+	f->fd = -1;
+	f->buf = (void *)(c+1);
+	f->buf_size = 0;
+	f->lbf = EOF;
+	f->write = wms_write;
+	f->seek = wms_seek;
+	f->close = wms_close;
+
+	if (!libc.threaded) f->lock = -1;
+
+	OFLLOCK();
+	f->next = libc.ofl_head;
+	if (libc.ofl_head) libc.ofl_head->prev = f;
+	libc.ofl_head = f;
+	OFLUNLOCK();
+
+	return f;
+}
diff --git a/libc/stdio/perror.c b/libc/stdio/perror.c
new file mode 100644
index 0000000000000000000000000000000000000000..1cffb7c252e3d645e898b312b37739b3af93996e
--- /dev/null
+++ b/libc/stdio/perror.c
@@ -0,0 +1,21 @@
+#include <string.h>
+#include <errno.h>
+#include "stdio_impl.h"
+
+void perror(const char *msg)
+{
+	FILE *f = stderr;
+	char *errstr = strerror(errno);
+
+	FLOCK(f);
+	
+	if (msg && *msg) {
+		fwrite(msg, strlen(msg), 1, f);
+		fputc(':', f);
+		fputc(' ', f);
+	}
+	fwrite(errstr, strlen(errstr), 1, f);
+	fputc('\n', f);
+
+	FUNLOCK(f);
+}
diff --git a/libc/stdio/printf.c b/libc/stdio/printf.c
new file mode 100644
index 0000000000000000000000000000000000000000..cebfe404fb97d465545020a76ba9b928cfcbb15a
--- /dev/null
+++ b/libc/stdio/printf.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include <stdarg.h>
+
+int printf(const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vfprintf(stdout, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/putc.c b/libc/stdio/putc.c
new file mode 100644
index 0000000000000000000000000000000000000000..fa8934969b62de4c4ca99172d13f95f13fc3e0a8
--- /dev/null
+++ b/libc/stdio/putc.c
@@ -0,0 +1,12 @@
+#include "stdio_impl.h"
+
+int putc(int c, FILE *f)
+{
+	if (f->lock < 0 || !__lockfile(f))
+		return putc_unlocked(c, f);
+	c = putc_unlocked(c, f);
+	__unlockfile(f);
+	return c;
+}
+
+weak_alias(putc, _IO_putc);
diff --git a/libc/stdio/putc_unlocked.c b/libc/stdio/putc_unlocked.c
new file mode 100644
index 0000000000000000000000000000000000000000..10071312e74bbbd636bc856e1448a00dbc74a205
--- /dev/null
+++ b/libc/stdio/putc_unlocked.c
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+
+int (putc_unlocked)(int c, FILE *f)
+{
+	return putc_unlocked(c, f);
+}
+
+weak_alias(putc_unlocked, fputc_unlocked);
+weak_alias(putc_unlocked, _IO_putc_unlocked);
diff --git a/libc/stdio/putchar.c b/libc/stdio/putchar.c
new file mode 100644
index 0000000000000000000000000000000000000000..945636d5e66288cd23da8b4b5fb2390ec6583fa8
--- /dev/null
+++ b/libc/stdio/putchar.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int putchar(int c)
+{
+	return fputc(c, stdout);
+}
diff --git a/libc/stdio/putchar_unlocked.c b/libc/stdio/putchar_unlocked.c
new file mode 100644
index 0000000000000000000000000000000000000000..8b5d06034162679e604e3e4666ccf2a423050d1a
--- /dev/null
+++ b/libc/stdio/putchar_unlocked.c
@@ -0,0 +1,6 @@
+#include "stdio_impl.h"
+
+int putchar_unlocked(int c)
+{
+	return putc_unlocked(c, stdout);
+}
diff --git a/libc/stdio/puts.c b/libc/stdio/puts.c
new file mode 100644
index 0000000000000000000000000000000000000000..5a38a49b975adcad3192eda3148ef1acf55ad0df
--- /dev/null
+++ b/libc/stdio/puts.c
@@ -0,0 +1,10 @@
+#include "stdio_impl.h"
+
+int puts(const char *s)
+{
+	int r;
+	FLOCK(stdout);
+	r = -(fputs(s, stdout) < 0 || putc_unlocked('\n', stdout) < 0);
+	FUNLOCK(stdout);
+	return r;
+}
diff --git a/libc/stdio/putw.c b/libc/stdio/putw.c
new file mode 100644
index 0000000000000000000000000000000000000000..0ff9d7fbffb98a5d5919a3e8658678095674a3b7
--- /dev/null
+++ b/libc/stdio/putw.c
@@ -0,0 +1,7 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+
+int putw(int x, FILE *f)
+{
+	return (int)fwrite(&x, sizeof x, 1, f)-1;
+}
diff --git a/libc/stdio/putwc.c b/libc/stdio/putwc.c
new file mode 100644
index 0000000000000000000000000000000000000000..4bb74733486cfaf827ddbd58d50f2b3616208756
--- /dev/null
+++ b/libc/stdio/putwc.c
@@ -0,0 +1,7 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+wint_t putwc(wchar_t c, FILE *f)
+{
+	return fputwc(c, f);
+}
diff --git a/libc/stdio/putwchar.c b/libc/stdio/putwchar.c
new file mode 100644
index 0000000000000000000000000000000000000000..b249c4ac10997061355a261ff15cda08743183d9
--- /dev/null
+++ b/libc/stdio/putwchar.c
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+wint_t putwchar(wchar_t c)
+{
+	return fputwc(c, stdout);
+}
+
+weak_alias(putwchar, putwchar_unlocked);
diff --git a/libc/stdio/remove.c b/libc/stdio/remove.c
new file mode 100644
index 0000000000000000000000000000000000000000..dd8890d86bfc3532e9470fd9393b150266f5e651
--- /dev/null
+++ b/libc/stdio/remove.c
@@ -0,0 +1,10 @@
+#include <stdio.h>
+#include <errno.h>
+#include <unistd.h>
+#include "syscall.h"
+
+int remove(const char *path)
+{
+	int r = unlink(path);
+	return (r && errno == EISDIR) ? rmdir(path) : r;
+}
diff --git a/libc/stdio/rewind.c b/libc/stdio/rewind.c
new file mode 100644
index 0000000000000000000000000000000000000000..6f4b58b5468900cab60ca6e28c494ac2eea1c645
--- /dev/null
+++ b/libc/stdio/rewind.c
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+
+void rewind(FILE *f)
+{
+	FLOCK(f);
+	__fseeko_unlocked(f, 0, SEEK_SET);
+	f->flags &= ~F_ERR;
+	FUNLOCK(f);
+}
diff --git a/libc/stdio/scanf.c b/libc/stdio/scanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..862f735692715faa6543ad08d11734d2f17ff56d
--- /dev/null
+++ b/libc/stdio/scanf.c
@@ -0,0 +1,12 @@
+#include "stdio.h"
+#include <stdarg.h>
+
+int scanf(const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vscanf(fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/setbuf.c b/libc/stdio/setbuf.c
new file mode 100644
index 0000000000000000000000000000000000000000..74ad7834ae59f20b8a9c4e25ff471313e6776e24
--- /dev/null
+++ b/libc/stdio/setbuf.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+void setbuf(FILE *restrict f, char *restrict buf)
+{
+	setvbuf(f, buf, buf ? _IOFBF : _IONBF, BUFSIZ);
+}
diff --git a/libc/stdio/setbuffer.c b/libc/stdio/setbuffer.c
new file mode 100644
index 0000000000000000000000000000000000000000..71233d2ec1aee44d044786b68d1cbbc6d39d9e33
--- /dev/null
+++ b/libc/stdio/setbuffer.c
@@ -0,0 +1,7 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+
+void setbuffer(FILE *f, char *buf, size_t size)
+{
+	setvbuf(f, buf, buf ? _IOFBF : _IONBF, size);
+}
diff --git a/libc/stdio/setlinebuf.c b/libc/stdio/setlinebuf.c
new file mode 100644
index 0000000000000000000000000000000000000000..b93c4d6a1e1671a613aee5a86fd40600da02e954
--- /dev/null
+++ b/libc/stdio/setlinebuf.c
@@ -0,0 +1,7 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+
+void setlinebuf(FILE *f)
+{
+	setvbuf(f, 0, _IOLBF, 0);
+}
diff --git a/libc/stdio/setvbuf.c b/libc/stdio/setvbuf.c
new file mode 100644
index 0000000000000000000000000000000000000000..541a125ff124b1c1b5aa15949f0890a3d12c6f6b
--- /dev/null
+++ b/libc/stdio/setvbuf.c
@@ -0,0 +1,24 @@
+#include "stdio_impl.h"
+
+/* This function makes no attempt to protect the user from his/her own
+ * stupidity. If called any time but when then ISO C standard specifically
+ * allows it, all hell can and will break loose, especially with threads!
+ *
+ * This implementation ignores all arguments except the buffering type,
+ * and uses the existing buffer allocated alongside the FILE object.
+ * In the case of stderr where the preexisting buffer is length 1, it
+ * is not possible to set line buffering or full buffering. */
+
+int setvbuf(FILE *restrict f, char *restrict buf, int type, size_t size)
+{
+	f->lbf = EOF;
+
+	if (type == _IONBF)
+		f->buf_size = 0;
+	else if (type == _IOLBF)
+		f->lbf = '\n';
+
+	f->flags |= F_SVB;
+
+	return 0;
+}
diff --git a/libc/stdio/shgetc.h b/libc/stdio/shgetc.h
new file mode 100644
index 0000000000000000000000000000000000000000..7beb8ce62182b64bb6f7349640b6f2d833b113c3
--- /dev/null
+++ b/libc/stdio/shgetc.h
@@ -0,0 +1,9 @@
+#include "stdio_impl.h"
+
+void __shlim(FILE *, off_t);
+int __shgetc(FILE *);
+
+#define shcnt(f) ((f)->shcnt + ((f)->rpos - (f)->rend))
+#define shlim(f, lim) __shlim((f), (lim))
+#define shgetc(f) (((f)->rpos < (f)->shend) ? *(f)->rpos++ : __shgetc(f))
+#define shunget(f) ((f)->shend ? (void)(f)->rpos-- : (void)0)
diff --git a/libc/stdio/snprintf.c b/libc/stdio/snprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..771503b284eba969c9f26e0e05416be0083e429d
--- /dev/null
+++ b/libc/stdio/snprintf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+
+int snprintf(char *restrict s, size_t n, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vsnprintf(s, n, fmt, ap);
+	va_end(ap);
+	return ret;
+}
+
diff --git a/libc/stdio/sprintf.c b/libc/stdio/sprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..9dff524c0925ed7a6903125cccbd4647b1bcf722
--- /dev/null
+++ b/libc/stdio/sprintf.c
@@ -0,0 +1,12 @@
+#include <stdio.h>
+#include <stdarg.h>
+
+int sprintf(char *restrict s, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vsprintf(s, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/sscanf.c b/libc/stdio/sscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..811190b5756835b2af5390466adfaa95dabb628c
--- /dev/null
+++ b/libc/stdio/sscanf.c
@@ -0,0 +1,12 @@
+#include "stdio.h"
+#include <stdarg.h>
+
+int sscanf(const char *restrict s, const char *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vsscanf(s, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/stderr.c b/libc/stdio/stderr.c
new file mode 100644
index 0000000000000000000000000000000000000000..3fd8f81d76ec4ed4cef8680914b822be55067831
--- /dev/null
+++ b/libc/stdio/stderr.c
@@ -0,0 +1,16 @@
+#include "stdio_impl.h"
+
+static unsigned char buf[UNGET];
+static FILE f = {
+	.buf = buf+UNGET,
+	.buf_size = 0,
+	.fd = 2,
+	.flags = F_PERM | F_NORD,
+	.lbf = -1,
+	.write = __stdio_write,
+	.seek = __stdio_seek,
+	.close = __stdio_close,
+	.lock = -1,
+};
+FILE *const stderr = &f;
+FILE *const __stderr_used = &f;
diff --git a/libc/stdio/stdin.c b/libc/stdio/stdin.c
new file mode 100644
index 0000000000000000000000000000000000000000..476dc7088f2ea46af4e95f0607f7b7eb394e3d8a
--- /dev/null
+++ b/libc/stdio/stdin.c
@@ -0,0 +1,15 @@
+#include "stdio_impl.h"
+
+static unsigned char buf[BUFSIZ+UNGET];
+static FILE f = {
+	.buf = buf+UNGET,
+	.buf_size = sizeof buf-UNGET,
+	.fd = 0,
+	.flags = F_PERM | F_NOWR,
+	.read = __stdio_read,
+	.seek = __stdio_seek,
+	.close = __stdio_close,
+	.lock = -1,
+};
+FILE *const stdin = &f;
+FILE *const __stdin_used = &f;
diff --git a/libc/stdio/stdio.h b/libc/stdio/stdio.h
new file mode 100644
index 0000000000000000000000000000000000000000..6d8b19c50e978248da1148b18418455107cc3391
--- /dev/null
+++ b/libc/stdio/stdio.h
@@ -0,0 +1,188 @@
+#ifndef _STDIO_H
+#define _STDIO_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <sys/types.h>
+#include <stdarg.h>
+
+#undef EOF
+#define EOF (-1)
+
+#undef SEEK_SET
+#undef SEEK_CUR
+#undef SEEK_END
+#define SEEK_SET 0
+#define SEEK_CUR 1
+#define SEEK_END 2
+
+#define _IOFBF 0
+#define _IOLBF 1
+#define _IONBF 2
+
+#define BUFSIZ 1024
+#define FILENAME_MAX 4095
+#define FOPEN_MAX 1000
+#define TMP_MAX 10000
+#define L_tmpnam 20
+
+typedef union {
+	char __opaque[16];
+	double __align;
+} fpos_t;
+
+
+typedef struct __FILE_s FILE;
+#define __FILE FILE
+
+extern FILE *const stdin;
+extern FILE *const stdout;
+extern FILE *const stderr;
+
+#define stdin  (stdin)
+#define stdout (stdout)
+#define stderr (stderr)
+
+FILE *fopen(const char *__restrict, const char *__restrict);
+FILE *freopen(const char *__restrict, const char *__restrict, FILE *__restrict);
+int fclose(FILE *);
+
+int remove(const char *);
+int rename(const char *, const char *);
+
+int feof(FILE *);
+int ferror(FILE *);
+int fflush(FILE *);
+void clearerr(FILE *);
+
+int fseek(FILE *, long, int);
+long ftell(FILE *);
+void rewind(FILE *);
+
+int fgetpos(FILE *__restrict, fpos_t *__restrict);
+int fsetpos(FILE *, const fpos_t *);
+
+size_t fread(void *__restrict, size_t, size_t, FILE *__restrict);
+size_t fwrite(const void *__restrict, size_t, size_t, FILE *__restrict);
+
+int fgetc(FILE *);
+int getc(FILE *);
+int getchar(void);
+int ungetc(int, FILE *);
+
+int fputc(int, FILE *);
+int putc(int, FILE *);
+int putchar(int);
+
+char *fgets(char *__restrict, int, FILE *__restrict);
+#if __STDC_VERSION__ < 201112L
+char *gets(char *);
+#endif
+
+int fputs(const char *__restrict, FILE *__restrict);
+int puts(const char *);
+
+int printf(const char *__restrict, ...);
+int fprintf(FILE *__restrict, const char *__restrict, ...);
+int sprintf(char *__restrict, const char *__restrict, ...);
+int snprintf(char *__restrict, size_t, const char *__restrict, ...);
+
+int vprintf(const char *__restrict, va_list);
+int vfprintf(FILE *__restrict, const char *__restrict, va_list);
+int vsprintf(char *__restrict, const char *__restrict, va_list);
+int vsnprintf(char *__restrict, size_t, const char *__restrict, va_list);
+
+int scanf(const char *__restrict, ...);
+int fscanf(FILE *__restrict, const char *__restrict, ...);
+int sscanf(const char *__restrict, const char *__restrict, ...);
+int vscanf(const char *__restrict, va_list);
+int vfscanf(FILE *__restrict, const char *__restrict, va_list);
+int vsscanf(const char *__restrict, const char *__restrict, va_list);
+
+void perror(const char *);
+
+int setvbuf(FILE *__restrict, char *__restrict, int, size_t);
+void setbuf(FILE *__restrict, char *__restrict);
+
+char *tmpnam(char *);
+FILE *tmpfile(void);
+
+#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
+ || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
+ || defined(_BSD_SOURCE)
+FILE *fmemopen(void *__restrict, size_t, const char *__restrict);
+FILE *open_memstream(char **, size_t *);
+FILE *fdopen(int, const char *);
+FILE *popen(const char *, const char *);
+int pclose(FILE *);
+int fileno(FILE *);
+int fseeko(FILE *, off_t, int);
+off_t ftello(FILE *);
+int dprintf(int, const char *__restrict, ...);
+int vdprintf(int, const char *__restrict, va_list);
+void flockfile(FILE *);
+int ftrylockfile(FILE *);
+void funlockfile(FILE *);
+int getc_unlocked(FILE *);
+int getchar_unlocked(void);
+int putc_unlocked(int, FILE *);
+int putchar_unlocked(int);
+ssize_t getdelim(char **__restrict, size_t *__restrict, int, FILE *__restrict);
+ssize_t getline(char **__restrict, size_t *__restrict, FILE *__restrict);
+int renameat(int, const char *, int, const char *);
+char *ctermid(char *);
+#define L_ctermid 20
+#endif
+
+
+#if defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
+ || defined(_BSD_SOURCE)
+#define P_tmpdir "/tmp"
+char *tempnam(const char *, const char *);
+#endif
+
+#if defined(_GNU_SOURCE) || defined(_BSD_SOURCE)
+#define L_cuserid 20
+char *cuserid(char *);
+void setlinebuf(FILE *);
+void setbuffer(FILE *, char *, size_t);
+int fgetc_unlocked(FILE *);
+int fputc_unlocked(int, FILE *);
+int fflush_unlocked(FILE *);
+size_t fread_unlocked(void *, size_t, size_t, FILE *);
+size_t fwrite_unlocked(const void *, size_t, size_t, FILE *);
+void clearerr_unlocked(FILE *);
+int feof_unlocked(FILE *);
+int ferror_unlocked(FILE *);
+int fileno_unlocked(FILE *);
+int getw(FILE *);
+int putw(int, FILE *);
+char *fgetln(FILE *, size_t *);
+int asprintf(char **, const char *, ...);
+int vasprintf(char **, const char *, va_list);
+#endif
+
+#ifdef _GNU_SOURCE
+char *fgets_unlocked(char *, int, FILE *);
+int fputs_unlocked(const char *, FILE *);
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) || defined(_GNU_SOURCE)
+#define tmpfile64 tmpfile
+#define fopen64 fopen
+#define freopen64 freopen
+#define fseeko64 fseeko
+#define ftello64 ftello
+#define fgetpos64 fgetpos
+#define fsetpos64 fsetpos
+#define fpos64_t fpos_t
+#define off64_t off_t
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libc/stdio/stdio_ext.h b/libc/stdio/stdio_ext.h
new file mode 100644
index 0000000000000000000000000000000000000000..e3ab7fd4f9c6b1bb90af537dcb19d7ede9491309
--- /dev/null
+++ b/libc/stdio/stdio_ext.h
@@ -0,0 +1,34 @@
+#ifndef _STDIO_EXT_H
+#define _STDIO_EXT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stdio.h>
+
+#define FSETLOCKING_QUERY 0
+#define FSETLOCKING_INTERNAL 1
+#define FSETLOCKING_BYCALLER 2
+
+void _flushlbf(void);
+int __fsetlocking(FILE *, int);
+int __fwriting(FILE *);
+int __freading(FILE *);
+int __freadable(FILE *);
+int __fwritable(FILE *);
+int __flbf(FILE *);
+size_t __fbufsize(FILE *);
+size_t __fpending(FILE *);
+int __fpurge(FILE *);
+
+size_t __freadahead(FILE *);
+const char *__freadptr(FILE *, size_t *);
+void __freadptrinc(FILE *, size_t);
+void __fseterr(FILE *);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/libc/stdio/stdio_impl.h b/libc/stdio/stdio_impl.h
new file mode 100644
index 0000000000000000000000000000000000000000..439318af064f068f246567e0e6aa8d0500cd8e18
--- /dev/null
+++ b/libc/stdio/stdio_impl.h
@@ -0,0 +1,94 @@
+#ifndef _STDIO_IMPL_H
+#define _STDIO_IMPL_H
+
+#include "stdio.h"
+#include "libc.h"
+
+#define UNGET 8
+
+#define FFINALLOCK(f) ((f)->lock>=0 ? __lockfile((f)) : 0)
+#define FLOCK(f) int __need_unlock = ((f)->lock>=0 ? __lockfile((f)) : 0)
+#define FUNLOCK(f) if (__need_unlock) __unlockfile((f)); else
+
+#define F_PERM 1
+#define F_NORD 4
+#define F_NOWR 8
+#define F_EOF 16
+#define F_ERR 32
+#define F_SVB 64
+
+struct __FILE_s {
+	unsigned flags;
+	unsigned char *rpos, *rend;
+	int (*close)(FILE *);
+	unsigned char *wend, *wpos;
+	unsigned char *mustbezero_1;
+	unsigned char *wbase;
+	size_t (*read)(FILE *, unsigned char *, size_t);
+	size_t (*write)(FILE *, const unsigned char *, size_t);
+	off_t (*seek)(FILE *, off_t, int);
+	unsigned char *buf;
+	size_t buf_size;
+	FILE *prev, *next;
+	int fd;
+	int pipe_pid;
+	long lockcount;
+	short dummy3;
+	signed char mode;
+	signed char lbf;
+	int lock;
+	int waiters;
+	void *cookie;
+	off_t off;
+	char *getln_buf;
+	void *mustbezero_2;
+	unsigned char *shend;
+	off_t shlim, shcnt;
+};
+
+size_t __stdio_read(FILE *, unsigned char *, size_t);
+size_t __stdio_write(FILE *, const unsigned char *, size_t);
+size_t __stdout_write(FILE *, const unsigned char *, size_t);
+off_t __stdio_seek(FILE *, off_t, int);
+int __stdio_close(FILE *);
+
+size_t __string_read(FILE *, unsigned char *, size_t);
+
+int __toread(FILE *);
+int __towrite(FILE *);
+
+#if defined(__PIC__) && (100*__GNUC__+__GNUC_MINOR__ >= 303)
+__attribute__((visibility("protected")))
+#endif
+int __overflow(FILE *, int), __uflow(FILE *);
+
+int __fseeko(FILE *, off_t, int);
+int __fseeko_unlocked(FILE *, off_t, int);
+off_t __ftello(FILE *);
+off_t __ftello_unlocked(FILE *);
+size_t __fwritex(const unsigned char *, size_t, FILE *);
+int __putc_unlocked(int, FILE *);
+
+FILE *__fdopen(int, const char *);
+int __fmodeflags(const char *);
+
+#define OFLLOCK() LOCK(libc.ofl_lock)
+#define OFLUNLOCK() UNLOCK(libc.ofl_lock)
+
+#define feof(f) ((f)->flags & F_EOF)
+#define ferror(f) ((f)->flags & F_ERR)
+
+#define getc_unlocked(f) \
+	( ((f)->rpos < (f)->rend) ? *(f)->rpos++ : __uflow((f)) )
+
+#define putc_unlocked(c, f) ( ((c)!=(f)->lbf && (f)->wpos<(f)->wend) \
+	? *(f)->wpos++ = (c) : __overflow((f),(c)) )
+
+/* Caller-allocated FILE * operations */
+FILE *__fopen_rb_ca(const char *, FILE *, unsigned char *, size_t);
+int __fclose_ca(FILE *);
+
+int __lockfile(FILE *) ATTR_LIBC_VISIBILITY;
+void __unlockfile(FILE *) ATTR_LIBC_VISIBILITY;
+
+#endif
diff --git a/libc/stdio/stdout.c b/libc/stdio/stdout.c
new file mode 100644
index 0000000000000000000000000000000000000000..3855dd0be2f812906d2493ad0f47b46ee43e8233
--- /dev/null
+++ b/libc/stdio/stdout.c
@@ -0,0 +1,16 @@
+#include "stdio_impl.h"
+
+static unsigned char buf[BUFSIZ+UNGET];
+static FILE f = {
+	.buf = buf+UNGET,
+	.buf_size = sizeof buf-UNGET,
+	.fd = 1,
+	.flags = F_PERM | F_NORD,
+	.lbf = '\n',
+	.write = __stdout_write,
+	.seek = __stdio_seek,
+	.close = __stdio_close,
+	.lock = -1,
+};
+FILE *const stdout = &f;
+FILE *const __stdout_used = &f;
diff --git a/libc/stdio/swprintf.c b/libc/stdio/swprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..cbf83d235d8e0e436ff942cc1915f33b35848147
--- /dev/null
+++ b/libc/stdio/swprintf.c
@@ -0,0 +1,14 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int swprintf(wchar_t *restrict s, size_t n, const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vswprintf(s, n, fmt, ap);
+	va_end(ap);
+	return ret;
+}
+
diff --git a/libc/stdio/swscanf.c b/libc/stdio/swscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..1fe3c3d888d9842c1b76804ff99bf56c204ce280
--- /dev/null
+++ b/libc/stdio/swscanf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int swscanf(const wchar_t *restrict s, const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vswscanf(s, fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/tempnam.c b/libc/stdio/tempnam.c
new file mode 100644
index 0000000000000000000000000000000000000000..f73ca9f9027f4cec78819da8b954fb7d932a837f
--- /dev/null
+++ b/libc/stdio/tempnam.c
@@ -0,0 +1,42 @@
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <time.h>
+#include "libc.h"
+#include "atomic.h"
+
+#define MAXTRIES 100
+
+char *tempnam(const char *dir, const char *pfx)
+{
+	static int index;
+	char *s;
+	struct timespec ts;
+	int pid = getpid();
+	size_t l;
+	int n;
+	int try=0;
+
+	if (!dir) dir = P_tmpdir;
+	if (!pfx) pfx = "temp";
+
+	if (access(dir, R_OK|W_OK|X_OK) != 0)
+		return NULL;
+
+	l = strlen(dir) + 1 + strlen(pfx) + 3*(sizeof(int)*3+2) + 1;
+	s = malloc(l);
+	if (!s) return s;
+
+	do {
+		clock_gettime(CLOCK_REALTIME, &ts);
+		n = ts.tv_nsec ^ (uintptr_t)&s ^ (uintptr_t)s;
+		snprintf(s, l, "%s/%s-%d-%d-%x", dir, pfx, pid, a_fetch_add(&index, 1), n);
+	} while (!access(s, F_OK) && try++<MAXTRIES);
+	if (try>=MAXTRIES) {
+		free(s);
+		return 0;
+	}
+	return s;
+}
diff --git a/libc/stdio/tmpfile.c b/libc/stdio/tmpfile.c
new file mode 100644
index 0000000000000000000000000000000000000000..195ba19140562c419b306769d3f7480b925e16c5
--- /dev/null
+++ b/libc/stdio/tmpfile.c
@@ -0,0 +1,27 @@
+#include <stdio.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include "stdio_impl.h"
+
+#define MAXTRIES 100
+
+FILE *tmpfile(void)
+{
+	char buf[L_tmpnam], *s;
+	int fd;
+	FILE *f;
+	int try;
+	for (try=0; try<MAXTRIES; try++) {
+		s = tmpnam(buf);
+		if (!s) return 0;
+		fd = open(s, O_RDWR|O_CREAT|O_EXCL|O_LARGEFILE, 0600);
+		if (fd >= 0) {
+			f = __fdopen(fd, "w+");
+			unlink(s);
+			return f;
+		}
+	}
+	return 0;
+}
+
+LFS64(tmpfile);
diff --git a/libc/stdio/tmpnam.c b/libc/stdio/tmpnam.c
new file mode 100644
index 0000000000000000000000000000000000000000..be358fb90e5f3b9dbbdad9b211bb15cbf4473ba1
--- /dev/null
+++ b/libc/stdio/tmpnam.c
@@ -0,0 +1,31 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdint.h>
+#include <unistd.h>
+#include <time.h>
+#include "libc.h"
+#include "syscall.h"
+#include "atomic.h"
+
+#define MAXTRIES 100
+
+char *tmpnam(char *s)
+{
+	static int index;
+	static char s2[L_tmpnam];
+	struct timespec ts;
+	int try = 0;
+	unsigned n;
+
+	if (!s) s = s2;
+
+	if (access(P_tmpdir, R_OK|W_OK|X_OK) != 0)
+		return NULL;
+
+	do {
+		clock_gettime(CLOCK_REALTIME, &ts);
+		n = ts.tv_nsec ^ (uintptr_t)&s ^ (uintptr_t)s;
+		snprintf(s, L_tmpnam, "/tmp/t%x-%x", a_fetch_add(&index, 1), n);
+	} while (!access(s, F_OK) && try++<MAXTRIES);
+	return try>=MAXTRIES ? 0 : s;
+}
diff --git a/libc/stdio/ungetc.c b/libc/stdio/ungetc.c
new file mode 100644
index 0000000000000000000000000000000000000000..7f56f8d5f07b79dba384f9ef02fe2b8c160b6467
--- /dev/null
+++ b/libc/stdio/ungetc.c
@@ -0,0 +1,19 @@
+#include "stdio_impl.h"
+
+int ungetc(int c, FILE *f)
+{
+	if (c == EOF) return c;
+
+	FLOCK(f);
+
+	if ((!f->rend && __toread(f)) || f->rpos <= f->buf - UNGET) {
+		FUNLOCK(f);
+		return EOF;
+	}
+
+	*--f->rpos = c;
+	f->flags &= ~F_EOF;
+
+	FUNLOCK(f);
+	return c;
+}
diff --git a/libc/stdio/ungetwc.c b/libc/stdio/ungetwc.c
new file mode 100644
index 0000000000000000000000000000000000000000..8cc85a6bfd2a00b615ecccdc96fbfc519e4b77f5
--- /dev/null
+++ b/libc/stdio/ungetwc.c
@@ -0,0 +1,34 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+#include <limits.h>
+#include <ctype.h>
+#include <string.h>
+
+wint_t ungetwc(wint_t c, FILE *f)
+{
+	unsigned char mbc[MB_LEN_MAX];
+	int l=1;
+
+	if (c == WEOF) return c;
+
+	/* Try conversion early so we can fail without locking if invalid */
+	if (!isascii(c) && (l = wctomb((void *)mbc, c)) < 0)
+		return WEOF;
+
+	FLOCK(f);
+
+	f->mode |= f->mode+1;
+
+	if ((!f->rend && __toread(f)) || f->rpos < f->buf - UNGET + l) {
+		FUNLOCK(f);
+		return EOF;
+	}
+
+	if (isascii(c)) *--f->rpos = c;
+	else memcpy(f->rpos -= l, mbc, l);
+
+	f->flags &= ~F_EOF;
+
+	FUNLOCK(f);
+	return c;
+}
diff --git a/libc/stdio/vasprintf.c b/libc/stdio/vasprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..68b7246b01362b2598894bb79e8074560fc3b833
--- /dev/null
+++ b/libc/stdio/vasprintf.c
@@ -0,0 +1,28 @@
+#define _GNU_SOURCE
+#include <stdio.h>
+#include <stdarg.h>
+#include <stdlib.h>
+
+#define GUESS 240U
+
+int vasprintf(char **s, const char *fmt, va_list ap)
+{
+	va_list ap2;
+	char *a;
+	int l=GUESS;
+
+	if (!(a=malloc(GUESS))) return -1;
+
+	va_copy(ap2, ap);
+	l=vsnprintf(a, GUESS, fmt, ap2);
+	va_end(ap2);
+
+	if (l<GUESS) {
+		char *b = realloc(a, l+1U);
+		*s = b ? b : a;
+		return l;
+	}
+	free(a);
+	if (l<0 || !(*s=malloc(l+1U))) return -1;
+	return vsnprintf(*s, l+1U, fmt, ap);
+}
diff --git a/libc/stdio/vdprintf.c b/libc/stdio/vdprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..c35d9b4fb0412fdefb2f4a07c198b8de8b451871
--- /dev/null
+++ b/libc/stdio/vdprintf.c
@@ -0,0 +1,16 @@
+#include "stdio_impl.h"
+
+static size_t wrap_write(FILE *f, const unsigned char *buf, size_t len)
+{
+	return __stdio_write(f, buf, len);
+}
+
+int vdprintf(int fd, const char *restrict fmt, va_list ap)
+{
+	FILE f = {
+		.fd = fd, .lbf = EOF, .write = wrap_write,
+		.buf = (void *)fmt, .buf_size = 0,
+		.lock = -1
+	};
+	return vfprintf(&f, fmt, ap);
+}
diff --git a/libc/stdio/vfprintf.c b/libc/stdio/vfprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..31db27f65454741425e29fc5f2d8183b6d2e4246
--- /dev/null
+++ b/libc/stdio/vfprintf.c
@@ -0,0 +1,683 @@
+#include "stdio_impl.h"
+#include <errno.h>
+#include <ctype.h>
+#include <limits.h>
+#include <string.h>
+#include <stdarg.h>
+#include <wchar.h>
+#include <inttypes.h>
+#include <math.h>
+#include <float.h>
+
+#define NL_ARGMAX _POSIX_ARG_MAX
+
+/* Some useful macros */
+
+#define MAX(a,b) ((a)>(b) ? (a) : (b))
+#define MIN(a,b) ((a)<(b) ? (a) : (b))
+#define CONCAT2(x,y) x ## y
+#define CONCAT(x,y) CONCAT2(x,y)
+
+/* Convenient bit representation for modifier flags, which all fall
+ * within 31 codepoints of the space character. */
+
+#define ALT_FORM   (1U<<'#'-' ')
+#define ZERO_PAD   (1U<<'0'-' ')
+#define LEFT_ADJ   (1U<<'-'-' ')
+#define PAD_POS    (1U<<' '-' ')
+#define MARK_POS   (1U<<'+'-' ')
+#define GROUPED    (1U<<'\''-' ')
+
+#define FLAGMASK (ALT_FORM|ZERO_PAD|LEFT_ADJ|PAD_POS|MARK_POS|GROUPED)
+
+#if UINT_MAX == ULONG_MAX
+#define LONG_IS_INT
+#endif
+
+#if SIZE_MAX != ULONG_MAX || UINTMAX_MAX != ULLONG_MAX
+#define ODD_TYPES
+#endif
+
+/* State machine to accept length modifiers + conversion specifiers.
+ * Result is 0 on failure, or an argument type to pop on success. */
+
+enum {
+	BARE, LPRE, LLPRE, HPRE, HHPRE, BIGLPRE,
+	ZTPRE, JPRE,
+	STOP,
+	PTR, INT, UINT, ULLONG,
+#ifndef LONG_IS_INT
+	LONG, ULONG,
+#else
+#define LONG INT
+#define ULONG UINT
+#endif
+	SHORT, USHORT, CHAR, UCHAR,
+#ifdef ODD_TYPES
+	LLONG, SIZET, IMAX, UMAX, PDIFF, UIPTR,
+#else
+#define LLONG ULLONG
+#define SIZET ULONG
+#define IMAX LLONG
+#define UMAX ULLONG
+#define PDIFF LONG
+#define UIPTR ULONG
+#endif
+	DBL, LDBL,
+	NOARG,
+	MAXSTATE
+};
+
+#define S(x) [(x)-'A']
+
+static const unsigned char states[]['z'-'A'+1] = {
+	{ /* 0: bare types */
+		S('d') = INT, S('i') = INT,
+		S('o') = UINT, S('u') = UINT, S('x') = UINT, S('X') = UINT,
+		S('e') = DBL, S('f') = DBL, S('g') = DBL, S('a') = DBL,
+		S('E') = DBL, S('F') = DBL, S('G') = DBL, S('A') = DBL,
+		S('c') = CHAR, S('C') = INT,
+		S('s') = PTR, S('S') = PTR, S('p') = UIPTR, S('n') = PTR,
+		S('m') = NOARG,
+		S('l') = LPRE, S('h') = HPRE, S('L') = BIGLPRE,
+		S('z') = ZTPRE, S('j') = JPRE, S('t') = ZTPRE,
+	}, { /* 1: l-prefixed */
+		S('d') = LONG, S('i') = LONG,
+		S('o') = ULONG, S('u') = ULONG, S('x') = ULONG, S('X') = ULONG,
+		S('e') = DBL, S('f') = DBL, S('g') = DBL, S('a') = DBL,
+		S('E') = DBL, S('F') = DBL, S('G') = DBL, S('A') = DBL,
+		S('c') = INT, S('s') = PTR, S('n') = PTR,
+		S('l') = LLPRE,
+	}, { /* 2: ll-prefixed */
+		S('d') = LLONG, S('i') = LLONG,
+		S('o') = ULLONG, S('u') = ULLONG,
+		S('x') = ULLONG, S('X') = ULLONG,
+		S('n') = PTR,
+	}, { /* 3: h-prefixed */
+		S('d') = SHORT, S('i') = SHORT,
+		S('o') = USHORT, S('u') = USHORT,
+		S('x') = USHORT, S('X') = USHORT,
+		S('n') = PTR,
+		S('h') = HHPRE,
+	}, { /* 4: hh-prefixed */
+		S('d') = CHAR, S('i') = CHAR,
+		S('o') = UCHAR, S('u') = UCHAR,
+		S('x') = UCHAR, S('X') = UCHAR,
+		S('n') = PTR,
+	}, { /* 5: L-prefixed */
+		S('e') = LDBL, S('f') = LDBL, S('g') = LDBL, S('a') = LDBL,
+		S('E') = LDBL, S('F') = LDBL, S('G') = LDBL, S('A') = LDBL,
+		S('n') = PTR,
+	}, { /* 6: z- or t-prefixed (assumed to be same size) */
+		S('d') = PDIFF, S('i') = PDIFF,
+		S('o') = SIZET, S('u') = SIZET,
+		S('x') = SIZET, S('X') = SIZET,
+		S('n') = PTR,
+	}, { /* 7: j-prefixed */
+		S('d') = IMAX, S('i') = IMAX,
+		S('o') = UMAX, S('u') = UMAX,
+		S('x') = UMAX, S('X') = UMAX,
+		S('n') = PTR,
+	}
+};
+
+#define OOB(x) ((unsigned)(x)-'A' > 'z'-'A')
+
+union arg
+{
+	uintmax_t i;
+	long double f;
+	void *p;
+};
+
+static void pop_arg(union arg *arg, int type, va_list *ap)
+{
+	/* Give the compiler a hint for optimizing the switch. */
+	if ((unsigned)type > MAXSTATE) return;
+	switch (type) {
+	       case PTR:	arg->p = va_arg(*ap, void *);
+	break; case INT:	arg->i = va_arg(*ap, int);
+	break; case UINT:	arg->i = va_arg(*ap, unsigned int);
+#ifndef LONG_IS_INT
+	break; case LONG:	arg->i = va_arg(*ap, long);
+	break; case ULONG:	arg->i = va_arg(*ap, unsigned long);
+#endif
+	break; case ULLONG:	arg->i = va_arg(*ap, unsigned long long);
+	break; case SHORT:	arg->i = (short)va_arg(*ap, int);
+	break; case USHORT:	arg->i = (unsigned short)va_arg(*ap, int);
+	break; case CHAR:	arg->i = (signed char)va_arg(*ap, int);
+	break; case UCHAR:	arg->i = (unsigned char)va_arg(*ap, int);
+#ifdef ODD_TYPES
+	break; case LLONG:	arg->i = va_arg(*ap, long long);
+	break; case SIZET:	arg->i = va_arg(*ap, size_t);
+	break; case IMAX:	arg->i = va_arg(*ap, intmax_t);
+	break; case UMAX:	arg->i = va_arg(*ap, uintmax_t);
+	break; case PDIFF:	arg->i = va_arg(*ap, ptrdiff_t);
+	break; case UIPTR:	arg->i = (uintptr_t)va_arg(*ap, void *);
+#endif
+	break; case DBL:	arg->f = va_arg(*ap, double);
+	break; case LDBL:	arg->f = va_arg(*ap, long double);
+	}
+}
+
+static void out(FILE *f, const char *s, size_t l)
+{
+	__fwritex((void *)s, l, f);
+}
+
+static void pad(FILE *f, char c, int w, int l, int fl)
+{
+	char pad[256];
+	if (fl & (LEFT_ADJ | ZERO_PAD) || l >= w) return;
+	l = w - l;
+	memset(pad, c, l>sizeof pad ? sizeof pad : l);
+	for (; l >= sizeof pad; l -= sizeof pad)
+		out(f, pad, sizeof pad);
+	out(f, pad, l);
+}
+
+static const char xdigits[16] = {
+	"0123456789ABCDEF"
+};
+
+static char *fmt_x(uintmax_t x, char *s, int lower)
+{
+	for (; x; x>>=4) *--s = xdigits[(x&15)]|lower;
+	return s;
+}
+
+static char *fmt_o(uintmax_t x, char *s)
+{
+	for (; x; x>>=3) *--s = '0' + (x&7);
+	return s;
+}
+
+static char *fmt_u(uintmax_t x, char *s)
+{
+	unsigned long y;
+	for (   ; x>ULONG_MAX; x/=10) *--s = '0' + x%10;
+	for (y=x;           y; y/=10) *--s = '0' + y%10;
+	return s;
+}
+
+#ifdef HAVE_FLOAT_SUPPORT
+static int fmt_fp(FILE *f, long double y, int w, int p, int fl, int t)
+{
+	uint32_t big[(LDBL_MAX_EXP+LDBL_MANT_DIG)/9+1];
+	uint32_t *a, *d, *r, *z;
+	int e2=0, e, i, j, l;
+	char buf[9+LDBL_MANT_DIG/4], *s;
+	const char *prefix="-0X+0X 0X-0x+0x 0x";
+	int pl;
+	char ebuf0[3*sizeof(int)], *ebuf=&ebuf0[3*sizeof(int)], *estr;
+
+	pl=1;
+	if (signbit(y)) {
+		y=-y;
+	} else if (fl & MARK_POS) {
+		prefix+=3;
+	} else if (fl & PAD_POS) {
+		prefix+=6;
+	} else prefix++, pl=0;
+
+	if (!isfinite(y)) {
+		char *s = (t&32)?"inf":"INF";
+		if (y!=y) s=(t&32)?"nan":"NAN", pl=0;
+		pad(f, ' ', w, 3+pl, fl&~ZERO_PAD);
+		out(f, prefix, pl);
+		out(f, s, 3);
+		pad(f, ' ', w, 3+pl, fl^LEFT_ADJ);
+		return MAX(w, 3+pl);
+	}
+
+	y = frexpl(y, &e2) * 2;
+	if (y) e2--;
+
+	if ((t|32)=='a') {
+		long double round = 8.0;
+		int re;
+
+		if (t&32) prefix += 9;
+		pl += 2;
+
+		if (p<0 || p>=LDBL_MANT_DIG/4-1) re=0;
+		else re=LDBL_MANT_DIG/4-1-p;
+
+		if (re) {
+			while (re--) round*=16;
+			if (*prefix=='-') {
+				y=-y;
+				y-=round;
+				y+=round;
+				y=-y;
+			} else {
+				y+=round;
+				y-=round;
+			}
+		}
+
+		estr=fmt_u(e2<0 ? -e2 : e2, ebuf);
+		if (estr==ebuf) *--estr='0';
+		*--estr = (e2<0 ? '-' : '+');
+		*--estr = t+('p'-'a');
+
+		s=buf;
+		do {
+			int x=y;
+			*s++=xdigits[x]|(t&32);
+			y=16*(y-x);
+			if (s-buf==1 && (y||p>0||(fl&ALT_FORM))) *s++='.';
+		} while (y);
+
+		if (p && s-buf-2 < p)
+			l = (p+2) + (ebuf-estr);
+		else
+			l = (s-buf) + (ebuf-estr);
+
+		pad(f, ' ', w, pl+l, fl);
+		out(f, prefix, pl);
+		pad(f, '0', w, pl+l, fl^ZERO_PAD);
+		out(f, buf, s-buf);
+		pad(f, '0', l-(ebuf-estr)-(s-buf), 0, 0);
+		out(f, estr, ebuf-estr);
+		pad(f, ' ', w, pl+l, fl^LEFT_ADJ);
+		return MAX(w, pl+l);
+	}
+	if (p<0) p=6;
+
+	if (y) y *= 0x1p28, e2-=28;
+
+	if (e2<0) a=r=z=big;
+	else a=r=z=big+sizeof(big)/sizeof(*big) - LDBL_MANT_DIG - 1;
+
+	do {
+		*z = y;
+		y = 1000000000*(y-*z++);
+	} while (y);
+
+	while (e2>0) {
+		uint32_t carry=0;
+		int sh=MIN(29,e2);
+		for (d=z-1; d>=a; d--) {
+			uint64_t x = ((uint64_t)*d<<sh)+carry;
+			*d = x % 1000000000;
+			carry = x / 1000000000;
+		}
+		if (!z[-1] && z>a) z--;
+		if (carry) *--a = carry;
+		e2-=sh;
+	}
+	while (e2<0) {
+		uint32_t carry=0, *b;
+		int sh=MIN(9,-e2);
+		for (d=a; d<z; d++) {
+			uint32_t rm = *d & (1<<sh)-1;
+			*d = (*d>>sh) + carry;
+			carry = (1000000000>>sh) * rm;
+		}
+		if (!*a) a++;
+		if (carry) *z++ = carry;
+		/* Avoid (slow!) computation past requested precision */
+		b = (t|32)=='f' ? r : a;
+		if (z-b > 2+p/9) z = b+2+p/9;
+		e2+=sh;
+	}
+
+	if (a<z) for (i=10, e=9*(r-a); *a>=i; i*=10, e++);
+	else e=0;
+
+	/* Perform rounding: j is precision after the radix (possibly neg) */
+	j = p - ((t|32)!='f')*e - ((t|32)=='g' && p);
+	if (j < 9*(z-r-1)) {
+		uint32_t x;
+		/* We avoid C's broken division of negative numbers */
+		d = r + 1 + ((j+9*LDBL_MAX_EXP)/9 - LDBL_MAX_EXP);
+		j += 9*LDBL_MAX_EXP;
+		j %= 9;
+		for (i=10, j++; j<9; i*=10, j++);
+		x = *d % i;
+		/* Are there any significant digits past j? */
+		if (x || d+1!=z) {
+			long double round = CONCAT(0x1p,LDBL_MANT_DIG);
+			long double small;
+			if (*d/i & 1) round += 2;
+			if (x<i/2) small=0x0.8p0;
+			else if (x==i/2 && d+1==z) small=0x1.0p0;
+			else small=0x1.8p0;
+			if (pl && *prefix=='-') round*=-1, small*=-1;
+			*d -= x;
+			/* Decide whether to round by probing round+small */
+			if (round+small != round) {
+				*d = *d + i;
+				while (*d > 999999999) {
+					*d--=0;
+					(*d)++;
+				}
+				if (d<a) a=d;
+				for (i=10, e=9*(r-a); *a>=i; i*=10, e++);
+			}
+		}
+		if (z>d+1) z=d+1;
+		for (; !z[-1] && z>a; z--);
+	}
+	
+	if ((t|32)=='g') {
+		if (!p) p++;
+		if (p>e && e>=-4) {
+			t--;
+			p-=e+1;
+		} else {
+			t-=2;
+			p--;
+		}
+		if (!(fl&ALT_FORM)) {
+			/* Count trailing zeros in last place */
+			if (z>a && z[-1]) for (i=10, j=0; z[-1]%i==0; i*=10, j++);
+			else j=9;
+			if ((t|32)=='f')
+				p = MIN(p,MAX(0,9*(z-r-1)-j));
+			else
+				p = MIN(p,MAX(0,9*(z-r-1)+e-j));
+		}
+	}
+	l = 1 + p + (p || (fl&ALT_FORM));
+	if ((t|32)=='f') {
+		if (e>0) l+=e;
+	} else {
+		estr=fmt_u(e<0 ? -e : e, ebuf);
+		while(ebuf-estr<2) *--estr='0';
+		*--estr = (e<0 ? '-' : '+');
+		*--estr = t;
+		l += ebuf-estr;
+	}
+
+	pad(f, ' ', w, pl+l, fl);
+	out(f, prefix, pl);
+	pad(f, '0', w, pl+l, fl^ZERO_PAD);
+
+	if ((t|32)=='f') {
+		if (a>r) a=r;
+		for (d=a; d<=r; d++) {
+			char *s = fmt_u(*d, buf+9);
+			if (d!=a) while (s>buf) *--s='0';
+			else if (s==buf+9) *--s='0';
+			out(f, s, buf+9-s);
+		}
+		if (p || (fl&ALT_FORM)) out(f, ".", 1);
+		for (; d<z && p>0; d++, p-=9) {
+			char *s = fmt_u(*d, buf+9);
+			while (s>buf) *--s='0';
+			out(f, s, MIN(9,p));
+		}
+		pad(f, '0', p+9, 9, 0);
+	} else {
+		if (z<=a) z=a+1;
+		for (d=a; d<z && p>=0; d++) {
+			char *s = fmt_u(*d, buf+9);
+			if (s==buf+9) *--s='0';
+			if (d!=a) while (s>buf) *--s='0';
+			else {
+				out(f, s++, 1);
+				if (p>0||(fl&ALT_FORM)) out(f, ".", 1);
+			}
+			out(f, s, MIN(buf+9-s, p));
+			p -= buf+9-s;
+		}
+		pad(f, '0', p+18, 18, 0);
+		out(f, estr, ebuf-estr);
+	}
+
+	pad(f, ' ', w, pl+l, fl^LEFT_ADJ);
+
+	return MAX(w, pl+l);
+}
+#endif /* HAVE_FLOAT_SUPPORT */
+
+static int getint(char **s) {
+	int i;
+	for (i=0; isdigit(**s); (*s)++)
+		i = 10*i + (**s-'0');
+	return i;
+}
+
+static int printf_core(FILE *f, const char *fmt, va_list *ap, union arg *nl_arg, int *nl_type)
+{
+	char *a, *z, *s=(char *)fmt;
+	unsigned l10n=0, fl;
+	int w, p;
+	union arg arg;
+	int argpos;
+	unsigned st, ps;
+	int cnt=0, l=0;
+	int i;
+	char buf[sizeof(uintmax_t)*3+3+LDBL_MANT_DIG/4];
+	const char *prefix;
+	int t, pl;
+	wchar_t wc[2], *ws;
+	char mb[4];
+
+	for (;;) {
+		/* Update output count, end loop when fmt is exhausted */
+		if (cnt >= 0) {
+			if (l > INT_MAX - cnt) {
+				errno = EOVERFLOW;
+				cnt = -1;
+			} else cnt += l;
+		}
+		if (!*s) break;
+
+		/* Handle literal text and %% format specifiers */
+		for (a=s; *s && *s!='%'; s++);
+		for (z=s; s[0]=='%' && s[1]=='%'; z++, s+=2);
+		l = z-a;
+		if (f) out(f, a, l);
+		if (l) continue;
+
+		if (isdigit(s[1]) && s[2]=='$') {
+			l10n=1;
+			argpos = s[1]-'0';
+			s+=3;
+		} else {
+			argpos = -1;
+			s++;
+		}
+
+		/* Read modifier flags */
+		for (fl=0; (unsigned)*s-' '<32 && (FLAGMASK&(1U<<*s-' ')); s++)
+			fl |= 1U<<*s-' ';
+
+		/* Read field width */
+		if (*s=='*') {
+			if (isdigit(s[1]) && s[2]=='$') {
+				l10n=1;
+				nl_type[s[1]-'0'] = INT;
+				w = nl_arg[s[1]-'0'].i;
+				s+=3;
+			} else if (!l10n) {
+				w = f ? va_arg(*ap, int) : 0;
+				s++;
+			} else return -1;
+			if (w<0) fl|=LEFT_ADJ, w=-w;
+		} else if ((w=getint(&s))<0) return -1;
+
+		/* Read precision */
+		if (*s=='.' && s[1]=='*') {
+			if (isdigit(s[2]) && s[3]=='$') {
+				nl_type[s[2]-'0'] = INT;
+				p = nl_arg[s[2]-'0'].i;
+				s+=4;
+			} else if (!l10n) {
+				p = f ? va_arg(*ap, int) : 0;
+				s+=2;
+			} else return -1;
+		} else if (*s=='.') {
+			s++;
+			p = getint(&s);
+		} else p = -1;
+
+		/* Format specifier state machine */
+		st=0;
+		do {
+			if (OOB(*s)) return -1;
+			ps=st;
+			st=states[st]S(*s++);
+		} while (st-1<STOP);
+		if (!st) return -1;
+
+		/* Check validity of argument type (nl/normal) */
+		if (st==NOARG) {
+			if (argpos>=0) return -1;
+			else if (!f) continue;
+		} else {
+			if (argpos>=0) nl_type[argpos]=st, arg=nl_arg[argpos];
+			else if (f) pop_arg(&arg, st, ap);
+			else return 0;
+		}
+
+		if (!f) continue;
+
+		z = buf + sizeof(buf);
+		prefix = "-+   0X0x";
+		pl = 0;
+		t = s[-1];
+
+		/* Transform ls,lc -> S,C */
+		if (ps && (t&15)==3) t&=~32;
+
+		/* - and 0 flags are mutually exclusive */
+		if (fl & LEFT_ADJ) fl &= ~ZERO_PAD;
+
+		switch(t) {
+		case 'n':
+			switch(ps) {
+			case BARE: *(int *)arg.p = cnt; break;
+			case LPRE: *(long *)arg.p = cnt; break;
+			case LLPRE: *(long long *)arg.p = cnt; break;
+			case HPRE: *(unsigned short *)arg.p = cnt; break;
+			case HHPRE: *(unsigned char *)arg.p = cnt; break;
+			case ZTPRE: *(size_t *)arg.p = cnt; break;
+			case JPRE: *(uintmax_t *)arg.p = cnt; break;
+			}
+			continue;
+		case 'p':
+			p = MAX(p, 2*sizeof(void*));
+			t = 'x';
+			fl |= ALT_FORM;
+		case 'x': case 'X':
+			a = fmt_x(arg.i, z, t&32);
+			if (arg.i && (fl & ALT_FORM)) prefix+=(t>>4), pl=2;
+			if (0) {
+		case 'o':
+			a = fmt_o(arg.i, z);
+			if ((fl&ALT_FORM) && arg.i) prefix+=5, pl=1;
+			} if (0) {
+		case 'd': case 'i':
+			pl=1;
+			if (arg.i>INTMAX_MAX) {
+				arg.i=-arg.i;
+			} else if (fl & MARK_POS) {
+				prefix++;
+			} else if (fl & PAD_POS) {
+				prefix+=2;
+			} else pl=0;
+		case 'u':
+			a = fmt_u(arg.i, z);
+			}
+			if (p>=0) fl &= ~ZERO_PAD;
+			if (!arg.i && !p) {
+				a=z;
+				break;
+			}
+			p = MAX(p, z-a + !arg.i);
+			break;
+		case 'c':
+			*(a=z-(p=1))=arg.i;
+			fl &= ~ZERO_PAD;
+			break;
+		case 'm':
+			if (1) a = strerror(errno); else
+		case 's':
+			a = arg.p ? arg.p : "(null)";
+			z = memchr(a, 0, p);
+			if (!z) z=a+p;
+			else p=z-a;
+			fl &= ~ZERO_PAD;
+			break;
+		case 'C':
+			wc[0] = arg.i;
+			wc[1] = 0;
+			arg.p = wc;
+			p = -1;
+		case 'S':
+			ws = arg.p;
+			for (i=l=0; i<0U+p && *ws && (l=wctomb(mb, *ws++))>=0 && l<=0U+p-i; i+=l);
+			if (l<0) return -1;
+			p = i;
+			pad(f, ' ', w, p, fl);
+			ws = arg.p;
+			for (i=0; i<0U+p && *ws && i+(l=wctomb(mb, *ws++))<=p; i+=l)
+				out(f, mb, l);
+			pad(f, ' ', w, p, fl^LEFT_ADJ);
+			l = w>p ? w : p;
+			continue;
+#ifdef HAVE_FLOAT_SUPPORT
+		case 'e': case 'f': case 'g': case 'a':
+		case 'E': case 'F': case 'G': case 'A':
+			l = fmt_fp(f, arg.f, w, p, fl, t);
+			continue;
+#endif
+		}
+
+		if (p < z-a) p = z-a;
+		if (w < pl+p) w = pl+p;
+
+		pad(f, ' ', w, pl+p, fl);
+		out(f, prefix, pl);
+		pad(f, '0', w, pl+p, fl^ZERO_PAD);
+		pad(f, '0', p, z-a, 0);
+		out(f, a, z-a);
+		pad(f, ' ', w, pl+p, fl^LEFT_ADJ);
+
+		l = w;
+	}
+
+	if (f) return cnt;
+	if (!l10n) return 0;
+
+	for (i=1; i<=NL_ARGMAX && nl_type[i]; i++)
+		pop_arg(nl_arg+i, nl_type[i], ap);
+	for (; i<=NL_ARGMAX && !nl_type[i]; i++);
+	if (i<=NL_ARGMAX) return -1;
+	return 1;
+}
+
+int vfprintf(FILE *restrict f, const char *restrict fmt, va_list ap)
+{
+	va_list ap2;
+	int nl_type[NL_ARGMAX+1] = {0};
+	union arg nl_arg[NL_ARGMAX+1];
+	unsigned char internal_buf[80], *saved_buf = 0;
+	int ret;
+
+	va_copy(ap2, ap);
+	if (printf_core(0, fmt, &ap2, nl_arg, nl_type) < 0) return -1;
+
+	FLOCK(f);
+	if (!f->buf_size) {
+		saved_buf = f->buf;
+		f->wpos = f->wbase = f->buf = internal_buf;
+		f->buf_size = sizeof internal_buf;
+		f->wend = internal_buf + sizeof internal_buf;
+	}
+	ret = printf_core(f, fmt, &ap2, nl_arg, nl_type);
+	if (saved_buf) {
+		f->write(f, 0, 0);
+		if (!f->wpos) ret = -1;
+		f->buf = saved_buf;
+		f->buf_size = 0;
+		f->wpos = f->wbase = f->wend = 0;
+	}
+	FUNLOCK(f);
+	va_end(ap2);
+	return ret;
+}
diff --git a/libc/stdio/vfscanf.c b/libc/stdio/vfscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..62f3dcbeec1ce5ab8283f9130ddc8715c450ae86
--- /dev/null
+++ b/libc/stdio/vfscanf.c
@@ -0,0 +1,344 @@
+#include "stdio_impl.h"
+#include "shgetc.h"
+#include "intscan.h"
+#include "floatscan.h"
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <wchar.h>
+#include <wctype.h>
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <math.h>
+#include <float.h>
+#include <inttypes.h>
+
+#define SIZE_hh -2
+#define SIZE_h  -1
+#define SIZE_def 0
+#define SIZE_l   1
+#define SIZE_L   2
+#define SIZE_ll  3
+
+static void store_int(void *dest, int size, unsigned long long i)
+{
+	if (!dest) return;
+	switch (size) {
+	case SIZE_hh:
+		*(char *)dest = i;
+		break;
+	case SIZE_h:
+		*(short *)dest = i;
+		break;
+	case SIZE_def:
+		*(int *)dest = i;
+		break;
+	case SIZE_l:
+		*(long *)dest = i;
+		break;
+	case SIZE_ll:
+		*(long long *)dest = i;
+		break;
+	}
+}
+
+static void *arg_n(va_list ap, unsigned int n)
+{
+	void *p;
+	unsigned int i;
+	va_list ap2;
+	va_copy(ap2, ap);
+	for (i=n; i>1; i--) va_arg(ap2, void *);
+	p = va_arg(ap2, void *);
+	va_end(ap2);
+	return p;
+}
+
+static int readwc(int c, wchar_t **wcs, mbstate_t *st)
+{
+	char ch = c;
+	wchar_t wc;
+	switch (mbrtowc(&wc, &ch, 1, st)) {
+	case -1:
+		return -1;
+	case -2:
+		break;
+	default:
+		if (*wcs) *(*wcs)++ = wc;
+	}
+	return 0;
+}
+
+int vfscanf(FILE *restrict f, const char *restrict fmt, va_list ap)
+{
+	int width;
+	int size;
+	int base;
+	const unsigned char *p;
+	int c, t;
+	char *s;
+	wchar_t *wcs;
+	mbstate_t st;
+	void *dest=NULL;
+	int invert;
+	int matches=0;
+	unsigned long long x;
+#ifdef HAVE_FLOAT_SUPPORT
+	long double y;
+#endif
+	off_t pos = 0;
+
+	FLOCK(f);
+
+	for (p=(const unsigned char *)fmt; *p; p++) {
+
+		if (isspace(*p)) {
+			while (isspace(p[1])) p++;
+			shlim(f, 0);
+			while (isspace(shgetc(f)));
+			shunget(f);
+			pos += shcnt(f);
+			continue;
+		}
+		if (*p != '%' || p[1] == '%') {
+			p += *p=='%';
+			shlim(f, 0);
+			c = shgetc(f);
+			if (c!=*p) {
+				shunget(f);
+				if (c<0) goto input_fail;
+				goto match_fail;
+			}
+			pos++;
+			continue;
+		}
+
+		p++;
+		if (*p=='*') {
+			dest = 0; p++;
+		} else if (isdigit(*p) && p[1]=='$') {
+			dest = arg_n(ap, *p-'0'); p+=2;
+		} else {
+			dest = va_arg(ap, void *);
+		}
+
+		for (width=0; isdigit(*p); p++) {
+			width = 10*width + *p - '0';
+		}
+
+		if (*p=='m') {
+			p++;
+		}
+
+		size = SIZE_def;
+		switch (*p++) {
+		case 'h':
+			if (*p == 'h') p++, size = SIZE_hh;
+			else size = SIZE_h;
+			break;
+		case 'l':
+			if (*p == 'l') p++, size = SIZE_ll;
+			else size = SIZE_l;
+			break;
+		case 'j':
+			size = SIZE_ll;
+			break;
+		case 'z':
+		case 't':
+			size = SIZE_l;
+			break;
+		case 'L':
+			size = SIZE_L;
+			break;
+		case 'd': case 'i': case 'o': case 'u': case 'x':
+		case 'a': case 'e': case 'f': case 'g':
+		case 'A': case 'E': case 'F': case 'G': case 'X':
+		case 's': case 'c': case '[':
+		case 'S': case 'C':
+		case 'p': case 'n':
+			p--;
+			break;
+		default:
+			goto fmt_fail;
+		}
+
+		t = *p;
+
+		switch (t) {
+		case 'C':
+		case 'c':
+			if (width < 1) width = 1;
+		case 's':
+			if (size == SIZE_l) t &= ~0x20;
+		case 'd': case 'i': case 'o': case 'u': case 'x':
+		case 'a': case 'e': case 'f': case 'g':
+		case 'A': case 'E': case 'F': case 'G': case 'X':
+		case '[': case 'S':
+		case 'p': case 'n':
+			if (width < 1) width = 0;
+			break;
+		default:
+			goto fmt_fail;
+		}
+
+		shlim(f, width);
+
+		if (t != 'n') {
+			if (shgetc(f) < 0) goto input_fail;
+			shunget(f);
+		}
+
+		switch (t) {
+		case 'n':
+			store_int(dest, size, pos);
+			/* do not increment match count, etc! */
+			continue;
+		case 'C':
+			wcs = dest;
+			st = (mbstate_t){ 0 };
+			while ((c=shgetc(f)) >= 0) {
+				if (readwc(c, &wcs, &st) < 0)
+					goto input_fail;
+			}
+			if (!mbsinit(&st)) goto input_fail;
+			if (shcnt(f) != width) goto match_fail;
+			break;
+		case 'c':
+			if (dest) {
+				s = dest;
+				while ((c=shgetc(f)) >= 0) *s++ = c;
+			} else {
+				while (shgetc(f)>=0);
+			}
+			if (shcnt(f) < width) goto match_fail;
+			break;
+		case '[':
+			s = dest;
+			wcs = dest;
+
+			if (*++p == '^') p++, invert = 1;
+			else invert = 0;
+
+			unsigned char scanset[257];
+			memset(scanset, invert, sizeof scanset);
+
+			scanset[0] = 0;
+			if (*p == '-') p++, scanset[1+'-'] = 1-invert;
+			else if (*p == ']') p++, scanset[1+']'] = 1-invert;
+			for (; *p != ']'; p++) {
+				if (!*p) goto fmt_fail;
+				if (*p=='-' && p[1] && p[1] != ']')
+					for (c=p++[-1]; c<*p; c++)
+						scanset[1+c] = 1-invert;
+				scanset[1+*p] = 1-invert;
+			}
+
+			if (size == SIZE_l) {
+				st = (mbstate_t){0};
+				while (scanset[(c=shgetc(f))+1]) {
+					if (readwc(c, &wcs, &st) < 0)
+						goto input_fail;
+				}
+				if (!mbsinit(&st)) goto input_fail;
+				s = 0;
+			} else if (s) {
+				while (scanset[(c=shgetc(f))+1])
+					*s++ = c;
+				wcs = 0;
+			} else {
+				while (scanset[(c=shgetc(f))+1]);
+			}
+			shunget(f);
+			if (!shcnt(f)) goto match_fail;
+			if (s) *s = 0;
+			if (wcs) *wcs = 0;
+			break;
+		default:
+			shlim(f, 0);
+			while (isspace(shgetc(f)));
+			shunget(f);
+			pos += shcnt(f);
+			shlim(f, width);
+			if (shgetc(f) < 0) goto input_fail;
+			shunget(f);
+		}
+
+		switch (t) {
+		case 'p':
+		case 'X':
+		case 'x':
+			base = 16;
+			goto int_common;
+		case 'o':
+			base = 8;
+			goto int_common;
+		case 'd':
+		case 'u':
+			base = 10;
+			goto int_common;
+		case 'i':
+			base = 0;
+		int_common:
+			x = __intscan(f, base, 0, ULLONG_MAX);
+			if (!shcnt(f)) goto match_fail;
+			if (t=='p' && dest) *(void **)dest = (void *)(uintptr_t)x;
+			else store_int(dest, size, x);
+			break;
+#ifdef HAVE_FLOAT_SUPPORT
+		case 'a': case 'A':
+		case 'e': case 'E':
+		case 'f': case 'F':
+		case 'g': case 'G':
+			y = __floatscan(f, size, 0);
+			if (!shcnt(f)) goto match_fail;
+			if (dest) switch (size) {
+			case SIZE_def:
+				*(float *)dest = y;
+				break;
+			case SIZE_l:
+				*(double *)dest = y;
+				break;
+			case SIZE_L:
+				*(long double *)dest = y;
+				break;
+			}
+			break;
+#endif
+		case 'S':
+			wcs = dest;
+			st = (mbstate_t){ 0 };
+			while (!isspace(c=shgetc(f)) && c!=EOF) {
+				if (readwc(c, &wcs, &st) < 0)
+					goto input_fail;
+			}
+			shunget(f);
+			if (!mbsinit(&st)) goto input_fail;
+			if (dest) *wcs++ = 0;
+			break;
+		case 's':
+			if (dest) {
+				s = dest;
+				while (!isspace(c=shgetc(f)) && c!=EOF)
+					*s++ = c;
+				*s = 0;
+			} else {
+				while (!isspace(c=shgetc(f)) && c!=EOF);
+			}
+			shunget(f);
+			break;
+		}
+
+		pos += shcnt(f);
+		if (dest) matches++;
+	}
+	if (0) {
+fmt_fail:
+input_fail:
+		if (!matches) matches--;
+	}
+match_fail:
+	FUNLOCK(f);
+	return matches;
+}
diff --git a/libc/stdio/vfwprintf.c b/libc/stdio/vfwprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..7f8bf29122f7fc528b7c3bc6ae1f2b4c4a7dd34b
--- /dev/null
+++ b/libc/stdio/vfwprintf.c
@@ -0,0 +1,363 @@
+#include "stdio_impl.h"
+#include <errno.h>
+#include <ctype.h>
+#include <limits.h>
+#include <string.h>
+#include <stdarg.h>
+#include <wchar.h>
+#include <wctype.h>
+#include <inttypes.h>
+
+#define NL_ARGMAX _POSIX_ARG_MAX
+
+/* Convenient bit representation for modifier flags, which all fall
+ * within 31 codepoints of the space character. */
+
+#define ALT_FORM   (1U<<'#'-' ')
+#define ZERO_PAD   (1U<<'0'-' ')
+#define LEFT_ADJ   (1U<<'-'-' ')
+#define PAD_POS    (1U<<' '-' ')
+#define MARK_POS   (1U<<'+'-' ')
+#define GROUPED    (1U<<'\''-' ')
+
+#define FLAGMASK (ALT_FORM|ZERO_PAD|LEFT_ADJ|PAD_POS|MARK_POS|GROUPED)
+
+#if UINT_MAX == ULONG_MAX
+#define LONG_IS_INT
+#endif
+
+#if SIZE_MAX != ULONG_MAX || UINTMAX_MAX != ULLONG_MAX
+#define ODD_TYPES
+#endif
+
+/* State machine to accept length modifiers + conversion specifiers.
+ * Result is 0 on failure, or an argument type to pop on success. */
+
+enum {
+	BARE, LPRE, LLPRE, HPRE, HHPRE, BIGLPRE,
+	ZTPRE, JPRE,
+	STOP,
+	PTR, INT, UINT, ULLONG,
+#ifndef LONG_IS_INT
+	LONG, ULONG,
+#else
+#define LONG INT
+#define ULONG UINT
+#endif
+	SHORT, USHORT, CHAR, UCHAR,
+#ifdef ODD_TYPES
+	LLONG, SIZET, IMAX, UMAX, PDIFF, UIPTR,
+#else
+#define LLONG ULLONG
+#define SIZET ULONG
+#define IMAX LLONG
+#define UMAX ULLONG
+#define PDIFF LONG
+#define UIPTR ULONG
+#endif
+	DBL, LDBL,
+	NOARG,
+	MAXSTATE
+};
+
+#define S(x) [(x)-'A']
+
+static const unsigned char states[]['z'-'A'+1] = {
+	{ /* 0: bare types */
+		S('d') = INT, S('i') = INT,
+		S('o') = UINT, S('u') = UINT, S('x') = UINT, S('X') = UINT,
+		S('e') = DBL, S('f') = DBL, S('g') = DBL, S('a') = DBL,
+		S('E') = DBL, S('F') = DBL, S('G') = DBL, S('A') = DBL,
+		S('c') = CHAR, S('C') = INT,
+		S('s') = PTR, S('S') = PTR, S('p') = UIPTR, S('n') = PTR,
+		S('m') = NOARG,
+		S('l') = LPRE, S('h') = HPRE, S('L') = BIGLPRE,
+		S('z') = ZTPRE, S('j') = JPRE, S('t') = ZTPRE,
+	}, { /* 1: l-prefixed */
+		S('d') = LONG, S('i') = LONG,
+		S('o') = ULONG, S('u') = ULONG, S('x') = ULONG, S('X') = ULONG,
+		S('c') = INT, S('s') = PTR, S('n') = PTR,
+		S('l') = LLPRE,
+	}, { /* 2: ll-prefixed */
+		S('d') = LLONG, S('i') = LLONG,
+		S('o') = ULLONG, S('u') = ULLONG,
+		S('x') = ULLONG, S('X') = ULLONG,
+		S('n') = PTR,
+	}, { /* 3: h-prefixed */
+		S('d') = SHORT, S('i') = SHORT,
+		S('o') = USHORT, S('u') = USHORT,
+		S('x') = USHORT, S('X') = USHORT,
+		S('n') = PTR,
+		S('h') = HHPRE,
+	}, { /* 4: hh-prefixed */
+		S('d') = CHAR, S('i') = CHAR,
+		S('o') = UCHAR, S('u') = UCHAR,
+		S('x') = UCHAR, S('X') = UCHAR,
+		S('n') = PTR,
+	}, { /* 5: L-prefixed */
+		S('e') = LDBL, S('f') = LDBL, S('g') = LDBL, S('a') = LDBL,
+		S('E') = LDBL, S('F') = LDBL, S('G') = LDBL, S('A') = LDBL,
+		S('n') = PTR,
+	}, { /* 6: z- or t-prefixed (assumed to be same size) */
+		S('d') = PDIFF, S('i') = PDIFF,
+		S('o') = SIZET, S('u') = SIZET,
+		S('x') = SIZET, S('X') = SIZET,
+		S('n') = PTR,
+	}, { /* 7: j-prefixed */
+		S('d') = IMAX, S('i') = IMAX,
+		S('o') = UMAX, S('u') = UMAX,
+		S('x') = UMAX, S('X') = UMAX,
+		S('n') = PTR,
+	}
+};
+
+#define OOB(x) ((unsigned)(x)-'A' > 'z'-'A')
+
+union arg
+{
+	uintmax_t i;
+	long double f;
+	void *p;
+};
+
+static void pop_arg(union arg *arg, int type, va_list *ap)
+{
+	/* Give the compiler a hint for optimizing the switch. */
+	if ((unsigned)type > MAXSTATE) return;
+	switch (type) {
+	       case PTR:	arg->p = va_arg(*ap, void *);
+	break; case INT:	arg->i = va_arg(*ap, int);
+	break; case UINT:	arg->i = va_arg(*ap, unsigned int);
+#ifndef LONG_IS_INT
+	break; case LONG:	arg->i = va_arg(*ap, long);
+	break; case ULONG:	arg->i = va_arg(*ap, unsigned long);
+#endif
+	break; case ULLONG:	arg->i = va_arg(*ap, unsigned long long);
+	break; case SHORT:	arg->i = (short)va_arg(*ap, int);
+	break; case USHORT:	arg->i = (unsigned short)va_arg(*ap, int);
+	break; case CHAR:	arg->i = (signed char)va_arg(*ap, int);
+	break; case UCHAR:	arg->i = (unsigned char)va_arg(*ap, int);
+#ifdef ODD_TYPES
+	break; case LLONG:	arg->i = va_arg(*ap, long long);
+	break; case SIZET:	arg->i = va_arg(*ap, size_t);
+	break; case IMAX:	arg->i = va_arg(*ap, intmax_t);
+	break; case UMAX:	arg->i = va_arg(*ap, uintmax_t);
+	break; case PDIFF:	arg->i = va_arg(*ap, ptrdiff_t);
+	break; case UIPTR:	arg->i = (uintptr_t)va_arg(*ap, void *);
+#endif
+	break; case DBL:	arg->f = va_arg(*ap, double);
+	break; case LDBL:	arg->f = va_arg(*ap, long double);
+	}
+}
+
+static void out(FILE *f, const wchar_t *s, size_t l)
+{
+	while (l--) fputwc(*s++, f);
+}
+
+static int getint(wchar_t **s) {
+	int i;
+	for (i=0; iswdigit(**s); (*s)++)
+		i = 10*i + (**s-'0');
+	return i;
+}
+
+static const char sizeprefix['y'-'a'] = {
+['a'-'a']='L', ['e'-'a']='L', ['f'-'a']='L', ['g'-'a']='L',
+['d'-'a']='j', ['i'-'a']='j', ['o'-'a']='j', ['u'-'a']='j', ['x'-'a']='j',
+['p'-'a']='j'
+};
+
+static int wprintf_core(FILE *f, const wchar_t *fmt, va_list *ap, union arg *nl_arg, int *nl_type)
+{
+	wchar_t *a, *z, *s=(wchar_t *)fmt;
+	unsigned l10n=0, litpct, fl;
+	int w, p;
+	union arg arg;
+	int argpos;
+	unsigned st, ps;
+	int cnt=0, l=0;
+	int i;
+	int t;
+	char *bs;
+	char charfmt[16];
+	wchar_t wc;
+
+	for (;;) {
+		/* Update output count, end loop when fmt is exhausted */
+		if (cnt >= 0) {
+			if (l > INT_MAX - cnt) {
+				if (!ferror(f)) errno = EOVERFLOW;
+				cnt = -1;
+			} else cnt += l;
+		}
+		if (!*s) break;
+
+		/* Handle literal text and %% format specifiers */
+		for (a=s; *s && *s!='%'; s++);
+		litpct = wcsspn(s, L"%")/2; /* Optimize %%%% runs */
+		z = s+litpct;
+		s += 2*litpct;
+		l = z-a;
+		if (f) out(f, a, l);
+		if (l) continue;
+
+		if (iswdigit(s[1]) && s[2]=='$') {
+			l10n=1;
+			argpos = s[1]-'0';
+			s+=3;
+		} else {
+			argpos = -1;
+			s++;
+		}
+
+		/* Read modifier flags */
+		for (fl=0; (unsigned)*s-' '<32 && (FLAGMASK&(1U<<*s-' ')); s++)
+			fl |= 1U<<*s-' ';
+
+		/* Read field width */
+		if (*s=='*') {
+			if (iswdigit(s[1]) && s[2]=='$') {
+				l10n=1;
+				nl_type[s[1]-'0'] = INT;
+				w = nl_arg[s[1]-'0'].i;
+				s+=3;
+			} else if (!l10n) {
+				w = f ? va_arg(*ap, int) : 0;
+				s++;
+			} else return -1;
+			if (w<0) fl|=LEFT_ADJ, w=-w;
+		} else if ((w=getint(&s))<0) return -1;
+
+		/* Read precision */
+		if (*s=='.' && s[1]=='*') {
+			if (isdigit(s[2]) && s[3]=='$') {
+				nl_type[s[2]-'0'] = INT;
+				p = nl_arg[s[2]-'0'].i;
+				s+=4;
+			} else if (!l10n) {
+				p = f ? va_arg(*ap, int) : 0;
+				s+=2;
+			} else return -1;
+		} else if (*s=='.') {
+			s++;
+			p = getint(&s);
+		} else p = -1;
+
+		/* Format specifier state machine */
+		st=0;
+		do {
+			if (OOB(*s)) return -1;
+			ps=st;
+			st=states[st]S(*s++);
+		} while (st-1<STOP);
+		if (!st) return -1;
+
+		/* Check validity of argument type (nl/normal) */
+		if (st==NOARG) {
+			if (argpos>=0) return -1;
+			else if (!f) continue;
+		} else {
+			if (argpos>=0) nl_type[argpos]=st, arg=nl_arg[argpos];
+			else if (f) pop_arg(&arg, st, ap);
+			else return 0;
+		}
+
+		if (!f) continue;
+		t = s[-1];
+		if (ps && (t&15)==3) t&=~32;
+
+		switch (t) {
+		case 'n':
+			switch(ps) {
+			case BARE: *(int *)arg.p = cnt; break;
+			case LPRE: *(long *)arg.p = cnt; break;
+			case LLPRE: *(long long *)arg.p = cnt; break;
+			case HPRE: *(unsigned short *)arg.p = cnt; break;
+			case HHPRE: *(unsigned char *)arg.p = cnt; break;
+			case ZTPRE: *(size_t *)arg.p = cnt; break;
+			case JPRE: *(uintmax_t *)arg.p = cnt; break;
+			}
+			continue;
+		case 'c':
+			fputwc(btowc(arg.i), f);
+			l = 1;
+			continue;
+		case 'C':
+			fputwc(arg.i, f);
+			l = 1;
+			continue;
+		case 'S':
+			a = arg.p;
+			z = wmemchr(a, 0, p);
+			if (!z) z=a+p;
+			else p=z-a;
+			if (w<p) w=p;
+			if (!(fl&LEFT_ADJ)) fprintf(f, "%.*s", w-p, "");
+			out(f, a, p);
+			if ((fl&LEFT_ADJ)) fprintf(f, "%.*s", w-p, "");
+			l=w;
+			continue;
+		case 's':
+			bs = arg.p;
+			if (p<0) p = INT_MAX;
+			for (i=l=0; l<p && (i=mbtowc(&wc, bs, MB_LEN_MAX))>0; bs+=i, l++);
+			if (i<0) return -1;
+			p=l;
+			if (w<p) w=p;
+			if (!(fl&LEFT_ADJ)) fprintf(f, "%.*s", w-p, "");
+			bs = arg.p;
+			while (l--) {
+				i=mbtowc(&wc, bs, MB_LEN_MAX);
+				bs+=i;
+				fputwc(wc, f);
+			}
+			if ((fl&LEFT_ADJ)) fprintf(f, "%.*s", w-p, "");
+			l=w;
+			continue;
+		}
+
+		snprintf(charfmt, sizeof charfmt, "%%%s%s%s%s%s*.*%c%c",
+			"#"+!(fl & ALT_FORM),
+			"+"+!(fl & MARK_POS),
+			"-"+!(fl & LEFT_ADJ),
+			" "+!(fl & PAD_POS),
+			"0"+!(fl & ZERO_PAD),
+			sizeprefix[(t|32)-'a'], t);
+
+		switch (t|32) {
+		case 'a': case 'e': case 'f': case 'g':
+			l = fprintf(f, charfmt, w, p, arg.f);
+			break;
+		case 'd': case 'i': case 'o': case 'u': case 'x': case 'p':
+			l = fprintf(f, charfmt, w, p, arg.i);
+			break;
+		}
+	}
+
+	if (f) return cnt;
+	if (!l10n) return 0;
+
+	for (i=1; i<=NL_ARGMAX && nl_type[i]; i++)
+		pop_arg(nl_arg+i, nl_type[i], ap);
+	for (; i<=NL_ARGMAX && !nl_type[i]; i++);
+	if (i<=NL_ARGMAX) return -1;
+	return 1;
+}
+
+int vfwprintf(FILE *restrict f, const wchar_t *restrict fmt, va_list ap)
+{
+	va_list ap2;
+	int nl_type[NL_ARGMAX] = {0};
+	union arg nl_arg[NL_ARGMAX];
+	int ret;
+
+	va_copy(ap2, ap);
+	if (wprintf_core(0, fmt, &ap2, nl_arg, nl_type) < 0) return -1;
+
+	FLOCK(f);
+	ret = wprintf_core(f, fmt, &ap2, nl_arg, nl_type);
+	FUNLOCK(f);
+	va_end(ap2);
+	return ret;
+}
diff --git a/libc/stdio/vfwscanf.c b/libc/stdio/vfwscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..7670282c2e405c1631fa62220562aa7e22dad5c8
--- /dev/null
+++ b/libc/stdio/vfwscanf.c
@@ -0,0 +1,309 @@
+#include "stdio_impl.h"
+#include "shgetc.h"
+#include "intscan.h"
+#include "floatscan.h"
+
+#include <stdlib.h>
+#include <stdarg.h>
+#include <ctype.h>
+#include <wchar.h>
+#include <wctype.h>
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <math.h>
+#include <float.h>
+
+
+#define SIZE_hh -2
+#define SIZE_h  -1
+#define SIZE_def 0
+#define SIZE_l   1
+#define SIZE_L   2
+#define SIZE_ll  3
+
+static void store_int(void *dest, int size, unsigned long long i)
+{
+	if (!dest) return;
+	switch (size) {
+	case SIZE_hh:
+		*(char *)dest = i;
+		break;
+	case SIZE_h:
+		*(short *)dest = i;
+		break;
+	case SIZE_def:
+		*(int *)dest = i;
+		break;
+	case SIZE_l:
+		*(long *)dest = i;
+		break;
+	case SIZE_ll:
+		*(long long *)dest = i;
+		break;
+	}
+}
+
+static void *arg_n(va_list ap, unsigned int n)
+{
+	void *p;
+	unsigned int i;
+	va_list ap2;
+	va_copy(ap2, ap);
+	for (i=n; i>1; i--) va_arg(ap2, void *);
+	p = va_arg(ap2, void *);
+	va_end(ap2);
+	return p;
+}
+
+static int in_set(const wchar_t *set, int c)
+{
+	int j;
+	const wchar_t *p = set;
+	if (*p == '-') {
+		if (c=='-') return 1;
+		p++;
+	} else if (*p == ']') {
+		if (c==']') return 1;
+		p++;
+	}
+	for (; *p && *p != ']'; p++) {
+		if (*p=='-' && p[1] && p[1] != ']')
+			for (j=p++[-1]; j<*p; j++)
+				if (c==j) return 1;
+		if (c==*p) return 1;
+	}
+	return 0;
+}
+
+#if 1
+#undef getwc
+#define getwc(f) \
+	((f)->rpos < (f)->rend && *(f)->rpos < 128 ? *(f)->rpos++ : (getwc)(f))
+
+#undef ungetwc
+#define ungetwc(c,f) \
+	((f)->rend && (c)<128U ? *--(f)->rpos : ungetwc((c),(f)))
+#endif
+
+int vfwscanf(FILE *restrict f, const wchar_t *restrict fmt, va_list ap)
+{
+	int width;
+	int size;
+	const wchar_t *p;
+	int c, t;
+	char *s;
+	wchar_t *wcs;
+	void *dest=NULL;
+	int invert;
+	int matches=0;
+	off_t pos = 0, cnt;
+	static const char size_pfx[][3] = { "hh", "h", "", "l", "L", "ll" };
+	char tmp[3*sizeof(int)+10];
+
+	FLOCK(f);
+
+	for (p=fmt; *p; p++) {
+
+		if (iswspace(*p)) {
+			while (iswspace(p[1])) p++;
+			while (iswspace((c=getwc(f)))) pos++;
+			ungetwc(c, f);
+			continue;
+		}
+		if (*p != '%' || p[1] == '%') {
+			p += *p=='%';
+			c = getwc(f);
+			if (c!=*p) {
+				ungetwc(c, f);
+				if (c<0) goto input_fail;
+				goto match_fail;
+			}
+			pos++;
+			continue;
+		}
+
+		p++;
+		if (*p=='*') {
+			dest = 0; p++;
+		} else if (iswdigit(*p) && p[1]=='$') {
+			dest = arg_n(ap, *p-'0'); p+=2;
+		} else {
+			dest = va_arg(ap, void *);
+		}
+
+		for (width=0; iswdigit(*p); p++) {
+			width = 10*width + *p - '0';
+		}
+
+		if (*p=='m') {
+			p++;
+		}
+
+		size = SIZE_def;
+		switch (*p++) {
+		case 'h':
+			if (*p == 'h') p++, size = SIZE_hh;
+			else size = SIZE_h;
+			break;
+		case 'l':
+			if (*p == 'l') p++, size = SIZE_ll;
+			else size = SIZE_l;
+			break;
+		case 'j':
+			size = SIZE_ll;
+			break;
+		case 'z':
+		case 't':
+			size = SIZE_l;
+			break;
+		case 'L':
+			size = SIZE_L;
+			break;
+		case 'd': case 'i': case 'o': case 'u': case 'x':
+		case 'a': case 'e': case 'f': case 'g':
+		case 'A': case 'E': case 'F': case 'G': case 'X':
+		case 's': case 'c': case '[':
+		case 'S': case 'C':
+		case 'p': case 'n':
+			p--;
+			break;
+		default:
+			goto fmt_fail;
+		}
+
+		t = *p;
+
+		/* Transform ls,lc -> S,C */
+		if (size==SIZE_l && (t&15)==3) t&=~32;
+
+		if (t != 'n') {
+			if (t != '[' && (t|32) != 'c')
+				while (iswspace((c=getwc(f)))) pos++;
+			else
+				c=getwc(f);
+			if (c < 0) goto input_fail;
+			ungetwc(c, f);
+		}
+
+		switch (t) {
+		case 'n':
+			store_int(dest, size, pos);
+			/* do not increment match count, etc! */
+			continue;
+
+		case 'c':
+			if (width < 1) width = 1;
+			s = dest;
+			for (; width && (c=getwc(f)) >= 0; width--) {
+				int l = wctomb(s?s:tmp, c);
+				if (l<0) goto input_fail;
+				if (s) s+=l;
+				pos++;
+			}
+			if (width) goto match_fail;
+			break;
+
+		case 'C':
+			if (width < 1) width = 1;
+			wcs = dest;
+			for (; width && (c=getwc(f)) >= 0; width--) {
+				pos++;
+				if (wcs)
+					*wcs++ = c;
+			}
+			if (width) goto match_fail;
+			break;
+
+		case 's':
+			if (width < 1) width = -1;
+			s = dest;
+			while (width && !iswspace(c=getwc(f)) && c!=EOF) {
+				int l = wctomb(s?s:tmp, c);
+				if (l<0) goto input_fail;
+				if (s) s+=l;
+				pos++;
+				width-=(width>0);
+			}
+			if (width) ungetwc(c, f);
+			if (s) *s = 0;
+			break;
+
+		case 'S':
+			wcs = dest;
+			if (width < 1) width = -1;
+			while (width && !iswspace(c=getwc(f)) && c!=EOF)
+				width-=(width>0), pos++, *wcs++ = c;
+			if (width) ungetwc(c, f);
+			if (wcs) *wcs = 0;
+			break;
+
+		case '[':
+			s = (size == SIZE_def) ? dest : 0;
+			wcs = (size == SIZE_l) ? dest : 0;
+
+			if (*++p == '^') p++, invert = 1;
+			else invert = 0;
+
+			int gotmatch = 0;
+
+			if (width < 1) width = -1;
+
+			while (width) {
+				if ((c=getwc(f))<0) break;
+				if (in_set(p, c) == invert)
+					break;
+				if (wcs) {
+					*wcs++ = c;
+				} else if (size != SIZE_l) {
+					int l = wctomb(s?s:tmp, c);
+					if (l<0) goto input_fail;
+					if (s) s+=l;
+				}
+				pos++;
+				width-=(width>0);
+				gotmatch=1;
+			}
+			if (width) ungetwc(c, f);
+
+			if (!gotmatch) goto match_fail;
+
+			if (*p==']') p++;
+			while (*p!=']') {
+				if (!*p) goto fmt_fail;
+				p++;
+			}
+
+			if (wcs) *wcs++ = 0;
+			if (s) *s++ = 0;
+			break;
+
+		case 'd': case 'i': case 'o': case 'u': case 'x':
+		case 'a': case 'e': case 'f': case 'g':
+		case 'A': case 'E': case 'F': case 'G': case 'X':
+		case 'p':
+			if (width < 1) width = 0;
+			snprintf(tmp, sizeof tmp, "%.*s%.0d%s%c%%lln",
+				1+!dest, "%*", width, size_pfx[size+2], t);
+			cnt = 0;
+			if (fscanf(f, tmp, dest?dest:&cnt, &cnt) == -1)
+				goto input_fail;
+			else if (!cnt)
+				goto match_fail;
+			pos += cnt;
+			break;
+		default:
+			goto fmt_fail;
+		}
+
+		if (dest) matches++;
+	}
+	if (0) {
+fmt_fail:
+input_fail:
+		if (!matches) matches--;
+	}
+match_fail:
+	FUNLOCK(f);
+	return matches;
+}
diff --git a/libc/stdio/vprintf.c b/libc/stdio/vprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..30d2bffa8821879fc28abac6cc3806b5788366ee
--- /dev/null
+++ b/libc/stdio/vprintf.c
@@ -0,0 +1,6 @@
+#include <stdio.h>
+
+int vprintf(const char *restrict fmt, va_list ap)
+{
+	return vfprintf(stdout, fmt, ap);
+}
diff --git a/libc/stdio/vscanf.c b/libc/stdio/vscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..26ed8f121a5bfdbb463d41a9d608414d687e83eb
--- /dev/null
+++ b/libc/stdio/vscanf.c
@@ -0,0 +1,7 @@
+#include "stdio.h"
+#include <stdarg.h>
+
+int vscanf(const char *restrict fmt, va_list ap)
+{
+	return vfscanf(stdin, fmt, ap);
+}
diff --git a/libc/stdio/vsnprintf.c b/libc/stdio/vsnprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..be2c44eb176d70a5d867b9f339dd58afe5953ec7
--- /dev/null
+++ b/libc/stdio/vsnprintf.c
@@ -0,0 +1,42 @@
+#include "stdio_impl.h"
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <stdint.h>
+
+static size_t sn_write(FILE *f, const unsigned char *s, size_t l)
+{
+	size_t k = f->wend - f->wpos;
+	if (k > l) k = l;
+	memcpy(f->wpos, s, k);
+	f->wpos += k;
+	/* pretend to succeed, but discard extra data */
+	return l;
+}
+
+int vsnprintf(char *restrict s, size_t n, const char *restrict fmt, va_list ap)
+{
+	int r;
+	char b;
+	FILE f = { .lbf = EOF, .write = sn_write, .lock = -1 };
+
+	if (n-1 > INT_MAX-1) {
+		if (n) {
+			errno = EOVERFLOW;
+			return -1;
+		}
+		s = &b;
+		n = 1;
+	}
+
+	/* Ensure pointers don't wrap if "infinite" n is passed in */
+	if (n > (char *)0+SIZE_MAX-s-1) n = (char *)0+SIZE_MAX-s-1;
+	f.buf_size = n;
+	f.buf = f.wpos = (void *)s;
+	f.wbase = f.wend = (void *)(s+n);
+	r = vfprintf(&f, fmt, ap);
+
+	/* Null-terminate, overwriting last char if dest buffer is full */
+	if (n) f.wpos[-(f.wpos == f.wend)] = 0;
+	return r;
+}
diff --git a/libc/stdio/vsprintf.c b/libc/stdio/vsprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..c57349d4d888d532b39a15d525d248b0eee3c48d
--- /dev/null
+++ b/libc/stdio/vsprintf.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+#include <limits.h>
+
+int vsprintf(char *restrict s, const char *restrict fmt, va_list ap)
+{
+	return vsnprintf(s, INT_MAX, fmt, ap);
+}
diff --git a/libc/stdio/vsscanf.c b/libc/stdio/vsscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..049f4dd0e6c506940fe1d25479da669cdd73991f
--- /dev/null
+++ b/libc/stdio/vsscanf.c
@@ -0,0 +1,15 @@
+#include "stdio_impl.h"
+
+static size_t do_read(FILE *f, unsigned char *buf, size_t len)
+{
+	return __string_read(f, buf, len);
+}
+
+int vsscanf(const char *restrict s, const char *restrict fmt, va_list ap)
+{
+	FILE f = {
+		.buf = (void *)s, .cookie = (void *)s,
+		.read = do_read, .lock = -1
+	};
+	return vfscanf(&f, fmt, ap);
+}
diff --git a/libc/stdio/vswprintf.c b/libc/stdio/vswprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..7d237bae72e945e5e4fdc459090e6ab75333636a
--- /dev/null
+++ b/libc/stdio/vswprintf.c
@@ -0,0 +1,53 @@
+#include "stdio_impl.h"
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <stdint.h>
+#include <wchar.h>
+
+struct cookie {
+	wchar_t *ws;
+	size_t l;
+};
+
+static size_t sw_write(FILE *f, const unsigned char *s, size_t l)
+{
+	size_t l0 = l;
+	int i = 0;
+	struct cookie *c = f->cookie;
+	if (s!=f->wbase && sw_write(f, f->wbase, f->wpos-f->wbase)==-1)
+		return -1;
+	while (c->l && l && (i=mbtowc(c->ws, (void *)s, l))>=0) {
+		s+=i;
+		l-=i;
+		c->l--;
+		c->ws++;
+	}
+	*c->ws = 0;
+	return i<0 ? i : l0;
+}
+
+int vswprintf(wchar_t *restrict s, size_t n, const wchar_t *restrict fmt, va_list ap)
+{
+	int r;
+	FILE f;
+	unsigned char buf[256];
+	struct cookie c = { s, n-1 };
+
+	memset(&f, 0, sizeof(FILE));
+	f.lbf = EOF;
+	f.write = sw_write;
+	f.buf_size = sizeof buf;
+	f.buf = buf;
+	f.lock = -1;
+	f.cookie = &c;
+	if (!n) {
+		return -1;
+	} else if (n > INT_MAX) {
+		errno = EOVERFLOW;
+		return -1;
+	}
+	r = vfwprintf(&f, fmt, ap);
+	sw_write(&f, 0, 0);
+	return r>=n ? -1 : r;
+}
diff --git a/libc/stdio/vswscanf.c b/libc/stdio/vswscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..7a2f7c7a98705c91a462c0bfbb3a029ae7d436f8
--- /dev/null
+++ b/libc/stdio/vswscanf.c
@@ -0,0 +1,36 @@
+#include "stdio_impl.h"
+#include <wchar.h>
+
+static size_t wstring_read(FILE *f, unsigned char *buf, size_t len)
+{
+	const wchar_t *src = f->cookie;
+	size_t k;
+
+	if (!src) return 0;
+
+	k = wcsrtombs((void *)f->buf, &src, f->buf_size, 0);
+	if (k==(size_t)-1) {
+		f->rpos = f->rend = 0;
+		return 0;
+	}
+
+	f->rpos = f->buf;
+	f->rend = f->buf + k;
+	f->cookie = (void *)src;
+
+	if (!len || !k) return 0;
+
+	*buf = *f->rpos++;
+	return 1;
+}
+
+int vswscanf(const wchar_t *restrict s, const wchar_t *restrict fmt, va_list ap)
+{
+	unsigned char buf[256];
+	FILE f = {
+		.buf = buf, .buf_size = sizeof buf,
+		.cookie = (void *)s,
+		.read = wstring_read, .lock = -1
+	};
+	return vfwscanf(&f, fmt, ap);
+}
diff --git a/libc/stdio/vwprintf.c b/libc/stdio/vwprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..eeeecdc7c62ae1508d135eeb5e52095550cbb0f6
--- /dev/null
+++ b/libc/stdio/vwprintf.c
@@ -0,0 +1,7 @@
+#include <stdio.h>
+#include <wchar.h>
+
+int vwprintf(const wchar_t *restrict fmt, va_list ap)
+{
+	return vfwprintf(stdout, fmt, ap);
+}
diff --git a/libc/stdio/vwscanf.c b/libc/stdio/vwscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..9297cf0d9455c183ee42fdb5d9c23f0081361fc9
--- /dev/null
+++ b/libc/stdio/vwscanf.c
@@ -0,0 +1,8 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int vwscanf(const wchar_t *restrict fmt, va_list ap)
+{
+	return vfwscanf(stdin, fmt, ap);
+}
diff --git a/libc/stdio/wprintf.c b/libc/stdio/wprintf.c
new file mode 100644
index 0000000000000000000000000000000000000000..342cd97911d365e4f787a95280b1ae7a9c631df3
--- /dev/null
+++ b/libc/stdio/wprintf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int wprintf(const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vwprintf(fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/stdio/wscanf.c b/libc/stdio/wscanf.c
new file mode 100644
index 0000000000000000000000000000000000000000..a207cc1b703c8ee130428daa82169a36a418f2d9
--- /dev/null
+++ b/libc/stdio/wscanf.c
@@ -0,0 +1,13 @@
+#include <stdio.h>
+#include <stdarg.h>
+#include <wchar.h>
+
+int wscanf(const wchar_t *restrict fmt, ...)
+{
+	int ret;
+	va_list ap;
+	va_start(ap, fmt);
+	ret = vwscanf(fmt, ap);
+	va_end(ap);
+	return ret;
+}
diff --git a/libc/temp/mktemp.c b/libc/temp/mktemp.c
index 992bc6d4b41e77273bddfd854ab9fc9b4232ffe7..c0e06f5ef424216c3b142999942b1146c801fa4d 100644
--- a/libc/temp/mktemp.c
+++ b/libc/temp/mktemp.c
@@ -6,12 +6,11 @@
 #include <errno.h>
 #include <time.h>
 #include <stdint.h>
-#include <sys/time.h>
 #include "libc.h"
 
 char *__mktemp(char *template)
 {
-	struct timeval tv;
+	struct timespec ts;
 	size_t i, l = strlen(template);
 	int retries = 10000;
 	unsigned long r;
@@ -22,8 +21,8 @@ char *__mktemp(char *template)
 		return template;
 	}
 	while (retries--) {
-		gettimeofday(&tv, NULL);
-		r = tv.tv_usec + (uintptr_t)&tv / 16 + (uintptr_t)template;
+		clock_gettime(CLOCK_REALTIME, &ts);
+		r = ts.tv_nsec + (uintptr_t)&ts / 16 + (uintptr_t)template;
 		for (i=1; i<=6; i++, r>>=4)
 			template[l-i] = 'A'+(r&15);
 		if (access(template, F_OK) < 0) return template;
diff --git a/libc/time.cc b/libc/time.cc
index 4262c9f235330c0f81c2f4091824258b316edc0a..2f3b5196b082cb0aab5a915ea4c4899e454641e1 100644
--- a/libc/time.cc
+++ b/libc/time.cc
@@ -1,4 +1,6 @@
 #include <sys/time.h>
+#include <time.h>
+#include "libc.hh"
 #include "drivers/clock.hh"
 #include "sched.hh"
 
@@ -25,3 +27,35 @@ int nanosleep(const struct timespec* req, struct timespec* rem)
     sched::thread::sleep_until(clock::get()->time() + convert(*req));
     return 0;
 }
+
+int clock_gettime(clockid_t clk_id, struct timespec* ts)
+{
+    if (clk_id != CLOCK_REALTIME) {
+        return libc_error(EINVAL);
+    }
+    u64 time = clock::get()->time();
+    auto sec = time / 1000000000;
+    auto nsec = time % 1000000000;
+    ts->tv_sec = sec;
+    ts->tv_nsec = nsec;
+    return 0;
+}
+
+int clock_getres(clockid_t clk_id, struct timespec* ts)
+{
+    if (clk_id != CLOCK_REALTIME) {
+        return libc_error(EINVAL);
+    }
+
+    if (ts) {
+        ts->tv_sec = 0;
+        ts->tv_nsec = 1;
+    }
+
+    return 0;
+}
+
+int clock_getcpuclockid(pid_t pid, clockid_t* clock_id)
+{
+    return libc_error(ENOSYS);
+}
diff --git a/loader.cc b/loader.cc
index 374151c71632ab225ea0c8ffc6712d17d692d4d7..241749c20dd7668fd74f3501b28b6c61faad96eb 100644
--- a/loader.cc
+++ b/loader.cc
@@ -282,7 +282,7 @@ void* do_main_thread(void* pprog)
 
     DeviceFactory::Instance()->InitializeDrivers();
 
-    //DriverFactory::Instance()->Destroy();
+    DriverFactory::Instance()->Destroy();
 
     auto t1 = clock::get()->time();
     auto t2 = clock::get()->time();
diff --git a/runtime.cc b/runtime.cc
index e5f4d7a735095f39ce8c15d85afb75c42a1912c8..fb786bf81b51fee879ec5ac16196cdd9f0567489 100644
--- a/runtime.cc
+++ b/runtime.cc
@@ -105,12 +105,6 @@ void __cxa_pure_virtual(void)
     abort();
 }
 
-void
-perror(const char* str)
-{
-    printf("%s: %s\n", str, strerror(errno));
-}
-
 namespace __cxxabiv1 {
     std::terminate_handler __terminate_handler = abort;
 
@@ -180,10 +174,6 @@ int _Uelf64_get_proc_name(unw_addr_space_t as, int pid, unw_word_t ip,
     return 0;
 }
 
-FILE* stdin;
-FILE* stdout;
-FILE* stderr;
-
 //    WCTDEF(alnum), WCTDEF(alpha), WCTDEF(blank), WCTDEF(cntrl),
 //    WCTDEF(digit), WCTDEF(graph), WCTDEF(lower), WCTDEF(print),
 //    WCTDEF(punct), WCTDEF(space), WCTDEF(upper), WCTDEF(xdigit),
@@ -197,86 +187,11 @@ static struct __locale_struct c_locale = {
     c_locale_array + 128, // __ctype_b
 };
 
-int ioctl(int fd, unsigned long request, ...)
-{
-    UNIMPLEMENTED("ioctl");
-}
-
 int poll(struct pollfd *fds, nfds_t nfds, int timeout)
 {
     UNIMPLEMENTED("poll");
 }
 
-int fileno(FILE *fp)
-{
-    UNIMPLEMENTED("fileno");
-}
-
-FILE *fdopen(int fd, const char *mode)
-{
-    UNIMPLEMENTED("fdopen");
-}
-
-int fflush(FILE *fp)
-{
-    UNIMPLEMENTED("fflush");
-}
-
-int fgetc(FILE *stream)
-{
-    UNIMPLEMENTED("fgetc");
-}
-
-#undef getc
-int getc(FILE *stream)
-{
-    UNIMPLEMENTED("getc");
-}
-
-int getchar(void)
-{
-    UNIMPLEMENTED("getchar");
-}
-
-char *gets(char *s)
-{
-    UNIMPLEMENTED("gets");
-}
-
-int ungetc(int c, FILE *stream)
-{
-    UNIMPLEMENTED("ungetc");
-}
-
-UNIMPL(int fputc(int c, FILE *stream))
-UNIMPL(int fputs(const char *s, FILE *stream))
-#undef putc
-UNIMPL(int putc(int c, FILE *stream))
-UNIMPL(int putchar(int c))
-
-int puts(const char *s)
-{
-	debug(s);
-	return 0;
-}
-
-int setvbuf(FILE *stream, char *buf, int mode, size_t size)
-{
-    debug("stub setvbuf()");
-    return 0;
-}
-UNIMPL(size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream))
-UNIMPL(size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream))
-UNIMPL(wint_t fgetwc(FILE *stream))
-UNIMPL(wint_t getwc(FILE *stream))
-UNIMPL(wint_t ungetwc(wint_t wc, FILE *stream))
-
-UNIMPL(int fseeko64(FILE *stream, off64_t offset, int whence))
-UNIMPL(off64_t ftell(FILE *stream))
-UNIMPL(FILE *fopen64(const char *path, const char *mode))
-UNIMPL(off64_t ftello64(FILE *stream))
-UNIMPL(wint_t fputwc(wchar_t wc, FILE *stream))
-UNIMPL(wint_t putwc(wchar_t wc, FILE *stream))
 UNIMPL(void __stack_chk_fail(void))
 UNIMPL(void __assert_fail(const char * assertion, const char * file, unsigned int line, const char * function))