Merge pull request #1834 from jhasse/close-during-generator

Close BuildLog while running generators, fix #1724
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index 71cd06e..511b92b 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -22,23 +22,36 @@
         curl -L -O https://www.mirrorservice.org/sites/dl.fedoraproject.org/pub/epel/7/x86_64/Packages/p/p7zip-plugins-16.02-10.el7.x86_64.rpm
         rpm -U --quiet p7zip-16.02-10.el7.x86_64.rpm
         rpm -U --quiet p7zip-plugins-16.02-10.el7.x86_64.rpm
-        yum install -y make gcc-c++
+        yum install -y make gcc-c++ libasan clang-analyzer
 
-    - name: Build ninja
+    - name: Build debug ninja
+      shell: bash
+      env:
+        CFLAGS: -fstack-protector-all -fsanitize=address
+        CXXFLAGS: -fstack-protector-all -fsanitize=address
+      run: |
+        scan-build -o scanlogs cmake -DCMAKE_BUILD_TYPE=Debug -B debug-build
+        scan-build -o scanlogs cmake --build debug-build --parallel --config Debug
+
+    - name: Test debug ninja
+      run: ./ninja_test
+      working-directory: debug-build
+
+    - name: Build release ninja
       shell: bash
       run: |
-        cmake -DCMAKE_BUILD_TYPE=Release -B build
-        cmake --build build --parallel --config Release
-        strip build/ninja
+        cmake -DCMAKE_BUILD_TYPE=Release -B release-build
+        cmake --build release-build --parallel --config Release
+        strip release-build/ninja
 
-    - name: Test ninja
+    - name: Test release ninja
       run: ./ninja_test
-      working-directory: build
+      working-directory: release-build
 
     - name: Create ninja archive
       run: |
         mkdir artifact
-        7z a artifact/ninja-linux.zip ./build/ninja
+        7z a artifact/ninja-linux.zip ./release-build/ninja
 
     # Upload ninja binary archive as an artifact
     - name: Upload artifact
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 65e42a4..b0b2fef 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -1,4 +1,7 @@
 cmake_minimum_required(VERSION 3.15)
+
+include(CheckIncludeFileCXX)
+
 project(ninja)
 
 # --- optional link-time optimization
@@ -48,6 +51,30 @@
 endif()
 target_include_directories(libninja-re2c PRIVATE src)
 
+# --- Check for 'browse' mode support
+function(check_platform_supports_browse_mode RESULT)
+	# Make sure the inline.sh script works on this platform.
+	# It uses the shell commands such as 'od', which may not be available.
+	execute_process(
+		COMMAND sh -c "echo 'TEST' | src/inline.sh var"
+		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+		RESULT_VARIABLE inline_result
+		OUTPUT_QUIET
+		ERROR_QUIET
+	)
+	if(NOT inline_result EQUAL "0")
+		# The inline script failed, so browse mode is not supported.
+		set(${RESULT} "0" PARENT_SCOPE)
+		return()
+	endif()
+
+	# Now check availability of the unistd header
+	check_include_file_cxx(unistd.h PLATFORM_HAS_UNISTD_HEADER)
+	set(${RESULT} "${PLATFORM_HAS_UNISTD_HEADER}" PARENT_SCOPE)
+endfunction()
+
+check_platform_supports_browse_mode(platform_supports_ninja_browse)
+
 # Core source files all build into ninja library.
 add_library(libninja OBJECT
 	src/build_log.cc
@@ -92,49 +119,84 @@
 target_compile_definitions(libninja PRIVATE _WIN32_WINNT=0x0601 __USE_MINGW_ANSI_STDIO=1)
 endif()
 
+# On IBM i (identified as "OS400" for compatibility reasons), this fixes missing
+# PRId64 (and others) at compile time, and links to libutil for getopt_long
+if(CMAKE_SYSTEM_NAME STREQUAL "OS400")
+	string(APPEND CMAKE_CXX_FLAGS " -D__STDC_FORMAT_MACROS")
+	string(APPEND CMAKE_EXE_LINKER_FLAGS " -lutil")
+endif()
+
 # Main executable is library plus main() function.
 add_executable(ninja src/ninja.cc)
 target_link_libraries(ninja PRIVATE libninja libninja-re2c)
 
-# Tests all build into ninja_test executable.
-add_executable(ninja_test
-	src/build_log_test.cc
-	src/build_test.cc
-	src/clean_test.cc
-	src/clparser_test.cc
-	src/depfile_parser_test.cc
-	src/deps_log_test.cc
-	src/disk_interface_test.cc
-	src/dyndep_parser_test.cc
-	src/edit_distance_test.cc
-	src/graph_test.cc
-	src/lexer_test.cc
-	src/manifest_parser_test.cc
-	src/ninja_test.cc
-	src/state_test.cc
-	src/string_piece_util_test.cc
-	src/subprocess_test.cc
-	src/test.cc
-	src/util_test.cc
-)
-if(WIN32)
-	target_sources(ninja_test PRIVATE src/includes_normalize_test.cc src/msvc_helper_test.cc)
+# Adds browse mode into the ninja binary if it's supported by the host platform.
+if(platform_supports_ninja_browse)
+	# Inlines src/browse.py into the browse_py.h header, so that it can be included
+	# by src/browse.cc
+	add_custom_command(
+		OUTPUT build/browse_py.h
+		MAIN_DEPENDENCY src/browse.py
+		DEPENDS src/inline.sh
+		COMMAND cmake -E make_directory ${CMAKE_BINARY_DIR}/build
+		COMMAND src/inline.sh kBrowsePy
+						< src/browse.py
+						> ${CMAKE_BINARY_DIR}/build/browse_py.h
+		WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
+		VERBATIM
+	)
+
+	target_compile_definitions(ninja PRIVATE NINJA_HAVE_BROWSE)
+	target_sources(ninja PRIVATE src/browse.cc)
+	set_source_files_properties(src/browse.cc
+		PROPERTIES
+			OBJECT_DEPENDS "${CMAKE_BINARY_DIR}/build/browse_py.h"
+			INCLUDE_DIRECTORIES "${CMAKE_BINARY_DIR}"
+			COMPILE_DEFINITIONS NINJA_PYTHON="python"
+	)
 endif()
-target_link_libraries(ninja_test PRIVATE libninja libninja-re2c)
 
-foreach(perftest
-  build_log_perftest
-  canon_perftest
-  clparser_perftest
-  depfile_parser_perftest
-  hash_collision_bench
-  manifest_parser_perftest
-)
-  add_executable(${perftest} src/${perftest}.cc)
-  target_link_libraries(${perftest} PRIVATE libninja libninja-re2c)
-endforeach()
+include(CTest)
+if(BUILD_TESTING)
+  # Tests all build into ninja_test executable.
+  add_executable(ninja_test
+    src/build_log_test.cc
+    src/build_test.cc
+    src/clean_test.cc
+    src/clparser_test.cc
+    src/depfile_parser_test.cc
+    src/deps_log_test.cc
+    src/disk_interface_test.cc
+    src/dyndep_parser_test.cc
+    src/edit_distance_test.cc
+    src/graph_test.cc
+    src/lexer_test.cc
+    src/manifest_parser_test.cc
+    src/ninja_test.cc
+    src/state_test.cc
+    src/string_piece_util_test.cc
+    src/subprocess_test.cc
+    src/test.cc
+    src/util_test.cc
+  )
+  if(WIN32)
+    target_sources(ninja_test PRIVATE src/includes_normalize_test.cc src/msvc_helper_test.cc)
+  endif()
+  target_link_libraries(ninja_test PRIVATE libninja libninja-re2c)
 
-enable_testing()
-add_test(NinjaTest ninja_test)
+  foreach(perftest
+    build_log_perftest
+    canon_perftest
+    clparser_perftest
+    depfile_parser_perftest
+    hash_collision_bench
+    manifest_parser_perftest
+  )
+    add_executable(${perftest} src/${perftest}.cc)
+    target_link_libraries(${perftest} PRIVATE libninja libninja-re2c)
+  endforeach()
+
+  add_test(NinjaTest ninja_test)
+endif()
 
 install(TARGETS ninja DESTINATION bin)
diff --git a/configure.py b/configure.py
index 8eef7e6..48c4821 100755
--- a/configure.py
+++ b/configure.py
@@ -269,7 +269,7 @@
     n.variable('configure_env', config_str + '$ ')
 n.newline()
 
-CXX = configure_env.get('CXX', 'g++')
+CXX = configure_env.get('CXX', 'c++')
 objext = '.o'
 if platform.is_msvc():
     CXX = 'cl'
diff --git a/src/browse.cc b/src/browse.cc
index c08c9f4..76bee07 100644
--- a/src/browse.cc
+++ b/src/browse.cc
@@ -22,6 +22,8 @@
 
 #include "build/browse_py.h"
 
+using namespace std;
+
 void RunBrowsePython(State* state, const char* ninja_command,
                      const char* input_file, int argc, char* argv[]) {
   // Fork off a Python process and have it run our code via its stdin.
diff --git a/src/build.cc b/src/build.cc
index 5b7c8d6..2fb2aa4 100644
--- a/src/build.cc
+++ b/src/build.cc
@@ -40,6 +40,8 @@
 #include "subprocess.h"
 #include "util.h"
 
+using namespace std;
+
 namespace {
 
 /// A CommandRunner that doesn't actually run the commands.
@@ -77,12 +79,9 @@
 }  // namespace
 
 BuildStatus::BuildStatus(const BuildConfig& config)
-    : config_(config),
-      start_time_millis_(GetTimeMillis()),
-      started_edges_(0), finished_edges_(0), total_edges_(0),
-      progress_status_format_(NULL),
-      overall_rate_(), current_rate_(config.parallelism) {
-
+    : config_(config), start_time_millis_(GetTimeMillis()), started_edges_(0),
+      finished_edges_(0), total_edges_(0), progress_status_format_(NULL),
+      current_rate_(config.parallelism) {
   // Don't do anything fancy in verbose mode.
   if (config_.verbosity != BuildConfig::NORMAL)
     printer_.set_smart_terminal(false);
@@ -1071,8 +1070,7 @@
       // complexity in IncludesNormalize::Relativize.
       deps_nodes->push_back(state_->GetNode(*i, ~0u));
     }
-  } else
-  if (deps_type == "gcc") {
+  } else if (deps_type == "gcc") {
     string depfile = result->edge->GetUnescapedDepfile();
     if (depfile.empty()) {
       *err = string("edge with deps=gcc but no depfile makes no sense");
diff --git a/src/build.h b/src/build.h
index 97773c4..2798693 100644
--- a/src/build.h
+++ b/src/build.h
@@ -46,7 +46,7 @@
   /// Add a target to our plan (including all its dependencies).
   /// Returns false if we don't need to build this target; may
   /// fill in |err| with an error message if there's a problem.
-  bool AddTarget(const Node* node, string* err);
+  bool AddTarget(const Node* node, std::string* err);
 
   // Pop a ready edge off the queue of edges to build.
   // Returns NULL if there's no work to do.
@@ -67,11 +67,11 @@
   /// If any of the edge's outputs are dyndep bindings of their dependents,
   /// this loads dynamic dependencies from the nodes' paths.
   /// Returns 'false' if loading dyndep info fails and 'true' otherwise.
-  bool EdgeFinished(Edge* edge, EdgeResult result, string* err);
+  bool EdgeFinished(Edge* edge, EdgeResult result, std::string* err);
 
   /// Clean the given node during the build.
   /// Return false on error.
-  bool CleanNode(DependencyScan* scan, Node* node, string* err);
+  bool CleanNode(DependencyScan* scan, Node* node, std::string* err);
 
   /// Number of edges with commands to run.
   int command_edge_count() const { return command_edges_; }
@@ -82,18 +82,18 @@
   /// Update the build plan to account for modifications made to the graph
   /// by information loaded from a dyndep file.
   bool DyndepsLoaded(DependencyScan* scan, const Node* node,
-                     const DyndepFile& ddf, string* err);
+                     const DyndepFile& ddf, std::string* err);
 private:
-  bool RefreshDyndepDependents(DependencyScan* scan, const Node* node, string* err);
-  void UnmarkDependents(const Node* node, set<Node*>* dependents);
-  bool AddSubTarget(const Node* node, const Node* dependent, string* err,
-                    set<Edge*>* dyndep_walk);
+  bool RefreshDyndepDependents(DependencyScan* scan, const Node* node, std::string* err);
+  void UnmarkDependents(const Node* node, std::set<Node*>* dependents);
+  bool AddSubTarget(const Node* node, const Node* dependent, std::string* err,
+                    std::set<Edge*>* dyndep_walk);
 
   /// Update plan with knowledge that the given node is up to date.
   /// If the node is a dyndep binding on any of its dependents, this
   /// loads dynamic dependencies from the node's path.
   /// Returns 'false' if loading dyndep info fails and 'true' otherwise.
-  bool NodeFinished(Node* node, string* err);
+  bool NodeFinished(Node* node, std::string* err);
 
   /// Enumerate possible steps we want for an edge.
   enum Want
@@ -109,20 +109,20 @@
   };
 
   void EdgeWanted(const Edge* edge);
-  bool EdgeMaybeReady(map<Edge*, Want>::iterator want_e, string* err);
+  bool EdgeMaybeReady(std::map<Edge*, Want>::iterator want_e, std::string* err);
 
   /// Submits a ready edge as a candidate for execution.
   /// The edge may be delayed from running, for example if it's a member of a
   /// currently-full pool.
-  void ScheduleWork(map<Edge*, Want>::iterator want_e);
+  void ScheduleWork(std::map<Edge*, Want>::iterator want_e);
 
   /// Keep track of which edges we want to build in this plan.  If this map does
   /// not contain an entry for an edge, we do not want to build the entry or its
   /// dependents.  If it does contain an entry, the enumeration indicates what
   /// we want for the edge.
-  map<Edge*, Want> want_;
+  std::map<Edge*, Want> want_;
 
-  set<Edge*> ready_;
+  std::set<Edge*> ready_;
 
   Builder* builder_;
 
@@ -146,13 +146,13 @@
     Result() : edge(NULL) {}
     Edge* edge;
     ExitStatus status;
-    string output;
+    std::string output;
     bool success() const { return status == ExitSuccess; }
   };
   /// Wait for a command to complete, or return false if interrupted.
   virtual bool WaitForCommand(Result* result) = 0;
 
-  virtual vector<Edge*> GetActiveEdges() { return vector<Edge*>(); }
+  virtual std::vector<Edge*> GetActiveEdges() { return std::vector<Edge*>(); }
   virtual void Abort() {}
 };
 
