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/fgets.c b/libc/stdio/fgets.c
index f26385d..311b7b2 100644
--- a/libc/stdio/fgets.c
+++ b/libc/stdio/fgets.c
@@ -51,6 +51,7 @@
 	if (n <= 0)		/* sanity check */
 		return (NULL);
 
+	FLOCKFILE(fp);
 	_SET_ORIENTATION(fp, -1);
 	s = buf;
 	n--;			/* leave space for NUL */
@@ -61,8 +62,10 @@
 		if (fp->_r <= 0) {
 			if (__srefill(fp)) {
 				/* EOF/error: stop with partial or no line */
-				if (s == buf)
+				if (s == buf) {
+					FUNLOCKFILE(fp);
 					return (NULL);
+                                }
 				break;
 			}
 		}
@@ -84,6 +87,7 @@
 			fp->_p = t;
 			(void)memcpy((void *)s, (void *)p, len);
 			s[len] = '\0';
+			FUNLOCKFILE(fp);
 			return (buf);
 		}
 		fp->_r -= len;
@@ -93,5 +97,6 @@
 		n -= len;
 	}
 	*s = '\0';
+	FUNLOCKFILE(fp);
 	return (buf);
 }