Fix the handle locking in stdio

Fix the handle locking in stdio to use flockfile/funlockfile
internally when and where required.  Macros in <stdio.h> are updated
to automatically call the underlying functions when the process is
threaded to obtain the necessary locking.  A private mutex is added
to protect __sglue, the internal list of FILE handles, and another
to protect the one-time initialization.  Some routines in libc that
use getc() change to use getc_unlocked() as they're either protected
by their own lock or aren't thread-safe routines anyway.

Based on OpenBSD change by guenther@openbsd.org
http://www.mail-archive.com/source-changes@cvs.openbsd.org/msg01015.html

Bug: 3446659
Change-Id: Ie82116e358c541718d6709ec45ca6796be5a007b
diff --git a/libc/stdio/fgetln.c b/libc/stdio/fgetln.c
index 95a5b31..0947dd8 100644
--- a/libc/stdio/fgetln.c
+++ b/libc/stdio/fgetln.c
@@ -71,19 +71,18 @@
 fgetln(FILE *fp, size_t *lenp)
 {
 	unsigned char *p;
+	char *ret;
 	size_t len;
 	size_t off;
 
+	FLOCKFILE(fp);
+
 	/* make sure there is input */
-	if (fp->_r <= 0 && __srefill(fp)) {
-		*lenp = 0;
-		return (NULL);
-	}
+	if (fp->_r <= 0 && __srefill(fp))
+		goto error;
 
 	/* look for a newline in the input */
 	if ((p = memchr((void *)fp->_p, '\n', fp->_r)) != NULL) {
-		char *ret;
-
 		/*
 		 * Found one.  Flag buffer as modified to keep fseek from
 		 * `optimising' a backward seek, in case the user stomps on
@@ -95,6 +94,7 @@
 		fp->_flags |= __SMOD;
 		fp->_r -= len;
 		fp->_p = p;
+		FUNLOCKFILE(fp);
 		return (ret);
 	}
 
@@ -139,12 +139,15 @@
 		break;
 	}
 	*lenp = len;
+	ret = (char *)fp->_lb._base;
 #ifdef notdef
-	fp->_lb._base[len] = '\0';
+	ret[len] = '\0';
 #endif
-	return ((char *)fp->_lb._base);
+	FUNLOCKFILE(fp);
+	return (ret);
 
 error:
 	*lenp = 0;		/* ??? */
+	FUNLOCKFILE(fp);
 	return (NULL);		/* ??? */
 }