Make tmpfile() respect $TMPDIR.

Contrary to the old comment, POSIX says nothing about whether or not
tmpfile() respects $TMPDIR, and it's significantly more useful on
Android if it does (because there's no shared /tmp that everyone can
write to).

Bug: https://issuetracker.google.com/36991167
Test: treehugger
Change-Id: I3cc45adff167420f100c8ed1c63cba1ea67e9f70
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index fb6bce9..c5ffe24 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -36,6 +36,7 @@
 
 #include <android-base/file.h>
 #include <android-base/silent_death_test.h>
+#include <android-base/strings.h>
 #include <android-base/test_utils.h>
 #include <android-base/unique_fd.h>
 
@@ -140,6 +141,22 @@
   fclose(fp);
 }
 
+TEST(STDIO_TEST, tmpfile_TMPDIR) {
+  TemporaryDir td;
+  setenv("TMPDIR", td.path, 1);
+
+  FILE* fp = tmpfile();
+  ASSERT_TRUE(fp != nullptr);
+
+  std::string fd_path = android::base::StringPrintf("/proc/self/fd/%d", fileno(fp));
+  char path[PATH_MAX];
+  ASSERT_GT(readlink(fd_path.c_str(), path, sizeof(path)), 0);
+  // $TMPDIR influenced where our temporary file ended up?
+  ASSERT_TRUE(android::base::StartsWith(path, td.path)) << path;
+  // And we used O_TMPFILE, right?
+  ASSERT_TRUE(android::base::EndsWith(path, " (deleted)")) << path;
+}
+
 TEST(STDIO_TEST, dprintf) {
   TemporaryFile tf;