Introduce api to track fd ownership in libc.

Add two functions to allow objects that own a file descriptor to
enforce that only they can close their file descriptor.

Use them in FILE* and DIR*.

Bug: http://b/110100358
Test: bionic_unit_tests
Test: aosp/master boots without errors
Test: treehugger
Change-Id: Iecd6e8b26c62217271e0822dc3d2d7888b091a45
diff --git a/libc/bionic/getpid.cpp b/libc/bionic/getpid.cpp
index 779b147..c6eb586 100644
--- a/libc/bionic/getpid.cpp
+++ b/libc/bionic/getpid.cpp
@@ -32,16 +32,22 @@
 
 extern "C" pid_t __getpid();
 
-pid_t getpid() {
+pid_t __get_cached_pid() {
   pthread_internal_t* self = __get_thread();
-
   if (__predict_true(self)) {
-    // Do we have a valid cached pid?
     pid_t cached_pid;
     if (__predict_true(self->get_cached_pid(&cached_pid))) {
       return cached_pid;
     }
   }
+  return 0;
+}
+
+pid_t getpid() {
+  pid_t cached_pid = __get_cached_pid();
+  if (__predict_true(cached_pid != 0)) {
+    return cached_pid;
+  }
 
   // We're still in the dynamic linker or we're in the middle of forking, so ask the kernel.
   // We don't know whether it's safe to update the cached value, so don't try.