@@ -186,24 +186,24 @@
   /// Clean up after interrupted commands by deleting output files.
   void Cleanup();
 
-  Node* AddTarget(const string& name, string* err);
+  Node* AddTarget(const std::string& name, std::string* err);
 
   /// Add a target to the build, scanning dependencies.
   /// @return false on error.
-  bool AddTarget(Node* target, string* err);
+  bool AddTarget(Node* target, std::string* err);
 
   /// Returns true if the build targets are already up to date.
   bool AlreadyUpToDate() const;
 
   /// Run the build.  Returns false on error.
   /// It is an error to call this function when AlreadyUpToDate() is true.
-  bool Build(string* err);
+  bool Build(std::string* err);
 
-  bool StartEdge(Edge* edge, string* err);
+  bool StartEdge(Edge* edge, std::string* err);
 
   /// Update status ninja logs following a command termination.
   /// @return false if the build can not proceed further due to a fatal error.
-  bool FinishCommand(CommandRunner::Result* result, string* err);
+  bool FinishCommand(CommandRunner::Result* result, std::string* err);
 
   /// Used for tests.
   void SetBuildLog(BuildLog* log) {
@@ -211,22 +211,22 @@
   }
 
   /// Load the dyndep information provided by the given node.
-  bool LoadDyndeps(Node* node, string* err);
+  bool LoadDyndeps(Node* node, std::string* err);
 
   State* state_;
   const BuildConfig& config_;
   Plan plan_;
 #if __cplusplus < 201703L
-  auto_ptr<CommandRunner> command_runner_;
+  std::auto_ptr<CommandRunner> command_runner_;
 #else
-  unique_ptr<CommandRunner> command_runner_;  // auto_ptr was removed in C++17.
+  std::unique_ptr<CommandRunner> command_runner_;  // auto_ptr was removed in C++17.
 #endif
   BuildStatus* status_;
 
  private:
-   bool ExtractDeps(CommandRunner::Result* result, const string& deps_type,
-                    const string& deps_prefix, vector<Node*>* deps_nodes,
-                    string* err);
+  bool ExtractDeps(CommandRunner::Result* result, const std::string& deps_type,
+                   const std::string& deps_prefix,
+                   std::vector<Node*>* deps_nodes, std::string* err);
 
   DiskInterface* disk_interface_;
   DependencyScan scan_;
@@ -241,7 +241,7 @@
   explicit BuildStatus(const BuildConfig& config);
   void PlanHasTotalEdges(int total);
   void BuildEdgeStarted(const Edge* edge);
-  void BuildEdgeFinished(Edge* edge, bool success, const string& output,
+  void BuildEdgeFinished(Edge* edge, bool success, const std::string& output,
                          int* start_time, int* end_time);
   void BuildLoadDyndeps();
   void BuildStarted();
@@ -257,8 +257,8 @@
   /// placeholders.
   /// @param progress_status_format The format of the progress status.
   /// @param status The status of the edge.
-  string FormatProgressStatus(const char* progress_status_format,
-                              EdgeStatus status) const;
+  std::string FormatProgressStatus(const char* progress_status_format,
+                                   EdgeStatus status) const;
 
  private:
   void PrintStatus(const Edge* edge, EdgeStatus status);
@@ -271,7 +271,7 @@
   int started_edges_, finished_edges_, total_edges_;
 
   /// Map of running edge to time the edge started running.
-  typedef map<const Edge*, int> RunningEdgeMap;
+  typedef std::map<const Edge*, int> RunningEdgeMap;
   RunningEdgeMap running_edges_;
 
   /// Prints progress output.
@@ -327,7 +327,7 @@
     double rate_;
     Stopwatch stopwatch_;
     const size_t N;
-    queue<double> times_;
+    std::queue<double> times_;
     int last_update_;
   };
 
diff --git a/src/build_log.cc b/src/build_log.cc
index c261b20..4dcd6ce 100644
--- a/src/build_log.cc
+++ b/src/build_log.cc
@@ -41,6 +41,8 @@
 #define strtoll _strtoi64
 #endif
 
+using namespace std;
+
 // Implementation details:
 // Each run's log appends to the log file.
 // To load, we run through all log entries in series, throwing away
@@ -188,7 +190,9 @@
   if (!log_file_) {
     return false;
   }
-  setvbuf(log_file_, NULL, _IOLBF, BUFSIZ);
+  if (setvbuf(log_file_, NULL, _IOLBF, BUFSIZ) != 0) {
+    return false;
+  }
   SetCloseOnExec(fileno(log_file_));
 
   // Opening a file in append mode doesn't set the file pointer to the file's
diff --git a/src/build_log.h b/src/build_log.h
index 6d060d1..88551e3 100644
--- a/src/build_log.h
+++ b/src/build_log.h
@@ -17,7 +17,6 @@
 
 #include <string>
 #include <stdio.h>
-using namespace std;
 
 #include "hash_map.h"
 #include "load_status.h"
@@ -47,17 +46,17 @@
 
   /// Prepares writing to the log file without actually opening it - that will
   /// happen when/if it's needed
-  bool OpenForWrite(const string& path, const BuildLogUser& user, string* err);
-
+  bool OpenForWrite(const std::string& path, const BuildLogUser& user,
+                    std::string* err);
   bool RecordCommand(Edge* edge, int start_time, int end_time,
                      TimeStamp mtime = 0);
   void Close();
 
   /// Load the on-disk log.
-  LoadStatus Load(const string& path, string* err);
+  LoadStatus Load(const std::string& path, std::string* err);
 
   struct LogEntry {
-    string output;
+    std::string output;
     uint64_t command_hash;
     int start_time;
     int end_time;
@@ -72,19 +71,20 @@
           mtime == o.mtime;
     }
 
-    explicit LogEntry(const string& output);
-    LogEntry(const string& output, uint64_t command_hash,
+    explicit LogEntry(const std::string& output);
+    LogEntry(const std::string& output, uint64_t command_hash,
              int start_time, int end_time, TimeStamp restat_mtime);
   };
 
   /// Lookup a previously-run command by its output path.
-  LogEntry* LookupByOutput(const string& path);
+  LogEntry* LookupByOutput(const std::string& path);
 
   /// Serialize an entry into a log file.
   bool WriteEntry(FILE* f, const LogEntry& entry);
 
   /// Rewrite the known log entries, throwing away old data.
