am 8c212ebe: Merge "Only use  if it exists and is writable."

# Via Elliott Hughes (1) and Gerrit Code Review (1)
* commit '8c212ebe53bb2baab3575f03069016f1fb11e449':
  Only use $EXTERNAL_STORAGE if it exists and is writable.
diff --git a/src/gtest-port.cc b/src/gtest-port.cc
index 01c5e1e..f914dbc 100644
--- a/src/gtest-port.cc
+++ b/src/gtest-port.cc
@@ -508,16 +508,23 @@
 // ANDROID
 #elif GTEST_OS_LINUX_ANDROID
     // Get $EXTERNAL_STORAGE from the environment, since this can change
-    // for shell users (fallback is still /sdcard, but this probably will
-    // never work properly again).
-    ::std::string external_storage = "/sdcard";
+    // for shell users (fallback is /data/nativetest, for emulator users).
+    ::std::string external_storage = "/data/nativetest";
     char *sdcard_path = getenv("EXTERNAL_STORAGE");
-    if (sdcard_path) {
-      external_storage = sdcard_path;
+    if (sdcard_path != NULL) {
+      // Check that $EXTERNAL_STORAGE exists and is writable before trying to use it.
+      struct stat sb;
+      if (stat(sdcard_path, &sb) != -1) {
+        if ((sb.st_mode & S_IWUSR) != 0) {
+          external_storage = sdcard_path;
+        }
+      }
     }
     external_storage += "/captured_stderr.XXXXXX";
     char *name_template = strdup(external_storage.c_str());
     const int captured_fd = mkstemp(name_template);
+    GTEST_CHECK_(captured_fd != -1) << "Unable to open temporary file "
+                                    << name_template;
     filename_ = name_template;
     free(name_template);
     name_template = NULL;