Save environment snapshot and use at fork/exec

Some applications may inadvertently or maliciously set of environment
variables such as LD_LIBRARY_PATH before spawning subprocesses.
To make this more difficult, save the environment at the time the
runtime starts and use the saved copy anytime Exec is called.

BUG: 30160149
TEST: make test-art-{host,target}

Change-Id: I887b78bdb21ab20855636a96da14a74c767bbfef
diff --git a/runtime/runtime.h b/runtime/runtime.h
index 6da60f2..5f89d6a 100644
--- a/runtime/runtime.h
+++ b/runtime/runtime.h
@@ -642,6 +642,12 @@
   // optimization that makes it impossible to deoptimize.
   bool IsDeoptimizeable(uintptr_t code) const SHARED_REQUIRES(Locks::mutator_lock_);
 
+  // Returns a saved copy of the environment (getenv/setenv values).
+  // Used by Fork to protect against overwriting LD_LIBRARY_PATH, etc.
+  char** GetEnvSnapshot() const {
+    return env_snapshot_.GetSnapshot();
+  }
+
  private:
   static void InitPlatformSignalHandlers();
 
@@ -864,6 +870,20 @@
   // Whether zygote code is in a section that should not start threads.
   bool zygote_no_threads_;
 
+  // Saved environment.
+  class EnvSnapshot {
+   public:
+    EnvSnapshot() = default;
+    void TakeSnapshot();
+    char** GetSnapshot() const;
+
+   private:
+    std::unique_ptr<char*[]> c_env_vector_;
+    std::vector<std::unique_ptr<std::string>> name_value_pairs_;
+
+    DISALLOW_COPY_AND_ASSIGN(EnvSnapshot);
+  } env_snapshot_;
+
   DISALLOW_COPY_AND_ASSIGN(Runtime);
 };
 std::ostream& operator<<(std::ostream& os, const Runtime::CalleeSaveType& rhs);