-  bool Recompact(const string& path, const BuildLogUser& user, string* err);
+  bool Recompact(const std::string& path, const BuildLogUser& user,
+                 std::string* err);
 
   /// Restat all outputs in the log
   bool Restat(StringPiece path, const DiskInterface& disk_interface,
diff --git a/src/build_log_perftest.cc b/src/build_log_perftest.cc
index e471d13..ced0df9 100644
--- a/src/build_log_perftest.cc
+++ b/src/build_log_perftest.cc
@@ -26,6 +26,8 @@
 #include <unistd.h>
 #endif
 
+using namespace std;
+
 const char kTestFilename[] = "BuildLogPerfTest-tempfile";
 
 struct NoDeadPaths : public BuildLogUser {
diff --git a/src/build_log_test.cc b/src/build_log_test.cc
index c81f570..3718299 100644
--- a/src/build_log_test.cc
+++ b/src/build_log_test.cc
@@ -27,6 +27,8 @@
 #endif
 #include <cassert>
 
+using namespace std;
+
 namespace {
 
 const char kTestFilename[] = "BuildLogTest-tempfile";
diff --git a/src/build_test.cc b/src/build_test.cc
index 12c3383..078080d 100644
--- a/src/build_test.cc
+++ b/src/build_test.cc
@@ -21,6 +21,8 @@
 #include "graph.h"
 #include "test.h"
 
+using namespace std;
+
 struct CompareEdgesByOutput {
   static bool cmp(const Edge* a, const Edge* b) {
     return a->outputs_[0]->path() < b->outputs_[0]->path();
diff --git a/src/canon_perftest.cc b/src/canon_perftest.cc
index 03f4a2f..088bd45 100644
--- a/src/canon_perftest.cc
+++ b/src/canon_perftest.cc
@@ -18,6 +18,8 @@
 #include "util.h"
 #include "metrics.h"
 
+using namespace std;
+
 const char kPath[] =
     "../../third_party/WebKit/Source/WebCore/"
     "platform/leveldb/LevelDBWriteBatch.cpp";
diff --git a/src/clean.cc b/src/clean.cc
index ec6e7d7..3e57437 100644
--- a/src/clean.cc
+++ b/src/clean.cc
@@ -22,14 +22,14 @@
 #include "state.h"
 #include "util.h"
 
+using namespace std;
+
 Cleaner::Cleaner(State* state,
                  const BuildConfig& config,
                  DiskInterface* disk_interface)
   : state_(state),
     config_(config),
     dyndep_loader_(state, disk_interface),
-    removed_(),
-    cleaned_(),
     cleaned_files_count_(0),
     disk_interface_(disk_interface),
     status_(0) {
diff --git a/src/clean.h b/src/clean.h
index 4c02ff6..cf3f1c3 100644
--- a/src/clean.h
+++ b/src/clean.h
@@ -22,8 +22,6 @@
 #include "dyndep.h"
 #include "build_log.h"
 
-using namespace std;
-
 struct State;
 struct Node;
 struct Rule;
@@ -78,15 +76,15 @@
  private:
   /// Remove the file @a path.
   /// @return whether the file has been removed.
-  int RemoveFile(const string& path);
+  int RemoveFile(const std::string& path);
   /// @returns whether the file @a path exists.
-  bool FileExists(const string& path);
-  void Report(const string& path);
+  bool FileExists(const std::string& path);
+  void Report(const std::string& path);
 
   /// Remove the given @a path file only if it has not been already removed.
-  void Remove(const string& path);
+  void Remove(const std::string& path);
   /// @return whether the given @a path has already been removed.
-  bool IsAlreadyRemoved(const string& path);
+  bool IsAlreadyRemoved(const std::string& path);
   /// Remove the depfile and rspfile for an Edge.
   void RemoveEdgeFiles(Edge* edge);
 
@@ -103,8 +101,8 @@
   State* state_;
   const BuildConfig& config_;
   DyndepLoader dyndep_loader_;
-  set<string> removed_;
-  set<Node*> cleaned_;
+  std::set<std::string> removed_;
+  std::set<Node*> cleaned_;
   int cleaned_files_count_;
   DiskInterface* disk_interface_;
   int status_;
diff --git a/src/clean_test.cc b/src/clean_test.cc
index d068f3c..1b843a2 100644
--- a/src/clean_test.cc
+++ b/src/clean_test.cc
@@ -22,6 +22,8 @@
 #include <unistd.h>
 #endif
 
+using namespace std;
+
 namespace {
 
 const char kTestFilename[] = "CleanTest-tempfile";
diff --git a/src/clparser.cc b/src/clparser.cc
index 7994c06..275641e 100644
--- a/src/clparser.cc
+++ b/src/clparser.cc
@@ -28,6 +28,8 @@
 #include "util.h"
 #endif
 
+using namespace std;
+
 namespace {
 
 /// Return true if \a input ends with \a needle.
diff --git a/src/clparser.h b/src/clparser.h
index e597e7e..2a33628 100644
--- a/src/clparser.h
+++ b/src/clparser.h
@@ -17,7 +17,6 @@
 
 #include <set>
 #include <string>
-using namespace std;
 
 /// Visual Studio's cl.exe requires some massaging to work with Ninja;
 /// for example, it emits include information on stderr in a funny
@@ -27,26 +26,26 @@
   /// Parse a line of cl.exe output and extract /showIncludes info.
   /// If a dependency is extracted, returns a nonempty string.
   /// Exposed for testing.
-  static string FilterShowIncludes(const string& line,
-                                   const string& deps_prefix);
+  static std::string FilterShowIncludes(const std::string& line,
+                                        const std::string& deps_prefix);
 
   /// Return true if a mentioned include file is a system path.
   /// Filtering these out reduces dependency information considerably.
-  static bool IsSystemInclude(string path);
+  static bool IsSystemInclude(std::string path);
 
   /// Parse a line of cl.exe output and return true if it looks like
   /// it's printing an input filename.  This is a heuristic but it appears
   /// to be the best we can do.
   /// Exposed for testing.
-  static bool FilterInputFilename(string line);
+  static bool FilterInputFilename(std::string line);
 
   /// Parse the full output of cl, filling filtered_output with the text that
   /// should be printed (if any). Returns true on success, or false with err
   /// filled. output must not be the same object as filtered_object.
-  bool Parse(const string& output, const string& deps_prefix,
-             string* filtered_output, string* err);
+  bool Parse(const std::string& output, const std::string& deps_prefix,
+             std::string* filtered_output, std::string* err);
 
-  set<string> includes_;
+  std::set<std::string> includes_;
 };
 
 #endif  // NINJA_CLPARSER_H_
diff --git a/src/clparser_perftest.cc b/src/clparser_perftest.cc
index 7ac5230..008ac46 100644
--- a/src/clparser_perftest.cc
+++ b/src/clparser_perftest.cc
@@ -18,6 +18,8 @@
 #include "clparser.h"
 #include "metrics.h"
 
+using namespace std;
+
 int main(int argc, char* argv[]) {
   // Output of /showIncludes from #include <iostream>
   string perf_testdata =
diff --git a/src/clparser_test.cc b/src/clparser_test.cc
index 1549ab1..0b829c1 100644
--- a/src/clparser_test.cc
+++ b/src/clparser_test.cc
@@ -17,6 +17,8 @@
 #include "test.h"
 #include "util.h"
 
+using namespace std;
+
 TEST(CLParserTest, ShowIncludes) {
   ASSERT_EQ("", CLParser::FilterShowIncludes("", ""));
 
diff --git a/src/depfile_parser.cc b/src/depfile_parser.cc
index 0b7dce1..bffeb76 100644
--- a/src/depfile_parser.cc
+++ b/src/depfile_parser.cc
@@ -18,6 +18,8 @@
 
 #include <algorithm>
 
+using namespace std;
+
 DepfileParser::DepfileParser(DepfileParserOptions options)
   : options_(options)
 {
diff --git a/src/depfile_parser.h b/src/depfile_parser.h
index 11b1228..0e8db81 100644
--- a/src/depfile_parser.h
+++ b/src/depfile_parser.h
@@ -17,7 +17,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 #include "string_piece.h"
 
@@ -33,10 +32,10 @@
   /// Parse an input file.  Input must be NUL-terminated.
   /// Warning: may mutate the content in-place and parsed StringPieces are
   /// pointers within it.
-  bool Parse(string* content, string* err);
+  bool Parse(std::string* content, std::string* err);
 
   std::vector<StringPiece> outs_;
-  vector<StringPiece> ins_;
+  std::vector<StringPiece> ins_;
   DepfileParserOptions options_;
 };
 
diff --git a/src/depfile_parser.in.cc b/src/depfile_parser.in.cc
index 95b4346..75ba982 100644
--- a/src/depfile_parser.in.cc
+++ b/src/depfile_parser.in.cc
@@ -17,6 +17,8 @@
 
 #include <algorithm>
 
+using namespace std;
+
 DepfileParser::DepfileParser(DepfileParserOptions options)
   : options_(options)
 {
diff --git a/src/depfile_parser_perftest.cc b/src/depfile_parser_perftest.cc
index b215221..52555e6 100644
--- a/src/depfile_parser_perftest.cc
+++ b/src/depfile_parser_perftest.cc
@@ -19,6 +19,8 @@
 #include "util.h"
 #include "metrics.h"
 
+using namespace std;
+
 int main(int argc, char* argv[]) {
   if (argc < 2) {
     printf("usage: %s <file1> <file2...>\n", argv[0]);
diff --git a/src/depfile_parser_test.cc b/src/depfile_parser_test.cc
index 8e2cd25..8886258 100644
--- a/src/depfile_parser_test.cc
+++ b/src/depfile_parser_test.cc
@@ -16,6 +16,8 @@
 
 #include "test.h"
 
+using namespace std;
+
 struct DepfileParserTest : public testing::Test {
   bool Parse(const char* input, string* err);
 
diff --git a/src/deps_log.cc b/src/deps_log.cc
index 1fb65ae..191f300 100644
--- a/src/deps_log.cc
+++ b/src/deps_log.cc
@@ -30,6 +30,8 @@
 #include "state.h"
 #include "util.h"
 
+using namespace std;
+
 // The version is stored as 4 bytes after the signature and also serves as a
 // byte order mark. Signature and version combined are 16 bytes long.
 const char kFileSignature[] = "# ninjadeps\n";
@@ -411,7 +413,9 @@
   }
   // Set the buffer size to this and flush the file buffer after every record
   // to make sure records aren't written partially.
-  setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1);
+  if (setvbuf(file_, NULL, _IOFBF, kMaxRecordSize + 1) != 0) {
+    return false;
+  }
   SetCloseOnExec(fileno(file_));
 
   // Opening a file in append mode doesn't set the file pointer to the file's
diff --git a/src/deps_log.h b/src/deps_log.h
index c4ada8b..cc44b41 100644
--- a/src/deps_log.h
+++ b/src/deps_log.h
@@ -17,7 +17,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 #include <stdio.h>
 
@@ -71,8 +70,8 @@
   ~DepsLog();
 
   // Writing (build-time) interface.
-  bool OpenForWrite(const string& path, string* err);
-  bool RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes);
+  bool OpenForWrite(const std::string& path, std::string* err);
+  bool RecordDeps(Node* node, TimeStamp mtime, const std::vector<Node*>& nodes);
   bool RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes);
   void Close();
 
@@ -85,11 +84,11 @@
     int node_count;
     Node** nodes;
   };
-  LoadStatus Load(const string& path, State* state, string* err);
+  LoadStatus Load(const std::string& path, State* state, std::string* err);
   Deps* GetDeps(Node* node);
 
   /// Rewrite the known log entries, throwing away old data.
-  bool Recompact(const string& path, string* err);
+  bool Recompact(const std::string& path, std::string* err);
 
   /// Returns if the deps entry for a node is still reachable from the manifest.
   ///
@@ -100,8 +99,8 @@
   bool IsDepsEntryLiveFor(Node* node);
 
   /// Used for tests.
-  const vector<Node*>& nodes() const { return nodes_; }
-  const vector<Deps*>& deps() const { return deps_; }
+  const std::vector<Node*>& nodes() const { return nodes_; }
+  const std::vector<Deps*>& deps() const { return deps_; }
 
  private:
   // Updates the in-memory representation.  Takes ownership of |deps|.
@@ -119,9 +118,9 @@
   std::string file_path_;
 
   /// Maps id -> Node.
-  vector<Node*> nodes_;
+  std::vector<Node*> nodes_;
   /// Maps id -> deps of that id.
-  vector<Deps*> deps_;
+  std::vector<Deps*> deps_;
 
   friend struct DepsLogTest;
 };
diff --git a/src/deps_log_test.cc b/src/deps_log_test.cc
index 0cdeb45..4055941 100644
--- a/src/deps_log_test.cc
+++ b/src/deps_log_test.cc
@@ -23,6 +23,8 @@
 #include "util.h"
 #include "test.h"
 
+using namespace std;
+
 namespace {
 
 const char kTestFilename[] = "DepsLogTest-tempfile";
diff --git a/src/disk_interface.cc b/src/disk_interface.cc
index 594bc51..49af001 100644
--- a/src/disk_interface.cc
+++ b/src/disk_interface.cc
@@ -33,6 +33,8 @@
 #include "metrics.h"
 #include "util.h"
 
+using namespace std;
+
 namespace {
 
 string DirName(const string& path) {
diff --git a/src/disk_interface.h b/src/disk_interface.h
index 145e089..bc29ab7 100644
--- a/src/disk_interface.h
+++ b/src/disk_interface.h
@@ -17,7 +17,6 @@
 
 #include <map>
 #include <string>
-using namespace std;
 
 #include "timestamp.h"
 
@@ -35,8 +34,8 @@
 
   /// Read and store in given string.  On success, return Okay.
   /// On error, return another Status and fill |err|.
-  virtual Status ReadFile(const string& path, string* contents,
-                          string* err) = 0;
+  virtual Status ReadFile(const std::string& path, std::string* contents,
+                          std::string* err) = 0;
 };
 
 /// Interface for accessing the disk.
@@ -46,25 +45,26 @@
 struct DiskInterface: public FileReader {
   /// stat() a file, returning the mtime, or 0 if missing and -1 on
   /// other errors.
-  virtual TimeStamp Stat(const string& path, string* err) const = 0;
+  virtual TimeStamp Stat(const std::string& path, std::string* err) const = 0;
 
   /// Create a directory, returning false on failure.
-  virtual bool MakeDir(const string& path) = 0;
+  virtual bool MakeDir(const std::string& path) = 0;
 
   /// Create a file, with the specified name and contents
   /// Returns true on success, false on failure
-  virtual bool WriteFile(const string& path, const string& contents) = 0;
+  virtual bool WriteFile(const std::string& path,
+                         const std::string& contents) = 0;
 
   /// Remove the file named @a path. It behaves like 'rm -f path' so no errors
   /// are reported if it does not exists.
   /// @returns 0 if the file has been removed,
   ///          1 if the file does not exist, and
   ///          -1 if an error occurs.
-  virtual int RemoveFile(const string& path) = 0;
+  virtual int RemoveFile(const std::string& path) = 0;
 
   /// Create all the parent directories for path; like mkdir -p
   /// `basename path`.
-  bool MakeDirs(const string& path);
+  bool MakeDirs(const std::string& path);
 };
 
 /// Implementation of DiskInterface that actually hits the disk.
@@ -75,11 +75,12 @@
 #endif
                       {}
   virtual ~RealDiskInterface() {}
-  virtual TimeStamp Stat(const string& path, string* err) const;
-  virtual bool MakeDir(const string& path);
-  virtual bool WriteFile(const string& path, const string& contents);
-  virtual Status ReadFile(const string& path, string* contents, string* err);
-  virtual int RemoveFile(const string& path);
+  virtual TimeStamp Stat(const std::string& path, std::string* err) const;
+  virtual bool MakeDir(const std::string& path);
+  virtual bool WriteFile(const std::string& path, const std::string& contents);
+  virtual Status ReadFile(const std::string& path, std::string* contents,
+                          std::string* err);
+  virtual int RemoveFile(const std::string& path);
 
   /// Whether stat information can be cached.  Only has an effect on Windows.
   void AllowStatCache(bool allow);
@@ -89,10 +90,10 @@
   /// Whether stat information can be cached.
   bool use_cache_;
 
-  typedef map<string, TimeStamp> DirCache;
+  typedef std::map<std::string, TimeStamp> DirCache;
   // TODO: Neither a map nor a hashmap seems ideal here.  If the statcache
   // works out, come up with a better data structure.
-  typedef map<string, DirCache> Cache;
+  typedef std::map<std::string, DirCache> Cache;
   mutable Cache cache_;
 #endif
 };
diff --git a/src/disk_interface_test.cc b/src/disk_interface_test.cc
index 866d1d6..066c770 100644
--- a/src/disk_interface_test.cc
+++ b/src/disk_interface_test.cc
@@ -23,6 +23,8 @@
 #include "graph.h"
 #include "test.h"
 
+using namespace std;
+
 namespace {
 
 struct DiskInterfaceTest : public testing::Test {
diff --git a/src/dyndep.cc b/src/dyndep.cc
index 2aee601..b388e9b 100644
--- a/src/dyndep.cc
+++ b/src/dyndep.cc
@@ -24,6 +24,8 @@
 #include "state.h"
 #include "util.h"
 
+using namespace std;
+
 bool DyndepLoader::LoadDyndeps(Node* node, std::string* err) const {
   DyndepFile ddf;
   return LoadDyndeps(node, &ddf, err);
diff --git a/src/dyndep_parser.cc b/src/dyndep_parser.cc
index baebbac..56da16f 100644
--- a/src/dyndep_parser.cc
+++ b/src/dyndep_parser.cc
@@ -22,6 +22,8 @@
 #include "util.h"
 #include "version.h"
 
+using namespace std;
+
 DyndepParser::DyndepParser(State* state, FileReader* file_reader,
                            DyndepFile* dyndep_file)
     : Parser(state, file_reader)
diff --git a/src/dyndep_parser.h b/src/dyndep_parser.h
index 09a3722..8f4c28d 100644
--- a/src/dyndep_parser.h
+++ b/src/dyndep_parser.h
@@ -27,17 +27,18 @@
                DyndepFile* dyndep_file);
 
   /// Parse a text string of input.  Used by tests.
-  bool ParseTest(const string& input, string* err) {
+  bool ParseTest(const std::string& input, std::string* err) {
     return Parse("input", input, err);
   }
 
 private:
   /// Parse a file, given its contents as a string.
-  bool Parse(const string& filename, const string& input, string* err);
+  bool Parse(const std::string& filename, const std::string& input,
+             std:: string* err);
 
-  bool ParseDyndepVersion(string* err);
-  bool ParseLet(string* key, EvalString* val, string* err);
-  bool ParseEdge(string* err);
+  bool ParseDyndepVersion(std::string* err);
+  bool ParseLet(std::string* key, EvalString* val, std::string* err);
+  bool ParseEdge(std::string* err);
 
   DyndepFile* dyndep_file_;
   BindingEnv env_;
diff --git a/src/dyndep_parser_test.cc b/src/dyndep_parser_test.cc
index 39ec657..1bba7ba 100644
--- a/src/dyndep_parser_test.cc
+++ b/src/dyndep_parser_test.cc
@@ -22,6 +22,8 @@
 #include "state.h"
 #include "test.h"
 
+using namespace std;
+
 struct DyndepParserTest : public testing::Test {
   void AssertParse(const char* input) {
     DyndepParser parser(&state_, &fs_, &dyndep_file_);
diff --git a/src/edit_distance.cc b/src/edit_distance.cc
index 3bb62b8..34bf0e5 100644
--- a/src/edit_distance.cc
+++ b/src/edit_distance.cc
@@ -17,6 +17,8 @@
 #include <algorithm>
 #include <vector>
 
+using namespace std;
+
 int EditDistance(const StringPiece& s1,
                  const StringPiece& s2,
                  bool allow_replacements,
diff --git a/src/eval_env.cc b/src/eval_env.cc
index e9b6c43..796a326 100644
--- a/src/eval_env.cc
+++ b/src/eval_env.cc
@@ -16,6 +16,8 @@
 
 #include "eval_env.h"
 
+using namespace std;
+
 string BindingEnv::LookupVariable(const string& var) {
   map<string, string>::iterator i = bindings_.find(var);
   if (i != bindings_.end())
diff --git a/src/eval_env.h b/src/eval_env.h
index 8fb9bf4..ca7daa4 100644
--- a/src/eval_env.h
+++ b/src/eval_env.h
@@ -18,7 +18,6 @@
 #include <map>
 #include <string>
 #include <vector>
-using namespace std;
 
 #include "string_piece.h"
 
@@ -27,7 +26,7 @@
 /// An interface for a scope for variable (e.g. "$foo") lookups.
 struct Env {
   virtual ~Env() {}
-  virtual string LookupVariable(const string& var) = 0;
+  virtual std::string LookupVariable(const std::string& var) = 0;
 };
 
 /// A tokenized string that contains variable references.
@@ -35,10 +34,10 @@
 struct EvalString {
   /// @return The evaluated string with variable expanded using value found in
   ///         environment @a env.
-  string Evaluate(Env* env) const;
+  std::string Evaluate(Env* env) const;
 
   /// @return The string with variables not expanded.
-  string Unparse() const;
+  std::string Unparse() const;
 
   void Clear() { parsed_.clear(); }
   bool empty() const { return parsed_.empty(); }
@@ -48,32 +47,32 @@
 
   /// Construct a human-readable representation of the parsed state,
   /// for use in tests.
-  string Serialize() const;
+  std::string Serialize() const;
 
 private:
   enum TokenType { RAW, SPECIAL };
-  typedef vector<pair<string, TokenType> > TokenList;
+  typedef std::vector<std::pair<std::string, TokenType> > TokenList;
   TokenList parsed_;
 };
 
 /// An invokable build command and associated metadata (description, etc.).
 struct Rule {
-  explicit Rule(const string& name) : name_(name) {}
+  explicit Rule(const std::string& name) : name_(name) {}
 
-  const string& name() const { return name_; }
+  const std::string& name() const { return name_; }
 
-  void AddBinding(const string& key, const EvalString& val);
+  void AddBinding(const std::string& key, const EvalString& val);
 
-  static bool IsReservedBinding(const string& var);
+  static bool IsReservedBinding(const std::string& var);
 
-  const EvalString* GetBinding(const string& key) const;
+  const EvalString* GetBinding(const std::string& key) const;
 
  private:
   // Allow the parsers to reach into this object and fill out its fields.
   friend struct ManifestParser;
 
-  string name_;
-  typedef map<string, EvalString> Bindings;
+  std::string name_;
+  typedef std::map<std::string, EvalString> Bindings;
   Bindings bindings_;
 };
 
@@ -84,26 +83,26 @@
   explicit BindingEnv(BindingEnv* parent) : parent_(parent) {}
 
   virtual ~BindingEnv() {}
-  virtual string LookupVariable(const string& var);
+  virtual std::string LookupVariable(const std::string& var);
 
   void AddRule(const Rule* rule);
-  const Rule* LookupRule(const string& rule_name);
-  const Rule* LookupRuleCurrentScope(const string& rule_name);
-  const map<string, const Rule*>& GetRules() const;
+  const Rule* LookupRule(const std::string& rule_name);
+  const Rule* LookupRuleCurrentScope(const std::string& rule_name);
+  const std::map<std::string, const Rule*>& GetRules() const;
 
-  void AddBinding(const string& key, const string& val);
+  void AddBinding(const std::string& key, const std::string& val);
 
   /// This is tricky.  Edges want lookup scope to go in this order:
   /// 1) value set on edge itself (edge_->env_)
   /// 2) value set on rule, with expansion in the edge's scope
   /// 3) value set on enclosing scope of edge (edge_->env_->parent_)
   /// This function takes as parameters the necessary info to do (2).
-  string LookupWithFallback(const string& var, const EvalString* eval,
-                            Env* env);
+  std::string LookupWithFallback(const std::string& var, const EvalString* eval,
+                                 Env* env);
 
 private:
-  map<string, string> bindings_;
-  map<string, const Rule*> rules_;
+  std::map<std::string, std::string> bindings_;
+  std::map<std::string, const Rule*> rules_;
   BindingEnv* parent_;
 };
 
diff --git a/src/graph.cc b/src/graph.cc
index 28a9653..ea11360 100644
--- a/src/graph.cc
+++ b/src/graph.cc
@@ -28,6 +28,8 @@
 #include "state.h"
 #include "util.h"
 
+using namespace std;
+
 bool Node::Stat(DiskInterface* disk_interface, string* err) {
   return (mtime_ = disk_interface->Stat(path_, err)) != -1;
 }
diff --git a/src/graph.h b/src/graph.h
index 2fa54af..4833f49 100644
--- a/src/graph.h
+++ b/src/graph.h
@@ -17,7 +17,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 #include "dyndep.h"
 #include "eval_env.h"
@@ -36,7 +35,7 @@
 /// Information about a node in the dependency graph: the file, whether
 /// it's dirty, mtime, etc.
 struct Node {
-  Node(const string& path, uint64_t slash_bits)
+  Node(const std::string& path, uint64_t slash_bits)
       : path_(path),
         slash_bits_(slash_bits),
         mtime_(-1),
@@ -46,10 +45,10 @@
         id_(-1) {}
 
   /// Return false on error.
-  bool Stat(DiskInterface* disk_interface, string* err);
+  bool Stat(DiskInterface* disk_interface, std::string* err);
 
   /// Return false on error.
-  bool StatIfNecessary(DiskInterface* disk_interface, string* err) {
+  bool StatIfNecessary(DiskInterface* disk_interface, std::string* err) {
     if (status_known())
       return true;
     return Stat(disk_interface, err);
@@ -74,13 +73,13 @@
     return mtime_ != -1;
   }
 
-  const string& path() const { return path_; }
+  const std::string& path() const { return path_; }
   /// Get |path()| but use slash_bits to convert back to original slash styles.
-  string PathDecanonicalized() const {
+  std::string PathDecanonicalized() const {
     return PathDecanonicalized(path_, slash_bits_);
   }
-  static string PathDecanonicalized(const string& path,
-                                    uint64_t slash_bits);
+  static std::string PathDecanonicalized(const std::string& path,
+                                         uint64_t slash_bits);
   uint64_t slash_bits() const { return slash_bits_; }
 
   TimeStamp mtime() const { return mtime_; }
@@ -98,13 +97,13 @@
   int id() const { return id_; }
   void set_id(int id) { id_ = id; }
 
-  const vector<Edge*>& out_edges() const { return out_edges_; }
+  const std::vector<Edge*>& out_edges() const { return out_edges_; }
   void AddOutEdge(Edge* edge) { out_edges_.push_back(edge); }
 
   void Dump(const char* prefix="") const;
 
 private:
-  string path_;
+  std::string path_;
 
   /// Set bits starting from lowest for backslashes that were normalized to
   /// forward slashes by CanonicalizePath. See |PathDecanonicalized|.
@@ -130,7 +129,7 @@
   Edge* in_edge_;
 
   /// All Edges that use this Node as an input.
-  vector<Edge*> out_edges_;
+  std::vector<Edge*> out_edges_;
 
   /// A dense integer id for the node, assigned and used by DepsLog.
   int id_;
@@ -158,13 +157,13 @@
   std::string EvaluateCommand(bool incl_rsp_file = false) const;
 
   /// Returns the shell-escaped value of |key|.
-  std::string GetBinding(const string& key) const;
-  bool GetBindingBool(const string& key) const;
+  std::string GetBinding(const std::string& key) const;
+  bool GetBindingBool(const std::string& key) const;
 
   /// Like GetBinding("depfile"), but without shell escaping.
-  string GetUnescapedDepfile() const;
+  std::string GetUnescapedDepfile() const;
   /// Like GetBinding("dyndep"), but without shell escaping.
-  string GetUnescapedDyndep() const;
+  std::string GetUnescapedDyndep() const;
   /// Like GetBinding("rspfile"), but without shell escaping.
   std::string GetUnescapedRspfile() const;
 
@@ -172,8 +171,8 @@
 
   const Rule* rule_;
   Pool* pool_;
-  vector<Node*> inputs_;
-  vector<Node*> outputs_;
+  std::vector<Node*> inputs_;
+  std::vector<Node*> outputs_;
   Node* dyndep_;
   BindingEnv* env_;
   VisitMark mark_;
@@ -232,7 +231,7 @@
   /// Load implicit dependencies for \a edge.
   /// @return false on error (without filling \a err if info is just missing
   //                          or out of date).
-  bool LoadDeps(Edge* edge, string* err);
+  bool LoadDeps(Edge* edge, std::string* err);
 
   DepsLog* deps_log() const {
     return deps_log_;
@@ -241,15 +240,15 @@
  private:
   /// Load implicit dependencies for \a edge from a depfile attribute.
   /// @return false on error (without filling \a err if info is just missing).
-  bool LoadDepFile(Edge* edge, const string& path, string* err);
+  bool LoadDepFile(Edge* edge, const std::string& path, std::string* err);
 
   /// Load implicit dependencies for \a edge from the DepsLog.
   /// @return false on error (without filling \a err if info is just missing).
-  bool LoadDepsFromLog(Edge* edge, string* err);
+  bool LoadDepsFromLog(Edge* edge, std::string* err);
 
   /// Preallocate \a count spaces in the input array on \a edge, returning
   /// an iterator pointing at the first new space.
-  vector<Node*>::iterator PreallocateSpace(Edge* edge, int count);
+  std::vector<Node*>::iterator PreallocateSpace(Edge* edge, int count);
 
   /// If we don't have a edge that generates this input already,
   /// create one; this makes us not abort if the input is missing,
@@ -279,12 +278,12 @@
   /// needs to be re-run, and update outputs_ready_ and each outputs' |dirty_|
   /// state accordingly.
   /// Returns false on failure.
-  bool RecomputeDirty(Node* node, string* err);
+  bool RecomputeDirty(Node* node, std::string* err);
 
   /// Recompute whether any output of the edge is dirty, if so sets |*dirty|.
   /// Returns false on failure.
   bool RecomputeOutputsDirty(Edge* edge, Node* most_recent_input,
-                             bool* dirty, string* err);
+                             bool* dirty, std::string* err);
 
   BuildLog* build_log() const {
     return build_log_;
@@ -301,17 +300,17 @@
   /// build graph with the new information.  One overload accepts
   /// a caller-owned 'DyndepFile' object in which to store the
   /// information loaded from the dyndep file.
-  bool LoadDyndeps(Node* node, string* err) const;
-  bool LoadDyndeps(Node* node, DyndepFile* ddf, string* err) const;
+  bool LoadDyndeps(Node* node, std::string* err) const;
+  bool LoadDyndeps(Node* node, DyndepFile* ddf, std::string* err) const;
 
  private:
-  bool RecomputeDirty(Node* node, vector<Node*>* stack, string* err);
-  bool VerifyDAG(Node* node, vector<Node*>* stack, string* err);
+  bool RecomputeDirty(Node* node, std::vector<Node*>* stack, std::string* err);
+  bool VerifyDAG(Node* node, std::vector<Node*>* stack, std::string* err);
 
   /// Recompute whether a given single output should be marked dirty.
   /// Returns true if so.
   bool RecomputeOutputDirty(const Edge* edge, const Node* most_recent_input,
-                            const string& command, Node* output);
+                            const std::string& command, Node* output);
 
   BuildLog* build_log_;
   DiskInterface* disk_interface_;
diff --git a/src/graph_test.cc b/src/graph_test.cc
index 660943f..14f6375 100644
--- a/src/graph_test.cc
+++ b/src/graph_test.cc
@@ -17,6 +17,8 @@
 
 #include "test.h"
 
+using namespace std;
+
 struct GraphTest : public StateTestWithBuiltinRules {
   GraphTest() : scan_(&state_, NULL, NULL, &fs_, NULL) {}
 
diff --git a/src/graphviz.cc b/src/graphviz.cc
index 0d07251..37b7108 100644
--- a/src/graphviz.cc
+++ b/src/graphviz.cc
@@ -20,6 +20,8 @@
 #include "dyndep.h"
 #include "graph.h"
 
+using namespace std;
+
 void GraphViz::AddTarget(Node* node) {
   if (visited_nodes_.find(node) != visited_nodes_.end())
     return;
diff --git a/src/hash_collision_bench.cc b/src/hash_collision_bench.cc
index ff947dc..52ff56d 100644
--- a/src/hash_collision_bench.cc
+++ b/src/hash_collision_bench.cc
@@ -15,11 +15,12 @@
 #include "build_log.h"
 
 #include <algorithm>
-using namespace std;
 
 #include <stdlib.h>
 #include <time.h>
 
+using namespace std;
+
 int random(int low, int high) {
   return int(low + (rand() / double(RAND_MAX)) * (high - low) + 0.5);
 }
diff --git a/src/includes_normalize-win32.cc b/src/includes_normalize-win32.cc
index 79bf5b4..9f8dfc2 100644
--- a/src/includes_normalize-win32.cc
+++ b/src/includes_normalize-win32.cc
@@ -24,6 +24,8 @@
 
 #include <windows.h>
 
+using namespace std;
+
 namespace {
 
 bool InternalGetFullPathName(const StringPiece& file_name, char* buffer,
diff --git a/src/includes_normalize.h b/src/includes_normalize.h
index 0339581..7d50556 100644
--- a/src/includes_normalize.h
+++ b/src/includes_normalize.h
@@ -14,7 +14,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 struct StringPiece;
 
@@ -22,18 +21,20 @@
 /// TODO: this likely duplicates functionality of CanonicalizePath; refactor.
 struct IncludesNormalize {
   /// Normalize path relative to |relative_to|.
-  IncludesNormalize(const string& relative_to);
+  IncludesNormalize(const std::string& relative_to);
 
   // Internal utilities made available for testing, maybe useful otherwise.
-  static string AbsPath(StringPiece s, string* err);
-  static string Relativize(StringPiece path,
-                           const vector<StringPiece>& start_list, string* err);
+  static std::string AbsPath(StringPiece s, std::string* err);
+  static std::string Relativize(StringPiece path,
+                                const std::vector<StringPiece>& start_list,
+                                std::string* err);
 
   /// Normalize by fixing slashes style, fixing redundant .. and . and makes the
   /// path |input| relative to |this->relative_to_| and store to |result|.
-  bool Normalize(const string& input, string* result, string* err) const;
+  bool Normalize(const std::string& input, std::string* result,
+                 std::string* err) const;
 
  private:
-  string relative_to_;
-  vector<StringPiece> split_relative_to_;
+  std::string relative_to_;
+  std::vector<StringPiece> split_relative_to_;
 };
diff --git a/src/includes_normalize_test.cc b/src/includes_normalize_test.cc
index dbcdbe0..9214f53 100644
--- a/src/includes_normalize_test.cc
+++ b/src/includes_normalize_test.cc
@@ -22,6 +22,8 @@
 #include "test.h"
 #include "util.h"
 
+using namespace std;
+
 namespace {
 
 string GetCurDir() {
diff --git a/src/inline.sh b/src/inline.sh
index b64e8ca..5092fa2 100755
--- a/src/inline.sh
+++ b/src/inline.sh
@@ -19,7 +19,14 @@
 # stdin and writes stdout.
 
 varname="$1"
-echo "const char $varname[] ="
-od -t x1 -A n -v | sed -e 's|^[\t ]\{0,\}$||g; s|[\t ]\{1,\}| |g; s| \{1,\}$||g; s| |\\x|g; s|^|"|; s|$|"|'
-echo ";"
 
+# 'od' and 'sed' may not be available on all platforms, and may not support the
+# flags used here. We must ensure that the script exits with a non-zero exit
+# code in those cases.
+byte_vals=$(od -t x1 -A n -v) || exit 1
+escaped_byte_vals=$(echo "${byte_vals}" \
+  | sed -e 's|^[\t ]\{0,\}$||g; s|[\t ]\{1,\}| |g; s| \{1,\}$||g; s| |\\x|g; s|^|"|; s|$|"|') \
+  || exit 1
+
+# Only write output once we have successfully generated the required data
+printf "const char %s[] = \n%s;" "${varname}" "${escaped_byte_vals}"
diff --git a/src/lexer.cc b/src/lexer.cc
index 35ae97b..6e4a470 100644
--- a/src/lexer.cc
+++ b/src/lexer.cc
@@ -1,4 +1,4 @@
-/* Generated by re2c 0.16 */
+/* Generated by re2c 1.1.1 */
 // Copyright 2011 Google Inc. All Rights Reserved.
 //
 // Licensed under the Apache License, Version 2.0 (the "License");
@@ -20,6 +20,8 @@
 #include "eval_env.h"
 #include "util.h"
 
+using namespace std;
+
 bool Lexer::Error(const string& message, string* err) {
   // Compute line/column.
   int line = 1;
@@ -233,8 +235,7 @@
 	goto yy5;
 yy9:
 	yyaccept = 0;
-	q = ++p;
-	yych = *p;
+	yych = *(q = ++p);
 	if (yybm[0+yych] & 32) {
 		goto yy9;
 	}
@@ -252,8 +253,7 @@
 	if (yych <= 0x00) goto yy5;
 	goto yy33;
 yy13:
-	++p;
-	yych = *p;
+	yych = *++p;
 yy14:
 	if (yybm[0+yych] & 64) {
 		goto yy13;
@@ -290,8 +290,8 @@
 	if (yych == 'u') goto yy41;
 	goto yy14;
 yy26:
-	++p;
-	if ((yych = *p) == '|') goto yy42;
+	yych = *++p;
+	if (yych == '|') goto yy42;
 	{ token = PIPE;     break; }
 yy28:
 	++p;
@@ -307,8 +307,7 @@
 		goto yy5;
 	}
 yy32:
-	++p;
-	yych = *p;
+	yych = *++p;
 yy33:
 	if (yybm[0+yych] & 128) {
 		goto yy32;
@@ -380,14 +379,14 @@
 	if (yych == 'u') goto yy61;
 	goto yy14;
 yy53:
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = POOL;     break; }
 yy55:
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = RULE;     break; }
@@ -396,8 +395,8 @@
 	if (yych == 'i') goto yy62;
 	goto yy14;
 yy58:
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = BUILD;    break; }
@@ -426,22 +425,22 @@
 	if (yych == 'j') goto yy70;
 	goto yy14;
 yy66:
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = DEFAULT;  break; }
 yy68:
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = INCLUDE;  break; }
 yy70:
 	yych = *++p;
 	if (yych != 'a') goto yy14;
-	++p;
-	if (yybm[0+(yych = *p)] & 64) {
+	yych = *++p;
+	if (yybm[0+yych] & 64) {
 		goto yy13;
 	}
 	{ token = SUBNINJA; break; }
@@ -521,8 +520,7 @@
 yy78:
 	{ break; }
 yy79:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 128) {
 		goto yy79;
 	}
@@ -600,8 +598,7 @@
       return false;
     }
 yy93:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 128) {
 		goto yy93;
 	}
@@ -681,8 +678,7 @@
       return Error("unexpected EOF", err);
     }
 yy100:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 16) {
 		goto yy100;
 	}
@@ -704,8 +700,8 @@
       }
     }
 yy105:
-	++p;
-	if ((yych = *p) == '\n') goto yy108;
+	yych = *++p;
+	if (yych == '\n') goto yy108;
 	{
       last_token_ = start;
       return Error(DescribeLastError(), err);
@@ -750,8 +746,7 @@
       return Error("bad $-escape (literal $ must be written as $$)", err);
     }
 yy112:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 32) {
 		goto yy112;
 	}
@@ -775,8 +770,7 @@
       continue;
     }
 yy120:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 64) {
 		goto yy120;
 	}
@@ -797,15 +791,13 @@
 	}
 	goto yy111;
 yy126:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yych == ' ') goto yy126;
 	{
       continue;
     }
 yy129:
-	++p;
-	yych = *p;
+	yych = *++p;
 	if (yybm[0+yych] & 128) {
 		goto yy129;
 	}
diff --git a/src/lexer.h b/src/lexer.h
index f366556..788d948 100644
--- a/src/lexer.h
+++ b/src/lexer.h
@@ -55,7 +55,7 @@
 
   /// If the last token read was an ERROR token, provide more info
   /// or the empty string.
-  string DescribeLastError();
+  std::string DescribeLastError();
 
   /// Start parsing some input.
   void Start(StringPiece filename, StringPiece input);
@@ -71,30 +71,30 @@
 
   /// Read a simple identifier (a rule or variable name).
   /// Returns false if a name can't be read.
-  bool ReadIdent(string* out);
+  bool ReadIdent(std::string* out);
 
   /// Read a path (complete with $escapes).
   /// Returns false only on error, returned path may be empty if a delimiter
   /// (space, newline) is hit.
-  bool ReadPath(EvalString* path, string* err) {
+  bool ReadPath(EvalString* path, std::string* err) {
     return ReadEvalString(path, true, err);
   }
 
   /// Read the value side of a var = value line (complete with $escapes).
   /// Returns false only on error.
-  bool ReadVarValue(EvalString* value, string* err) {
+  bool ReadVarValue(EvalString* value, std::string* err) {
     return ReadEvalString(value, false, err);
   }
 
   /// Construct an error message with context.
-  bool Error(const string& message, string* err);
+  bool Error(const std::string& message, std::string* err);
 
 private:
   /// Skip past whitespace (called after each read token/ident/etc.).
   void EatWhitespace();
 
   /// Read a $-escaped string.
-  bool ReadEvalString(EvalString* eval, bool path, string* err);
+  bool ReadEvalString(EvalString* eval, bool path, std::string* err);
 
   StringPiece filename_;
   StringPiece input_;
diff --git a/src/lexer.in.cc b/src/lexer.in.cc
index c1fb822..88007e7 100644
--- a/src/lexer.in.cc
+++ b/src/lexer.in.cc
@@ -19,6 +19,8 @@
 #include "eval_env.h"
 #include "util.h"
 
+using namespace std;
+
 bool Lexer::Error(const string& message, string* err) {
   // Compute line/column.
   int line = 1;
diff --git a/src/lexer_test.cc b/src/lexer_test.cc
index 331d8e1..c5c416d 100644
--- a/src/lexer_test.cc
+++ b/src/lexer_test.cc
@@ -17,6 +17,8 @@
 #include "eval_env.h"
 #include "test.h"
 
+using namespace std;
+
 TEST(Lexer, ReadVarValue) {
   Lexer lexer("plain text $var $VaR ${x}\n");
   EvalString eval;
diff --git a/src/line_printer.cc b/src/line_printer.cc
index c93173e..68c58ad 100644
--- a/src/line_printer.cc
+++ b/src/line_printer.cc
@@ -30,6 +30,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 LinePrinter::LinePrinter() : have_blank_line_(true), console_locked_(false) {
   const char* term = getenv("TERM");
 #ifndef _WIN32
diff --git a/src/line_printer.h b/src/line_printer.h
index 92d4dc4..a8ec9ff 100644
--- a/src/line_printer.h
+++ b/src/line_printer.h
@@ -17,7 +17,6 @@
 
 #include <stddef.h>
 #include <string>
-using namespace std;
 
 /// Prints lines of text, possibly overprinting previously printed lines
 /// if the terminal supports it.
@@ -35,10 +34,10 @@
   };
   /// Overprints the current line. If type is ELIDE, elides to_print to fit on
   /// one line.
-  void Print(string to_print, LineType type);
+  void Print(std::string to_print, LineType type);
 
   /// Prints a string on a new line, not overprinting previous output.
-  void PrintOnNewLine(const string& to_print);
+  void PrintOnNewLine(const std::string& to_print);
 
   /// Lock or unlock the console.  Any output sent to the LinePrinter while the
   /// console is locked will not be printed until it is unlocked.
@@ -58,13 +57,13 @@
   bool console_locked_;
 
   /// Buffered current line while console is locked.
-  string line_buffer_;
+  std::string line_buffer_;
 
   /// Buffered line type while console is locked.
   LineType line_type_;
 
   /// Buffered console output while console is locked.
-  string output_buffer_;
+  std::string output_buffer_;
 
 #ifdef _WIN32
   void* console_;
diff --git a/src/manifest_parser.cc b/src/manifest_parser.cc
index bb53dc2..860a8fc 100644
--- a/src/manifest_parser.cc
+++ b/src/manifest_parser.cc
@@ -23,6 +23,8 @@
 #include "util.h"
 #include "version.h"
 
+using namespace std;
+
 ManifestParser::ManifestParser(State* state, FileReader* file_reader,
                                ManifestParserOptions options)
     : Parser(state, file_reader),
diff --git a/src/manifest_parser.h b/src/manifest_parser.h
index e14d069..954cf46 100644
--- a/src/manifest_parser.h
+++ b/src/manifest_parser.h
@@ -44,24 +44,25 @@
                  ManifestParserOptions options = ManifestParserOptions());
 
   /// Parse a text string of input.  Used by tests.
-  bool ParseTest(const string& input, string* err) {
+  bool ParseTest(const std::string& input, std::string* err) {
     quiet_ = true;
     return Parse("input", input, err);
   }
 
 private:
   /// Parse a file, given its contents as a string.
-  bool Parse(const string& filename, const string& input, string* err);
+  bool Parse(const std::string& filename, const std::string& input,
+             std::string* err);
 
   /// Parse various statement types.
-  bool ParsePool(string* err);
-  bool ParseRule(string* err);
-  bool ParseLet(string* key, EvalString* val, string* err);
-  bool ParseEdge(string* err);
-  bool ParseDefault(string* err);
+  bool ParsePool(std::string* err);
+  bool ParseRule(std::string* err);
+  bool ParseLet(std::string* key, EvalString* val, std::string* err);
+  bool ParseEdge(std::string* err);
+  bool ParseDefault(std::string* err);
 
   /// Parse either a 'subninja' or 'include' line.
-  bool ParseFileInclude(bool new_scope, string* err);
+  bool ParseFileInclude(bool new_scope, std::string* err);
 
   BindingEnv* env_;
   ManifestParserOptions options_;
diff --git a/src/manifest_parser_perftest.cc b/src/manifest_parser_perftest.cc
index 67d11f9..92f5e13 100644
--- a/src/manifest_parser_perftest.cc
+++ b/src/manifest_parser_perftest.cc
@@ -37,6 +37,8 @@
 #include "state.h"
 #include "util.h"
 
+using namespace std;
+
 bool WriteFakeManifests(const string& dir, string* err) {
   RealDiskInterface disk_interface;
   TimeStamp mtime = disk_interface.Stat(dir + "/build.ninja", err);
diff --git a/src/manifest_parser_test.cc b/src/manifest_parser_test.cc
index f4aee2d..ec2eeed 100644
--- a/src/manifest_parser_test.cc
+++ b/src/manifest_parser_test.cc
@@ -21,6 +21,8 @@
 #include "state.h"
 #include "test.h"
 
+using namespace std;
+
 struct ParserTest : public testing::Test {
   void AssertParse(const char* input) {
     ManifestParser parser(&state, &fs_);
diff --git a/src/metrics.cc b/src/metrics.cc
index a7d3c7a..dbaf221 100644
--- a/src/metrics.cc
+++ b/src/metrics.cc
@@ -28,6 +28,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 Metrics* g_metrics = NULL;
 
 namespace {
diff --git a/src/metrics.h b/src/metrics.h
index b6da859..11239b5 100644
--- a/src/metrics.h
+++ b/src/metrics.h
@@ -17,7 +17,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 #include "util.h"  // For int64_t.
 
@@ -26,7 +25,7 @@
 
 /// A single metrics we're tracking, like "depfile load time".
 struct Metric {
-  string name;
+  std::string name;
   /// Number of times we've hit the code path.
   int count;
   /// Total time (in micros) we've spent on the code path.
@@ -49,13 +48,13 @@
 
 /// The singleton that stores metrics and prints the report.
 struct Metrics {
-  Metric* NewMetric(const string& name);
+  Metric* NewMetric(const std::string& name);
 
   /// Print a summary report to stdout.
   void Report();
 
 private:
-  vector<Metric*> metrics_;
+  std::vector<Metric*> metrics_;
 };
 
 /// Get the current time as relative to some epoch.
diff --git a/src/minidump-win32.cc b/src/minidump-win32.cc
index ca93638..9aea767 100644
--- a/src/minidump-win32.cc
+++ b/src/minidump-win32.cc
@@ -19,6 +19,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 typedef BOOL (WINAPI *MiniDumpWriteDumpFunc) (
     IN HANDLE,
     IN DWORD,
diff --git a/src/msvc_helper-win32.cc b/src/msvc_helper-win32.cc
index de6147a..1148ae5 100644
--- a/src/msvc_helper-win32.cc
+++ b/src/msvc_helper-win32.cc
@@ -18,6 +18,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 namespace {
 
 string Replace(const string& input, const string& find, const string& replace) {
diff --git a/src/msvc_helper.h b/src/msvc_helper.h
index 70d1fff..568b9f9 100644
--- a/src/msvc_helper.h
+++ b/src/msvc_helper.h
@@ -13,9 +13,8 @@
 // limitations under the License.
 
 #include <string>
-using namespace std;
 
-string EscapeForDepfile(const string& path);
+std::string EscapeForDepfile(const std::string& path);
 
 /// Wraps a synchronous execution of a CL subprocess.
 struct CLWrapper {
@@ -27,7 +26,7 @@
 
   /// Start a process and gather its raw output.  Returns its exit code.
   /// Crashes (calls Fatal()) on error.
-  int Run(const string& command, string* output);
+  int Run(const std::string& command, std::string* output);
 
   void* env_block_;
 };
diff --git a/src/msvc_helper_main-win32.cc b/src/msvc_helper_main-win32.cc
index 644b2a2..7d59307 100644
--- a/src/msvc_helper_main-win32.cc
+++ b/src/msvc_helper_main-win32.cc
@@ -24,6 +24,8 @@
 
 #include "getopt.h"
 
+using namespace std;
+
 namespace {
 
 void Usage() {
diff --git a/src/msvc_helper_test.cc b/src/msvc_helper_test.cc
index eaae51f..d9e2ee6 100644
--- a/src/msvc_helper_test.cc
+++ b/src/msvc_helper_test.cc
@@ -17,6 +17,8 @@
 #include "test.h"
 #include "util.h"
 
+using namespace std;
+
 TEST(EscapeForDepfileTest, SpacesInFilename) {
   ASSERT_EQ("sub\\some\\ sdk\\foo.h",
             EscapeForDepfile("sub\\some sdk\\foo.h"));
diff --git a/src/ninja.cc b/src/ninja.cc
index 00e3a5c..471a023 100644
--- a/src/ninja.cc
+++ b/src/ninja.cc
@@ -46,6 +46,8 @@
 #include "util.h"
 #include "version.h"
 
+using namespace std;
+
 #ifdef _MSC_VER
 // Defined in msvc_helper_main-win32.cc.
 int MSVCHelperMain(int argc, char** argv);
diff --git a/src/ninja_test.cc b/src/ninja_test.cc
index d642c5c..b40e176 100644
--- a/src/ninja_test.cc
+++ b/src/ninja_test.cc
@@ -28,6 +28,8 @@
 #include "test.h"
 #include "line_printer.h"
 
+using namespace std;
+
 struct RegisteredTest {
   testing::Test* (*factory)();
   const char *name;
diff --git a/src/parser.cc b/src/parser.cc
index 745c532..756922d 100644
--- a/src/parser.cc
+++ b/src/parser.cc
@@ -17,6 +17,8 @@
 #include "disk_interface.h"
 #include "metrics.h"
 
+using namespace std;
+
 bool Parser::Load(const string& filename, string* err, Lexer* parent) {
   METRIC_RECORD(".ninja parse");
   string contents;
diff --git a/src/parser.h b/src/parser.h
index e2d2b97..011fad8 100644
--- a/src/parser.h
+++ b/src/parser.h
@@ -17,8 +17,6 @@
 
 #include <string>
 
-using namespace std;
-
 #include "lexer.h"
 
 struct FileReader;
@@ -30,12 +28,12 @@
       : state_(state), file_reader_(file_reader) {}
 
   /// Load and parse a file.
-  bool Load(const string& filename, string* err, Lexer* parent = NULL);
+  bool Load(const std::string& filename, std::string* err, Lexer* parent = NULL);
 
 protected:
   /// If the next token is not \a expected, produce an error string
   /// saying "expected foo, got bar".
-  bool ExpectToken(Lexer::Token expected, string* err);
+  bool ExpectToken(Lexer::Token expected, std::string* err);
 
   State* state_;
   FileReader* file_reader_;
@@ -43,8 +41,8 @@
 
 private:
   /// Parse a file, given its contents as a string.
-  virtual bool Parse(const string& filename, const string& input,
-                     string* err) = 0;
+  virtual bool Parse(const std::string& filename, const std::string& input,
+                     std::string* err) = 0;
 };
 
 #endif  // NINJA_PARSER_H_
diff --git a/src/state.cc b/src/state.cc
index 74cf4c1..d3a9e29 100644
--- a/src/state.cc
+++ b/src/state.cc
@@ -22,6 +22,7 @@
 #include "metrics.h"
 #include "util.h"
 
+using namespace std;
 
 void Pool::EdgeScheduled(const Edge& edge) {
   if (depth_ != 0)
diff --git a/src/state.h b/src/state.h
index 6fe886c..f553ed4 100644
--- a/src/state.h
+++ b/src/state.h
@@ -19,7 +19,6 @@
 #include <set>
 #include <string>
 #include <vector>
-using namespace std;
 
 #include "eval_env.h"
 #include "hash_map.h"
@@ -38,13 +37,13 @@
 /// the total scheduled weight diminishes enough (i.e. when a scheduled edge
 /// completes).
 struct Pool {
-  Pool(const string& name, int depth)
+  Pool(const std::string& name, int depth)
     : name_(name), current_use_(0), depth_(depth), delayed_(&WeightedEdgeCmp) {}
 
   // A depth of 0 is infinite
   bool is_valid() const { return depth_ >= 0; }
   int depth() const { return depth_; }
-  const string& name() const { return name_; }
+  const std::string& name() const { return name_; }
   int current_use() const { return current_use_; }
 
   /// true if the Pool might delay this edge
@@ -62,13 +61,13 @@
   void DelayEdge(Edge* edge);
 
   /// Pool will add zero or more edges to the ready_queue
-  void RetrieveReadyEdges(set<Edge*>* ready_queue);
+  void RetrieveReadyEdges(std::set<Edge*>* ready_queue);
 
   /// Dump the Pool and its edges (useful for debugging).
   void Dump() const;
 
  private:
-  string name_;
+  std::string name_;
 
   /// |current_use_| is the total of the weights of the edges which are
   /// currently scheduled in the Plan (i.e. the edges in Plan::ready_).
@@ -77,7 +76,7 @@
 
   static bool WeightedEdgeCmp(const Edge* a, const Edge* b);
 
-  typedef set<Edge*,bool(*)(const Edge*, const Edge*)> DelayedEdges;
+  typedef std::set<Edge*,bool(*)(const Edge*, const Edge*)> DelayedEdges;
   DelayedEdges delayed_;
 };
 
@@ -90,17 +89,17 @@
   State();
 
   void AddPool(Pool* pool);
-  Pool* LookupPool(const string& pool_name);
+  Pool* LookupPool(const std::string& pool_name);
 
   Edge* AddEdge(const Rule* rule);
 
   Node* GetNode(StringPiece path, uint64_t slash_bits);
   Node* LookupNode(StringPiece path) const;
-  Node* SpellcheckNode(const string& path);
+  Node* SpellcheckNode(const std::string& path);
 
   void AddIn(Edge* edge, StringPiece path, uint64_t slash_bits);
   bool AddOut(Edge* edge, StringPiece path, uint64_t slash_bits);
-  bool AddDefault(StringPiece path, string* error);
+  bool AddDefault(StringPiece path, std::string* error);
 
   /// Reset state.  Keeps all nodes and edges, but restores them to the
   /// state where we haven't yet examined the disk for dirty state.
@@ -111,21 +110,21 @@
 
   /// @return the root node(s) of the graph. (Root nodes have no output edges).
   /// @param error where to write the error message if somethings went wrong.
-  vector<Node*> RootNodes(string* error) const;
-  vector<Node*> DefaultNodes(string* error) const;
+  std::vector<Node*> RootNodes(std::string* error) const;
+  std::vector<Node*> DefaultNodes(std::string* error) const;
 
   /// Mapping of path -> Node.
   typedef ExternalStringHashMap<Node*>::Type Paths;
   Paths paths_;
 
   /// All the pools used in the graph.
-  map<string, Pool*> pools_;
+  std::map<std::string, Pool*> pools_;
 
   /// All the edges of the graph.
-  vector<Edge*> edges_;
+  std::vector<Edge*> edges_;
 
   BindingEnv bindings_;
-  vector<Node*> defaults_;
+  std::vector<Node*> defaults_;
 };
 
 #endif  // NINJA_STATE_H_
diff --git a/src/state_test.cc b/src/state_test.cc
index 458b519..96469f9 100644
--- a/src/state_test.cc
+++ b/src/state_test.cc
@@ -16,6 +16,8 @@
 #include "state.h"
 #include "test.h"
 
+using namespace std;
+
 namespace {
 
 TEST(State, Basic) {
diff --git a/src/string_piece.h b/src/string_piece.h
index 031bda4..1c0bee6 100644
--- a/src/string_piece.h
+++ b/src/string_piece.h
@@ -17,8 +17,6 @@
 
 #include <string>
 
-using namespace std;
-
 #include <string.h>
 
 /// StringPiece represents a slice of a string whose memory is managed
@@ -30,7 +28,7 @@
   StringPiece() : str_(NULL), len_(0) {}
 
   /// The constructors intentionally allow for implicit conversions.
-  StringPiece(const string& str) : str_(str.data()), len_(str.size()) {}
+  StringPiece(const std::string& str) : str_(str.data()), len_(str.size()) {}
   StringPiece(const char* str) : str_(str), len_(strlen(str)) {}
 
   StringPiece(const char* str, size_t len) : str_(str), len_(len) {}
@@ -38,14 +36,15 @@
   bool operator==(const StringPiece& other) const {
     return len_ == other.len_ && memcmp(str_, other.str_, len_) == 0;
   }
+
   bool operator!=(const StringPiece& other) const {
     return !(*this == other);
   }
 
   /// Convert the slice into a full-fledged std::string, copying the
   /// data into a new string.
-  string AsString() const {
-    return len_ ? string(str_, len_) : string();
+  std::string AsString() const {
+    return len_ ? std::string(str_, len_) : std::string();
   }
 
   const_iterator begin() const {
diff --git a/src/string_piece_util.h b/src/string_piece_util.h
index 2e40b9f..28470f1 100644
--- a/src/string_piece_util.h
+++ b/src/string_piece_util.h
@@ -19,11 +19,10 @@
 #include <vector>
 
 #include "string_piece.h"
-using namespace std;
 
-vector<StringPiece> SplitStringPiece(StringPiece input, char sep);
+std::vector<StringPiece> SplitStringPiece(StringPiece input, char sep);
 
-string JoinStringPiece(const vector<StringPiece>& list, char sep);
+std::string JoinStringPiece(const std::vector<StringPiece>& list, char sep);
 
 inline char ToLowerASCII(char c) {
   return (c >= 'A' && c <= 'Z') ? (c + ('a' - 'A')) : c;
diff --git a/src/string_piece_util_test.cc b/src/string_piece_util_test.cc
index 648c647..b77ae84 100644
--- a/src/string_piece_util_test.cc
+++ b/src/string_piece_util_test.cc
@@ -16,6 +16,8 @@
 
 #include "test.h"
 
+using namespace std;
+
 TEST(StringPieceUtilTest, SplitStringPiece) {
   {
     string input("a:b:c");
diff --git a/src/subprocess-posix.cc b/src/subprocess-posix.cc
index 74785d1..0c5f556 100644
--- a/src/subprocess-posix.cc
+++ b/src/subprocess-posix.cc
@@ -34,6 +34,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 Subprocess::Subprocess(bool use_console) : fd_(-1), pid_(-1),
                                            use_console_(use_console) {
 }
diff --git a/src/subprocess-win32.cc b/src/subprocess-win32.cc
index d221476..ff3baac 100644
--- a/src/subprocess-win32.cc
+++ b/src/subprocess-win32.cc
@@ -21,6 +21,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 Subprocess::Subprocess(bool use_console) : child_(NULL) , overlapped_(),
                                            is_reading_(false),
                                            use_console_(use_console) {
diff --git a/src/subprocess.h b/src/subprocess.h
index b2d486c..9e3d2ee 100644
--- a/src/subprocess.h
+++ b/src/subprocess.h
@@ -18,7 +18,6 @@
 #include <string>
 #include <vector>
 #include <queue>
-using namespace std;
 
 #ifdef _WIN32
 #include <windows.h>
@@ -49,14 +48,14 @@
 
   bool Done() const;
 
-  const string& GetOutput() const;
+  const std::string& GetOutput() const;
 
  private:
   Subprocess(bool use_console);
-  bool Start(struct SubprocessSet* set, const string& command);
+  bool Start(struct SubprocessSet* set, const std::string& command);
   void OnPipeReady();
 
-  string buf_;
+  std::string buf_;
 
 #ifdef _WIN32
   /// Set up pipe_ as the parent-side pipe of the subprocess; return the
@@ -84,13 +83,13 @@
   SubprocessSet();
   ~SubprocessSet();
 
-  Subprocess* Add(const string& command, bool use_console = false);
+  Subprocess* Add(const std::string& command, bool use_console = false);
   bool DoWork();
   Subprocess* NextFinished();
   void Clear();
 
-  vector<Subprocess*> running_;
-  queue<Subprocess*> finished_;
+  std::vector<Subprocess*> running_;
+  std::queue<Subprocess*> finished_;
 
 #ifdef _WIN32
   static BOOL WINAPI NotifyInterrupted(DWORD dwCtrlType);
diff --git a/src/subprocess_test.cc b/src/subprocess_test.cc
index 6e487db..073fe86 100644
--- a/src/subprocess_test.cc
+++ b/src/subprocess_test.cc
@@ -24,6 +24,8 @@
 #include <unistd.h>
 #endif
 
+using namespace std;
+
 namespace {
 
 #ifdef _WIN32
diff --git a/src/test.cc b/src/test.cc
index 021005e..11b1c9e 100644
--- a/src/test.cc
+++ b/src/test.cc
@@ -43,6 +43,8 @@
 }
 #endif
 
+using namespace std;
+
 namespace {
 
 #ifdef _WIN32
diff --git a/src/test.h b/src/test.h
index 6af17b3..4552c34 100644
--- a/src/test.h
+++ b/src/test.h
@@ -118,7 +118,7 @@
   void AddCatRule(State* state);
 
   /// Short way to get a Node by its path from state_.
-  Node* GetNode(const string& path);
+  Node* GetNode(const std::string& path);
 
   State state_;
 };
@@ -135,7 +135,7 @@
   VirtualFileSystem() : now_(1) {}
 
   /// "Create" a file with contents.
-  void Create(const string& path, const string& contents);
+  void Create(const std::string& path, const std::string& contents);
 
   /// Tick "time" forwards; subsequent file operations will be newer than
   /// previous ones.
@@ -144,25 +144,26 @@
   }
 
   // DiskInterface
-  virtual TimeStamp Stat(const string& path, string* err) const;
-  virtual bool WriteFile(const string& path, const string& contents);
-  virtual bool MakeDir(const string& path);
-  virtual Status ReadFile(const string& path, string* contents, string* err);
-  virtual int RemoveFile(const string& path);
+  virtual TimeStamp Stat(const std::string& path, std::string* err) const;
+  virtual bool WriteFile(const std::string& path, const std::string& contents);
+  virtual bool MakeDir(const std::string& path);
+  virtual Status ReadFile(const std::string& path, std::string* contents,
+                          std::string* err);
+  virtual int RemoveFile(const std::string& path);
 
   /// An entry for a single in-memory file.
   struct Entry {
     int mtime;
-    string stat_error;  // If mtime is -1.
-    string contents;
+    std::string stat_error;  // If mtime is -1.
+    std::string contents;
   };
 
-  vector<string> directories_made_;
-  vector<string> files_read_;
-  typedef map<string, Entry> FileMap;
+  std::vector<std::string> directories_made_;
+  std::vector<std::string> files_read_;
+  typedef std::map<std::string, Entry> FileMap;
   FileMap files_;
-  set<string> files_removed_;
-  set<string> files_created_;
+  std::set<std::string> files_removed_;
+  std::set<std::string> files_created_;
 
   /// A simple fake timestamp for file operations.
   int now_;
@@ -170,15 +171,15 @@
 
 struct ScopedTempDir {
   /// Create a temporary directory and chdir into it.
-  void CreateAndEnter(const string& name);
+  void CreateAndEnter(const std::string& name);
 
   /// Clean up the temporary directory.
   void Cleanup();
 
   /// The temp directory containing our dir.
-  string start_dir_;
+  std::string start_dir_;
   /// The subdirectory name for our dir, or empty if it hasn't been set up.
-  string temp_dir_name_;
+  std::string temp_dir_name_;
 };
 
 #endif // NINJA_TEST_H_
diff --git a/src/util.cc b/src/util.cc
index 4df2bb2..c76f730 100644
--- a/src/util.cc
+++ b/src/util.cc
@@ -54,6 +54,8 @@
 #include "edit_distance.h"
 #include "metrics.h"
 
+using namespace std;
+
 void Fatal(const char* msg, ...) {
   va_list ap;
   fprintf(stderr, "ninja: fatal: ");
diff --git a/src/util.h b/src/util.h
index 6a4a7a9..4e6ebb8 100644
--- a/src/util.h
+++ b/src/util.h
@@ -23,7 +23,6 @@
 
 #include <string>
 #include <vector>
-using namespace std;
 
 #ifdef _MSC_VER
 #define NORETURN __declspec(noreturn)
@@ -57,29 +56,30 @@
 /// Canonicalize a path like "foo/../bar.h" into just "bar.h".
 /// |slash_bits| has bits set starting from lowest for a backslash that was
 /// normalized to a forward slash. (only used on Windows)
-bool CanonicalizePath(string* path, uint64_t* slash_bits, string* err);
+bool CanonicalizePath(std::string* path, uint64_t* slash_bits,
+                      std::string* err);
 bool CanonicalizePath(char* path, size_t* len, uint64_t* slash_bits,
-                      string* err);
+                      std::string* err);
 
 /// Appends |input| to |*result|, escaping according to the whims of either
 /// Bash, or Win32's CommandLineToArgvW().
 /// Appends the string directly to |result| without modification if we can
 /// determine that it contains no problematic characters.
-void GetShellEscapedString(const string& input, string* result);
-void GetWin32EscapedString(const string& input, string* result);
+void GetShellEscapedString(const std::string& input, std::string* result);
+void GetWin32EscapedString(const std::string& input, std::string* result);
 
 /// Read a file to a string (in text mode: with CRLF conversion
 /// on Windows).
 /// Returns -errno and fills in \a err on error.
-int ReadFile(const string& path, string* contents, string* err);
+int ReadFile(const std::string& path, std::string* contents, std::string* err);
 
 /// Mark a file descriptor to not be inherited on exec()s.
 void SetCloseOnExec(int fd);
 
 /// Given a misspelled string and a list of correct spellings, returns
 /// the closest match or NULL if there is no close enough match.
-const char* SpellcheckStringV(const string& text,
-                              const vector<const char*>& words);
+const char* SpellcheckStringV(const std::string& text,
+                              const std::vector<const char*>& words);
 
 /// Like SpellcheckStringV, but takes a NULL-terminated list.
 const char* SpellcheckString(const char* text, ...);
@@ -87,7 +87,7 @@
 bool islatinalpha(int c);
 
 /// Removes all Ansi escape codes (http://www.termsys.demon.co.uk/vtansi.htm).
-string StripAnsiEscapeCodes(const string& in);
+std::string StripAnsiEscapeCodes(const std::string& in);
 
 /// @return the number of processors on the machine.  Useful for an initial
 /// guess for how many jobs to run in parallel.  @return 0 on error.
@@ -99,10 +99,10 @@
 
 /// Elide the given string @a str with '...' in the middle if the length
 /// exceeds @a width.
-string ElideMiddle(const string& str, size_t width);
+std::string ElideMiddle(const std::string& str, size_t width);
 
 /// Truncates a file to the given size.
-bool Truncate(const string& path, size_t size, string* err);
+bool Truncate(const std::string& path, size_t size, std::string* err);
 
 #ifdef _MSC_VER
 #define snprintf _snprintf
@@ -116,7 +116,7 @@
 
 #ifdef _WIN32
 /// Convert the value returned by GetLastError() into a string.
-string GetLastErrorString();
+std::string GetLastErrorString();
 
 /// Calls Fatal() with a function name and GetLastErrorString.
 NORETURN void Win32Fatal(const char* function, const char* hint = NULL);
diff --git a/src/util_test.cc b/src/util_test.cc
index b43788d..1621c91 100644
--- a/src/util_test.cc
+++ b/src/util_test.cc
@@ -16,6 +16,8 @@
 
 #include "test.h"
 
+using namespace std;
+
 namespace {
 
 bool CanonicalizePath(string* path, string* err) {
diff --git a/src/version.cc b/src/version.cc
index 9d27e87..f25a30a 100644
--- a/src/version.cc
+++ b/src/version.cc
@@ -18,6 +18,8 @@
 
 #include "util.h"
 
+using namespace std;
+
 const char* kNinjaVersion = "1.10.1.git";
 
 void ParseVersion(const string& version, int* major, int* minor) {
diff --git a/src/version.h b/src/version.h
index bd6b9ff..9d84ecb 100644
--- a/src/version.h
+++ b/src/version.h
@@ -16,17 +16,16 @@
 #define NINJA_VERSION_H_
 
 #include <string>
-using namespace std;
 
 /// The version number of the current Ninja release.  This will always
 /// be "git" on trunk.
 extern const char* kNinjaVersion;
 
 /// Parse the major/minor components of a version string.
-void ParseVersion(const string& version, int* major, int* minor);
+void ParseVersion(const std::string& version, int* major, int* minor);
 
 /// Check whether \a version is compatible with the current Ninja version,
 /// aborting if not.
-void CheckNinjaVersion(const string& required_version);
+void CheckNinjaVersion(const std::string& required_version);
 
 #endif  // NINJA_VERSION_H_