Cleanup: Replace NULL with nullptr

At several places, NULL and nullptr were mixed. This commit cleans this up and switches NULL to nullptr where appropriate.

Closes #13168.

PiperOrigin-RevId: 362043567
diff --git a/src/main/cpp/archive_utils.cc b/src/main/cpp/archive_utils.cc
index ab6445f..b20b6cb 100644
--- a/src/main/cpp/archive_utils.cc
+++ b/src/main/cpp/archive_utils.cc
@@ -37,7 +37,7 @@
 
   // Scan the zip file "archive_path" until a file named "stop_entry" is seen,
   // then stop.
-  // If entry_names is not null, it receives a list of all file members
+  // If entry_names is not nullptr, it receives a list of all file members
   // up to and including "stop_entry".
   // If a callback is given, it is run with the name and contents of
   // each such member.
diff --git a/src/main/cpp/blaze.cc b/src/main/cpp/blaze.cc
index 41c4717..8470183 100644
--- a/src/main/cpp/blaze.cc
+++ b/src/main/cpp/blaze.cc
@@ -738,7 +738,7 @@
   FILE *fp = fopen(path.AsNativePath().c_str(), "r");
 #endif
 
-  if (fp == NULL) {
+  if (fp == nullptr) {
     BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
         << "opening " << path.AsPrintablePath()
         << " failed: " << GetLastErrorString();
@@ -1385,7 +1385,7 @@
   // environment variables to modify the current process, we may actually use
   // such map to configure a process from scratch (via interfaces like execvpe
   // or posix_spawn), so we need to inherit any untouched variables.
-  for (char **entry = environ; *entry != NULL; entry++) {
+  for (char **entry = environ; *entry != nullptr; entry++) {
     const std::string var_value = *entry;
     std::string::size_type equals = var_value.find('=');
     if (equals == std::string::npos) {
@@ -2089,7 +2089,7 @@
 
     // Execute the requested program, but before doing so, flush everything
     // we still have to say.
-    fflush(NULL);
+    fflush(nullptr);
     ExecuteRunRequest(blaze_util::Path(request.argv(0)), argv);
   }
 
diff --git a/src/main/cpp/blaze_util.cc b/src/main/cpp/blaze_util.cc
index d30c0d3..43dfc63 100644
--- a/src/main/cpp/blaze_util.cc
+++ b/src/main/cpp/blaze_util.cc
@@ -48,12 +48,12 @@
                            const char *next_arg,
                            const char *key) {
   const char *value = blaze_util::var_strprefix(arg, key);
-  if (value == NULL) {
-    return NULL;
+  if (value == nullptr) {
+    return nullptr;
   } else if (value[0] == '=') {
     return value + 1;
   } else if (value[0]) {
-    return NULL;  // trailing garbage in key name
+    return nullptr;  // trailing garbage in key name
   }
 
   return next_arg;
@@ -61,7 +61,7 @@
 
 bool GetNullaryOption(const char *arg, const char *key) {
   const char *value = blaze_util::var_strprefix(arg, key);
-  if (value == NULL) {
+  if (value == nullptr) {
     return false;
   } else if (value[0] == '=') {
     BAZEL_DIE(blaze_exit_code::BAD_ARGV)
@@ -77,7 +77,7 @@
 const char* SearchUnaryOption(const vector<string>& args,
                               const char *key, bool warn_if_dupe) {
   if (args.empty()) {
-    return NULL;
+    return nullptr;
   }
 
   const char* value = nullptr;
@@ -101,7 +101,7 @@
     const char* result = GetUnaryOption(args[i].c_str(),
                                         args[i + 1].c_str(),
                                         key);
-    if (result != NULL) {
+    if (result != nullptr) {
       // 'key' was found and 'result' has its value.
       if (value) {
         // 'key' was found once before, because 'value' is not empty.
@@ -121,7 +121,7 @@
       if (!found_dupe) {
         // We did not find a duplicate in the first N-1 arguments. Examine the
         // last argument, it may be a duplicate.
-        found_dupe = (GetUnaryOption(args[i].c_str(), NULL, key) != nullptr);
+        found_dupe = (GetUnaryOption(args[i].c_str(), nullptr, key) != nullptr);
       }
       if (found_dupe) {
         BAZEL_LOG(WARNING) << key << " is given more than once, "
@@ -133,7 +133,7 @@
     // 'value' is empty, so 'key' was not yet found in the first N-1 arguments.
     // If 'key' is in the last argument, we'll parse and return the value from
     // that, and if it isn't, we'll return NULL.
-    return GetUnaryOption(args[i].c_str(), NULL, key);
+    return GetUnaryOption(args[i].c_str(), nullptr, key);
   }
 }
 
diff --git a/src/main/cpp/blaze_util.h b/src/main/cpp/blaze_util.h
index ed358d1..ebf7a6d 100644
--- a/src/main/cpp/blaze_util.h
+++ b/src/main/cpp/blaze_util.h
@@ -49,7 +49,7 @@
 // When 'warn_if_dupe' is true, the method checks if 'key' is specified more
 // than once and prints a warning if so.
 // Returns the value of the 'key' flag iff it occurs in args.
-// Returns NULL otherwise.
+// Returns nullptr otherwise.
 const char* SearchUnaryOption(const std::vector<std::string>& args,
                               const char* key, bool warn_if_dupe);
 
diff --git a/src/main/cpp/blaze_util_bsd.cc b/src/main/cpp/blaze_util_bsd.cc
index 14f5456..a9b81df 100644
--- a/src/main/cpp/blaze_util_bsd.cc
+++ b/src/main/cpp/blaze_util_bsd.cc
@@ -63,10 +63,10 @@
 string GetOutputRoot() {
   char buf[2048];
   struct passwd pwbuf;
-  struct passwd *pw = NULL;
+  struct passwd *pw = nullptr;
   int uid = getuid();
   int r = getpwuid_r(uid, &pwbuf, buf, 2048, &pw);
-  if (r != -1 && pw != NULL) {
+  if (r != -1 && pw != nullptr) {
     return blaze_util::JoinPath(pw->pw_dir, ".cache/bazel");
   } else {
     return "/tmp";
diff --git a/src/main/cpp/blaze_util_darwin.cc b/src/main/cpp/blaze_util_darwin.cc
index 9179815..a45eb79 100644
--- a/src/main/cpp/blaze_util_darwin.cc
+++ b/src/main/cpp/blaze_util_darwin.cc
@@ -49,7 +49,7 @@
 using std::vector;
 
 // A stack based class for RAII type handling of CF based types that need
-// CFRelease called on them. Checks for NULL before calling release.
+// CFRelease called on them. Checks for nullptr before calling release.
 template <typename T> class CFScopedReleaser {
  public:
   explicit CFScopedReleaser(T value) : value_(value) { }
@@ -60,7 +60,7 @@
   }
   T get() { return value_; }
   operator T() { return value_; }
-  bool isValid() { return value_ != NULL; }
+  bool isValid() { return value_ != nullptr; }
 
  private:
   T value_;
@@ -105,8 +105,8 @@
       kCFAllocatorDefault,
       reinterpret_cast<const UInt8 *>(output_base.AsNativePath().c_str()),
       output_base.AsNativePath().length(), true));
-  CFBooleanRef cf_local = NULL;
-  CFErrorRef cf_error = NULL;
+  CFBooleanRef cf_local = nullptr;
+  CFErrorRef cf_error = nullptr;
   if (!cf_url.isValid() ||
       !CFURLCopyResourcePropertyForKey(cf_url, kCFURLVolumeIsLocalKey,
                                        &cf_local, &cf_error)) {
@@ -136,7 +136,7 @@
 
 uint64_t GetMillisecondsMonotonic() {
   struct timeval ts = {};
-  if (gettimeofday(&ts, NULL) < 0) {
+  if (gettimeofday(&ts, nullptr) < 0) {
     BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
         << "error calling gettimeofday: " << GetLastErrorString();
   }
@@ -178,14 +178,14 @@
 
   // java_home will print a warning if no JDK could be found
   FILE *output = popen("/usr/libexec/java_home -v 1.8+ 2> /dev/null", "r");
-  if (output == NULL) {
+  if (output == nullptr) {
     return "";
   }
 
   char buf[512];
   char *result = fgets(buf, sizeof(buf), output);
   pclose(output);
-  if (result == NULL) {
+  if (result == nullptr) {
     return "";
   }
 
@@ -225,7 +225,7 @@
                        << "' from backups";
     return;
   }
-  CFErrorRef cf_error = NULL;
+  CFErrorRef cf_error = nullptr;
   if (!CFURLSetResourcePropertyForKey(cf_url, kCFURLIsExcludedFromBackupKey,
                                       kCFBooleanTrue, &cf_error)) {
     CFScopedReleaser<CFErrorRef> cf_error_releaser(cf_error);
diff --git a/src/main/cpp/blaze_util_linux.cc b/src/main/cpp/blaze_util_linux.cc
index 6d131ba..2183d43 100644
--- a/src/main/cpp/blaze_util_linux.cc
+++ b/src/main/cpp/blaze_util_linux.cc
@@ -51,10 +51,10 @@
   } else {
     char buf[2048];
     struct passwd pwbuf;
-    struct passwd *pw = NULL;
+    struct passwd *pw = nullptr;
     int uid = getuid();
     int r = getpwuid_r(uid, &pwbuf, buf, 2048, &pw);
-    if (r != -1 && pw != NULL) {
+    if (r != -1 && pw != nullptr) {
       base = pw->pw_dir;
     }
   }
@@ -152,7 +152,7 @@
 
   // Resolve all symlinks.
   char resolved_path[PATH_MAX];
-  if (realpath(javac_dir.c_str(), resolved_path) == NULL) {
+  if (realpath(javac_dir.c_str(), resolved_path) == nullptr) {
     return "";
   }
   javac_dir = resolved_path;
diff --git a/src/main/cpp/blaze_util_posix.cc b/src/main/cpp/blaze_util_posix.cc
index c722b41..3ad443f 100644
--- a/src/main/cpp/blaze_util_posix.cc
+++ b/src/main/cpp/blaze_util_posix.cc
@@ -190,7 +190,7 @@
   // Unblock all signals.
   sigset_t sigset;
   sigemptyset(&sigset);
-  sigprocmask(SIG_SETMASK, &sigset, NULL);
+  sigprocmask(SIG_SETMASK, &sigset, nullptr);
 
   signal(SIGINT, handler);
   signal(SIGTERM, handler);
@@ -255,7 +255,7 @@
     for (; i < args.size(); i++) {
       charpp_[i] = strdup(args[i].c_str());
     }
-    charpp_[i] = NULL;
+    charpp_[i] = nullptr;
   }
 
   // Constructs a new CharPP from a list of environment variables.
@@ -279,12 +279,12 @@
           assert(false);
       }
     }
-    charpp_[i] = NULL;
+    charpp_[i] = nullptr;
   }
 
   // Deletes all memory held by the CharPP.
   ~CharPP() {
-    for (char** ptr = charpp_; *ptr != NULL; ptr++) {
+    for (char** ptr = charpp_; *ptr != nullptr; ptr++) {
       free(*ptr);
     }
     free(charpp_);
@@ -532,14 +532,12 @@
 
 string GetEnv(const string& name) {
   char* result = getenv(name.c_str());
-  return result != NULL ? string(result) : "";
+  return result != nullptr ? string(result) : "";
 }
 
 string GetPathEnv(const string& name) { return GetEnv(name); }
 
-bool ExistsEnv(const string& name) {
-  return getenv(name.c_str()) != NULL;
-}
+bool ExistsEnv(const string& name) { return getenv(name.c_str()) != nullptr; }
 
 void SetEnv(const string& name, const string& value) {
   setenv(name.c_str(), value.c_str(), 1);
@@ -558,8 +556,8 @@
   // output (when for example a query returns results as proto), in which case
   // we must not perform line buffering on the client side. So turn off
   // buffering here completely.
-  setvbuf(stdout, NULL, _IONBF, 0);
-  setvbuf(stderr, NULL, _IONBF, 0);
+  setvbuf(stdout, nullptr, _IONBF, 0);
+  setvbuf(stderr, nullptr, _IONBF, 0);
 
   // Ensure we have three open fds.  Otherwise we can end up with
   // bizarre things like stdout going to the lock file, etc.
@@ -736,7 +734,7 @@
   time_t seconds_part = (time_t)(milliseconds / 1000);
   long nanoseconds_part = ((long)(milliseconds % 1000)) * 1000 * 1000;
   struct timespec sleeptime = {seconds_part, nanoseconds_part};
-  nanosleep(&sleeptime, NULL);
+  nanosleep(&sleeptime, nullptr);
 }
 
 string GetUserName() {
@@ -746,7 +744,7 @@
   }
   errno = 0;
   passwd *pwent = getpwuid(getuid());  // NOLINT (single-threaded)
-  if (pwent == NULL || pwent->pw_name == NULL) {
+  if (pwent == nullptr || pwent->pw_name == nullptr) {
     BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
         << "$USER is not set, and unable to look up name of current user: "
         << GetLastErrorString();
diff --git a/src/main/cpp/blaze_util_windows.cc b/src/main/cpp/blaze_util_windows.cc
index c1194c4..7cd1881 100644
--- a/src/main/cpp/blaze_util_windows.cc
+++ b/src/main/cpp/blaze_util_windows.cc
@@ -89,7 +89,7 @@
   bool Finish(string* error) override;
 
  private:
-  WindowsDumper() : threadpool_(NULL), cleanup_group_(NULL) {}
+  WindowsDumper() : threadpool_(nullptr), cleanup_group_(nullptr) {}
 
   PTP_POOL threadpool_;
   PTP_CLEANUP_GROUP cleanup_group_;
@@ -135,8 +135,8 @@
 WindowsDumper* WindowsDumper::Create(string* error) {
   unique_ptr<WindowsDumper> result(new WindowsDumper());
 
-  result->threadpool_ = CreateThreadpool(NULL);
-  if (result->threadpool_ == NULL) {
+  result->threadpool_ = CreateThreadpool(nullptr);
+  if (result->threadpool_ == nullptr) {
     if (error) {
       string msg = GetLastErrorString();
       *error = "CreateThreadpool failed: " + msg;
@@ -145,7 +145,7 @@
   }
 
   result->cleanup_group_ = CreateThreadpoolCleanupGroup();
-  if (result->cleanup_group_ == NULL) {
+  if (result->cleanup_group_ == nullptr) {
     string msg = GetLastErrorString();
     CloseThreadpool(result->threadpool_);
     if (error) {
@@ -164,7 +164,7 @@
   InitializeThreadpoolEnvironment(&result->threadpool_env_);
   SetThreadpoolCallbackPool(&result->threadpool_env_, result->threadpool_);
   SetThreadpoolCallbackCleanupGroup(&result->threadpool_env_,
-                                    result->cleanup_group_, NULL);
+                                    result->cleanup_group_, nullptr);
 
   return result.release();  // release pointer ownership
 }
@@ -184,7 +184,7 @@
                                               &dir_cache_lock_, &dir_cache_,
                                               &error_lock_, &error_msg_));
   PTP_WORK w = CreateThreadpoolWork(WorkCallback, ctx.get(), &threadpool_env_);
-  if (w == NULL) {
+  if (w == nullptr) {
     string err = GetLastErrorString();
     err = string("WindowsDumper::Dump() couldn't submit work: ") + err;
 
@@ -197,14 +197,14 @@
 }
 
 bool WindowsDumper::Finish(string* error) {
-  if (threadpool_ == NULL) {
+  if (threadpool_ == nullptr) {
     return true;
   }
-  CloseThreadpoolCleanupGroupMembers(cleanup_group_, FALSE, NULL);
+  CloseThreadpoolCleanupGroupMembers(cleanup_group_, FALSE, nullptr);
   CloseThreadpoolCleanupGroup(cleanup_group_);
   CloseThreadpool(threadpool_);
-  threadpool_ = NULL;
-  cleanup_group_ = NULL;
+  threadpool_ = nullptr;
+  cleanup_group_ = nullptr;
 
   std::lock_guard<std::mutex> g(error_lock_);
   if (!error_msg_.empty() && error) {
@@ -429,8 +429,8 @@
   // is the same as %USERPROFILE%, but it does not require the envvar to be set.
   // On Windows 2016 Server, Nano server: FOLDERID_Profile is unknown but
   // %USERPROFILE% is set. See https://github.com/bazelbuild/bazel/issues/6701
-  if (SUCCEEDED(::SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT, NULL,
-                                       &wpath))) {
+  if (SUCCEEDED(::SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT,
+                                       nullptr, &wpath))) {
     string result = blaze_util::WstringToCstring(wpath);
     ::CoTaskMemFree(wpath);
     return result;
@@ -580,10 +580,10 @@
         /* dwCreationDisposition */
         daemon_out_append ? OPEN_ALWAYS : CREATE_ALWAYS,
         /* dwFlagsAndAttributes */ FILE_ATTRIBUTE_NORMAL,
-        /* hTemplateFile */ NULL);
+        /* hTemplateFile */ nullptr);
     if (handle != INVALID_HANDLE_VALUE) {
-      if (daemon_out_append
-          && !SetFilePointerEx(handle, {0}, NULL, FILE_END)) {
+      if (daemon_out_append &&
+          !SetFilePointerEx(handle, {0}, nullptr, FILE_END)) {
         fprintf(stderr, "Could not seek to end of file (%s)\n",
                 path.AsPrintablePath().c_str());
         return INVALID_HANDLE_VALUE;
@@ -633,11 +633,11 @@
                   const StartupOptions& options,
                   BlazeServerStartup** server_startup) {
   SECURITY_ATTRIBUTES inheritable_handle_sa = {sizeof(SECURITY_ATTRIBUTES),
-                                               NULL, TRUE};
+                                               nullptr, TRUE};
 
   AutoHandle devnull(::CreateFileW(
       L"NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE,
-      &inheritable_handle_sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
+      &inheritable_handle_sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
   if (!devnull.IsValid()) {
     std::string error = GetLastErrorString();
     BAZEL_DIE(blaze_exit_code::LOCAL_ENVIRONMENTAL_ERROR)
@@ -705,15 +705,15 @@
     WithEnvVars env_obj(env);
 
     ok = CreateProcessW(
-        /* lpApplicationName */ NULL,
+        /* lpApplicationName */ nullptr,
         /* lpCommandLine */ cmdline.cmdline,
-        /* lpProcessAttributes */ NULL,
-        /* lpThreadAttributes */ NULL,
+        /* lpProcessAttributes */ nullptr,
+        /* lpThreadAttributes */ nullptr,
         /* bInheritHandles */ TRUE,
         /* dwCreationFlags */ DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP |
             EXTENDED_STARTUPINFO_PRESENT,
-        /* lpEnvironment */ NULL,
-        /* lpCurrentDirectory */ NULL,
+        /* lpEnvironment */ nullptr,
+        /* lpCurrentDirectory */ nullptr,
         /* lpStartupInfo */ &startupInfoEx.StartupInfo,
         /* lpProcessInformation */ &processInfo);
   }
@@ -937,7 +937,7 @@
 }
 
 string GetEnv(const string& name) {
-  DWORD size = ::GetEnvironmentVariableA(name.c_str(), NULL, 0);
+  DWORD size = ::GetEnvironmentVariableA(name.c_str(), nullptr, 0);
   if (size == 0) {
     return string();  // unset or empty envvar
   }
@@ -966,7 +966,7 @@
 }
 
 bool ExistsEnv(const string& name) {
-  return ::GetEnvironmentVariableA(name.c_str(), NULL, 0) != 0;
+  return ::GetEnvironmentVariableA(name.c_str(), nullptr, 0) != 0;
 }
 
 void SetEnv(const string& name, const string& value) {
@@ -991,7 +991,7 @@
       "Try opening a console, such as the Windows Command Prompt (cmd.exe) "
       "or PowerShell, and running \"bazel help\".\n\n"
       "Press Enter to close this window...");
-  ReadFile(GetStdHandle(STD_INPUT_HANDLE), dummy, 1, dummy, NULL);
+  ReadFile(GetStdHandle(STD_INPUT_HANDLE), dummy, 1, dummy, nullptr);
   return true;
 }
 
@@ -1015,13 +1015,13 @@
                                      STD_ERROR_HANDLE};
   for (int i = 0; i <= 2; ++i) {
     HANDLE handle = ::GetStdHandle(stdhandles[i]);
-    if (handle == INVALID_HANDLE_VALUE || handle == NULL) {
+    if (handle == INVALID_HANDLE_VALUE || handle == nullptr) {
       // Ensure we have open fds to each std* stream. Otherwise we can end up
       // with bizarre things like stdout going to the lock file, etc.
       _open("NUL", (i == 0) ? _O_RDONLY : _O_WRONLY);
     }
     DWORD mode = 0;
-    if (i > 0 && handle != INVALID_HANDLE_VALUE && handle != NULL &&
+    if (i > 0 && handle != INVALID_HANDLE_VALUE && handle != nullptr &&
         ::GetConsoleMode(handle, &mode)) {
       DWORD newmode = mode | ENABLE_PROCESSED_OUTPUT |
                       ENABLE_WRAP_AT_EOL_OUTPUT |
@@ -1096,10 +1096,10 @@
         /* lpFileName */ lockfile.AsNativePath().c_str(),
         /* dwDesiredAccess */ GENERIC_READ | GENERIC_WRITE,
         /* dwShareMode */ FILE_SHARE_READ,
-        /* lpSecurityAttributes */ NULL,
+        /* lpSecurityAttributes */ nullptr,
         /* dwCreationDisposition */ CREATE_ALWAYS,
         /* dwFlagsAndAttributes */ FILE_ATTRIBUTE_NORMAL,
-        /* hTemplateFile */ NULL);
+        /* hTemplateFile */ nullptr);
     if (blaze_lock->handle != INVALID_HANDLE_VALUE) {
       // We could open the file, so noone else holds a lock on it.
       break;
diff --git a/src/main/cpp/option_processor.cc b/src/main/cpp/option_processor.cc
index dc3455f..421e6ef 100644
--- a/src/main/cpp/option_processor.cc
+++ b/src/main/cpp/option_processor.cc
@@ -625,7 +625,7 @@
 
 static std::vector<std::string> GetProcessedEnv() {
   std::vector<std::string> processed_env;
-  for (char** env = environ; *env != NULL; env++) {
+  for (char** env = environ; *env != nullptr; env++) {
     string env_str(*env);
     if (IsValidEnvName(*env)) {
       PreprocessEnvString(&env_str);
diff --git a/src/main/cpp/startup_options.cc b/src/main/cpp/startup_options.cc
index 8564ed3..1aaadc9 100644
--- a/src/main/cpp/startup_options.cc
+++ b/src/main/cpp/startup_options.cc
@@ -224,8 +224,8 @@
   // options begin with "--" or "-". Values are given together with the option
   // delimited by '=' or in the next option.
   const char* arg = argstr.c_str();
-  const char* next_arg = next_argstr.empty() ? NULL : next_argstr.c_str();
-  const char* value = NULL;
+  const char *next_arg = next_argstr.empty() ? nullptr : next_argstr.c_str();
+  const char *value = nullptr;
 
   bool is_nullary;
   if (!MaybeCheckValidNullary(argstr, &is_nullary, error)) {
@@ -267,42 +267,42 @@
     return blaze_exit_code::SUCCESS;
   }
 
-  if ((value = GetUnaryOption(arg, next_arg, "--output_base")) != NULL) {
+  if ((value = GetUnaryOption(arg, next_arg, "--output_base")) != nullptr) {
     output_base = blaze_util::Path(blaze::AbsolutePathFromFlag(value));
     option_sources["output_base"] = rcfile;
-  } else if ((value = GetUnaryOption(arg, next_arg,
-                                     "--install_base")) != NULL) {
+  } else if ((value = GetUnaryOption(arg, next_arg, "--install_base")) !=
+             nullptr) {
     install_base = blaze::AbsolutePathFromFlag(value);
     option_sources["install_base"] = rcfile;
-  } else if ((value = GetUnaryOption(arg, next_arg,
-                                     "--output_user_root")) != NULL) {
+  } else if ((value = GetUnaryOption(arg, next_arg, "--output_user_root")) !=
+             nullptr) {
     output_user_root = blaze::AbsolutePathFromFlag(value);
     option_sources["output_user_root"] = rcfile;
-  } else if ((value = GetUnaryOption(arg, next_arg,
-                                     "--server_jvm_out")) != NULL) {
+  } else if ((value = GetUnaryOption(arg, next_arg, "--server_jvm_out")) !=
+             nullptr) {
     server_jvm_out = blaze_util::Path(blaze::AbsolutePathFromFlag(value));
     option_sources["server_jvm_out"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--failure_detail_out")) !=
-             NULL) {
+             nullptr) {
     failure_detail_out = blaze_util::Path(blaze::AbsolutePathFromFlag(value));
     option_sources["failure_detail_out"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--host_jvm_profile")) !=
-             NULL) {
+             nullptr) {
     host_jvm_profile = value;
     option_sources["host_jvm_profile"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--server_javabase")) !=
-             NULL) {
+             nullptr) {
     // TODO(bazel-team): Consider examining the javabase and re-execing in case
     // of architecture mismatch.
     explicit_server_javabase_ =
         blaze_util::Path(blaze::AbsolutePathFromFlag(value));
     option_sources["server_javabase"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--host_jvm_args")) !=
-             NULL) {
+             nullptr) {
     host_jvm_args.push_back(value);
     option_sources["host_jvm_args"] = rcfile;  // NB: This is incorrect
   } else if ((value = GetUnaryOption(arg, next_arg, "--io_nice_level")) !=
-             NULL) {
+             nullptr) {
     if (!blaze_util::safe_strto32(value, &io_nice_level) ||
         io_nice_level > 7) {
       blaze_util::StringPrintf(error,
@@ -312,7 +312,7 @@
     }
     option_sources["io_nice_level"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--max_idle_secs")) !=
-             NULL) {
+             nullptr) {
     if (!blaze_util::safe_strto32(value, &max_idle_secs) ||
         max_idle_secs < 0) {
       blaze_util::StringPrintf(error,
@@ -321,7 +321,7 @@
     }
     option_sources["max_idle_secs"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--macos_qos_class")) !=
-             NULL) {
+             nullptr) {
     // We parse the value of this flag on all platforms even if it is
     // macOS-specific to ensure that rc files mentioning it are valid.
     if (strcmp(value, "user-interactive") == 0) {
@@ -351,7 +351,7 @@
     }
     option_sources["macos_qos_class"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg,
-                                     "--connect_timeout_secs")) != NULL) {
+                                     "--connect_timeout_secs")) != nullptr) {
     if (!blaze_util::safe_strto32(value, &connect_timeout_secs) ||
         connect_timeout_secs < 1 || connect_timeout_secs > 3600) {
       blaze_util::StringPrintf(
@@ -362,8 +362,8 @@
       return blaze_exit_code::BAD_ARGV;
     }
     option_sources["connect_timeout_secs"] = rcfile;
-  } else if ((value = GetUnaryOption(arg, next_arg,
-                                     "--local_startup_timeout_secs")) != NULL) {
+  } else if ((value = GetUnaryOption(
+                  arg, next_arg, "--local_startup_timeout_secs")) != nullptr) {
     if (!blaze_util::safe_strto32(value, &local_startup_timeout_secs) ||
         local_startup_timeout_secs < 1) {
       blaze_util::StringPrintf(
@@ -375,16 +375,16 @@
     }
     option_sources["local_startup_timeout_secs"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--digest_function")) !=
-             NULL) {
+             nullptr) {
     digest_function = value;
     option_sources["digest_function"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg,
                                      "--unix_digest_hash_attribute_name")) !=
-             NULL) {
+             nullptr) {
     unix_digest_hash_attribute_name = value;
     option_sources["unix_digest_hash_attribute_name"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--command_port")) !=
-             NULL) {
+             nullptr) {
     if (!blaze_util::safe_strto32(value, &command_port) ||
         command_port < 0 || command_port > 65535) {
       blaze_util::StringPrintf(error,
@@ -395,7 +395,7 @@
     }
     option_sources["command_port"] = rcfile;
   } else if ((value = GetUnaryOption(arg, next_arg, "--invocation_policy")) !=
-             NULL) {
+             nullptr) {
     if (!have_invocation_policy_) {
       have_invocation_policy_ = true;
       invocation_policy = value;
@@ -422,7 +422,7 @@
     }
   }
 
-  *is_space_separated = ((value == next_arg) && (value != NULL));
+  *is_space_separated = ((value == next_arg) && (value != nullptr));
   return blaze_exit_code::SUCCESS;
 }
 
diff --git a/src/main/cpp/util/errors_windows.cc b/src/main/cpp/util/errors_windows.cc
index b7e0148..a9a698c 100644
--- a/src/main/cpp/util/errors_windows.cc
+++ b/src/main/cpp/util/errors_windows.cc
@@ -37,8 +37,8 @@
   size_t size = FormatMessageA(
       FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM |
           FORMAT_MESSAGE_IGNORE_INSERTS,
-      NULL, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-      (LPSTR)&message_buffer, 0, NULL);
+      nullptr, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+      (LPSTR)&message_buffer, 0, nullptr);
 
   stringstream result;
   result << "(error: " << last_error << "): " << message_buffer;
diff --git a/src/main/cpp/util/file_posix.cc b/src/main/cpp/util/file_posix.cc
index e21e354..c184893 100644
--- a/src/main/cpp/util/file_posix.cc
+++ b/src/main/cpp/util/file_posix.cc
@@ -153,12 +153,12 @@
 
 static bool RemoveDirRecursively(const std::string &path) {
   DIR *dir;
-  if ((dir = opendir(path.c_str())) == NULL) {
+  if ((dir = opendir(path.c_str())) == nullptr) {
     return false;
   }
 
   struct dirent *ent;
-  while ((ent = readdir(dir)) != NULL) {
+  while ((ent = readdir(dir)) != nullptr) {
     if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {
       continue;
     }
@@ -354,8 +354,8 @@
 bool PathExists(const Path &path) { return PathExists(path.AsNativePath()); }
 
 string MakeCanonical(const char *path) {
-  char *resolved_path = realpath(path, NULL);
-  if (resolved_path == NULL) {
+  char *resolved_path = realpath(path, nullptr);
+  if (resolved_path == nullptr) {
     return "";
   } else {
     string ret = resolved_path;
@@ -476,10 +476,10 @@
 }
 
 time_t PosixFileMtime::GetNow() {
-  time_t result = time(NULL);
+  time_t result = time(nullptr);
   if (result == -1) {
     BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
-        << "time(NULL) failed: " << GetLastErrorString();
+        << "time(nullptr) failed: " << GetLastErrorString();
   }
   return result;
 }
@@ -506,7 +506,7 @@
 
 string GetCwd() {
   char cwdbuf[PATH_MAX];
-  if (getcwd(cwdbuf, sizeof cwdbuf) == NULL) {
+  if (getcwd(cwdbuf, sizeof cwdbuf) == nullptr) {
     BAZEL_DIE(blaze_exit_code::INTERNAL_ERROR)
         << "getcwd() failed: " << GetLastErrorString();
   }
@@ -522,12 +522,12 @@
   DIR *dir;
   struct dirent *ent;
 
-  if ((dir = opendir(path.c_str())) == NULL) {
+  if ((dir = opendir(path.c_str())) == nullptr) {
     // This is not a directory or it cannot be opened.
     return;
   }
 
-  while ((ent = readdir(dir)) != NULL) {
+  while ((ent = readdir(dir)) != nullptr) {
     if (!strcmp(ent->d_name, ".") || !strcmp(ent->d_name, "..")) {
       continue;
     }
@@ -551,7 +551,7 @@
       }
 
       consume->Consume(filename, is_directory);
-    }
+  }
 
     closedir(dir);
   }
diff --git a/src/main/cpp/util/file_windows.cc b/src/main/cpp/util/file_windows.cc
index 533ccfb..4570e9a 100644
--- a/src/main/cpp/util/file_windows.cc
+++ b/src/main/cpp/util/file_windows.cc
@@ -77,12 +77,13 @@
   bool Send(const void* buffer, int size) override {
     DWORD actually_written = 0;
     return ::WriteFile(_write_handle, buffer, size, &actually_written,
-                       NULL) == TRUE;
+                       nullptr) == TRUE;
   }
 
   int Receive(void* buffer, int size, int* error) override {
     DWORD actually_read = 0;
-    BOOL result = ::ReadFile(_read_handle, buffer, size, &actually_read, NULL);
+    BOOL result =
+        ::ReadFile(_read_handle, buffer, size, &actually_read, nullptr);
     if (error != nullptr) {
       // TODO(laszlocsomor): handle the error mode that is errno=EINTR on Linux.
       *error = result ? IPipe::SUCCESS : IPipe::OTHER_ERROR;
@@ -97,7 +98,7 @@
 
 IPipe* CreatePipe() {
   // The pipe HANDLEs can be inherited.
-  SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), NULL, TRUE};
+  SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES), nullptr, TRUE};
   HANDLE read_handle = INVALID_HANDLE_VALUE;
   HANDLE write_handle = INVALID_HANDLE_VALUE;
   if (!CreatePipe(&read_handle, &write_handle, &sa, 0)) {
@@ -144,13 +145,13 @@
       /* lpFileName */ path.AsNativePath().c_str(),
       /* dwDesiredAccess */ GENERIC_READ,
       /* dwShareMode */ FILE_SHARE_READ,
-      /* lpSecurityAttributes */ NULL,
+      /* lpSecurityAttributes */ nullptr,
       /* dwCreationDisposition */ OPEN_EXISTING,
       /* dwFlagsAndAttributes */
       // Per CreateFile's documentation on MSDN, opening directories requires
       // the FILE_FLAG_BACKUP_SEMANTICS flag.
       is_directory ? FILE_FLAG_BACKUP_SEMANTICS : FILE_ATTRIBUTE_NORMAL,
-      /* hTemplateFile */ NULL));
+      /* hTemplateFile */ nullptr));
 
   if (!handle.IsValid()) {
     return false;
@@ -187,20 +188,20 @@
       /* lpFileName */ path.AsNativePath().c_str(),
       /* dwDesiredAccess */ FILE_WRITE_ATTRIBUTES,
       /* dwShareMode */ FILE_SHARE_READ,
-      /* lpSecurityAttributes */ NULL,
+      /* lpSecurityAttributes */ nullptr,
       /* dwCreationDisposition */ OPEN_EXISTING,
       /* dwFlagsAndAttributes */
       IsDirectoryW(path.AsNativePath())
           ? (FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS)
           : FILE_ATTRIBUTE_NORMAL,
-      /* hTemplateFile */ NULL));
+      /* hTemplateFile */ nullptr));
   if (!handle.IsValid()) {
     return false;
   }
   return ::SetFileTime(
              /* hFile */ handle,
-             /* lpCreationTime */ NULL,
-             /* lpLastAccessTime */ NULL,
+             /* lpCreationTime */ nullptr,
+             /* lpLastAccessTime */ nullptr,
              /* lpLastWriteTime */ &time) == TRUE;
 }
 
@@ -233,17 +234,17 @@
       /* lpFileName */ path.AsNativePath().c_str(),
       /* dwDesiredAccess */ GENERIC_READ,
       /* dwShareMode */ kAllShare,
-      /* lpSecurityAttributes */ NULL,
+      /* lpSecurityAttributes */ nullptr,
       /* dwCreationDisposition */ OPEN_EXISTING,
       /* dwFlagsAndAttributes */ FILE_ATTRIBUTE_NORMAL,
-      /* hTemplateFile */ NULL);
+      /* hTemplateFile */ nullptr);
   return true;
 }
 
 int ReadFromHandle(file_handle_type handle, void* data, size_t size,
                    int* error) {
   DWORD actually_read = 0;
-  bool success = ::ReadFile(handle, data, size, &actually_read, NULL);
+  bool success = ::ReadFile(handle, data, size, &actually_read, nullptr);
   if (error != nullptr) {
     // TODO(laszlocsomor): handle the error cases that are errno=EINTR and
     // errno=EAGAIN on Linux.
@@ -322,17 +323,17 @@
       /* lpFileName */ path.AsNativePath().c_str(),
       /* dwDesiredAccess */ GENERIC_WRITE,
       /* dwShareMode */ FILE_SHARE_READ,
-      /* lpSecurityAttributes */ NULL,
+      /* lpSecurityAttributes */ nullptr,
       /* dwCreationDisposition */ CREATE_ALWAYS,
       /* dwFlagsAndAttributes */ FILE_ATTRIBUTE_NORMAL,
-      /* hTemplateFile */ NULL));
+      /* hTemplateFile */ nullptr));
   if (!handle.IsValid()) {
     return false;
   }
 
   // TODO(laszlocsomor): respect `perm` and set the file permissions accordingly
   DWORD actually_written = 0;
-  ::WriteFile(handle, data, size, &actually_written, NULL);
+  ::WriteFile(handle, data, size, &actually_written, nullptr);
   return actually_written == size;
 }
 
@@ -343,7 +344,7 @@
     return WriteResult::OTHER_ERROR;
   }
 
-  if (::WriteFile(h, data, size, &written, NULL)) {
+  if (::WriteFile(h, data, size, &written, nullptr)) {
     return (written == size) ? WriteResult::SUCCESS : WriteResult::OTHER_ERROR;
   } else {
     return (GetLastError() == ERROR_NO_DATA) ? WriteResult::BROKEN_PIPE
@@ -411,8 +412,8 @@
   // Attempt opening the path, which may be anything -- a file, a directory, a
   // symlink, even a dangling symlink is fine.
   // Follow reparse points, getting us that much closer to the real path.
-  AutoHandle h(CreateFileW(path, 0, kAllShare, NULL, OPEN_EXISTING,
-                           FILE_FLAG_BACKUP_SEMANTICS, NULL));
+  AutoHandle h(CreateFileW(path, 0, kAllShare, nullptr, OPEN_EXISTING,
+                           FILE_FLAG_BACKUP_SEMANTICS, nullptr));
   if (!h.IsValid()) {
     // Path does not exist or it's a dangling junction/symlink.
     return false;
@@ -495,8 +496,8 @@
 }
 
 static bool CanReadFileW(const wstring& path) {
-  AutoHandle handle(CreateFileW(path.c_str(), GENERIC_READ, kAllShare, NULL,
-                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL));
+  AutoHandle handle(CreateFileW(path.c_str(), GENERIC_READ, kAllShare, nullptr,
+                                OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr));
   return handle.IsValid();
 }
 
@@ -548,10 +549,10 @@
       /* lpFileName */ dummy_path.AsNativePath().c_str(),
       /* dwDesiredAccess */ GENERIC_WRITE | GENERIC_READ,
       /* dwShareMode */ kAllShare,
-      /* lpSecurityAttributes */ NULL,
+      /* lpSecurityAttributes */ nullptr,
       /* dwCreationDisposition */ OPEN_ALWAYS,
       /* dwFlagsAndAttributes */ FILE_ATTRIBUTE_NORMAL,
-      /* hTemplateFile */ NULL);
+      /* hTemplateFile */ nullptr);
   DWORD err = GetLastError();
   if (handle == INVALID_HANDLE_VALUE) {
     // We couldn't open the file, and not because the dummy file already exists.
@@ -573,8 +574,8 @@
   // Attempt opening the path, which may be anything -- a file, a directory, a
   // symlink, even a dangling symlink is fine.
   // Follow reparse points in order to return false for dangling ones.
-  AutoHandle h(CreateFileW(path.c_str(), 0, kAllShare, NULL, OPEN_EXISTING,
-                           FILE_FLAG_BACKUP_SEMANTICS, NULL));
+  AutoHandle h(CreateFileW(path.c_str(), 0, kAllShare, nullptr, OPEN_EXISTING,
+                           FILE_FLAG_BACKUP_SEMANTICS, nullptr));
   BY_HANDLE_FILE_INFORMATION info;
   return h.IsValid() && GetFileInformationByHandle(h, &info) &&
          info.dwFileAttributes != INVALID_FILE_ATTRIBUTES &&
@@ -620,7 +621,7 @@
         << ") could not find dirname: " << GetLastErrorString();
   }
   return MakeDirectoriesW(parent, mode) &&
-         ::CreateDirectoryW(abs_path.c_str(), NULL) == TRUE;
+         ::CreateDirectoryW(abs_path.c_str(), nullptr) == TRUE;
 }
 
 bool MakeDirectories(const string& path, unsigned int mode) {
diff --git a/src/main/cpp/util/path_posix.cc b/src/main/cpp/util/path_posix.cc
index f95dc36..c271b00 100644
--- a/src/main/cpp/util/path_posix.cc
+++ b/src/main/cpp/util/path_posix.cc
@@ -49,7 +49,7 @@
 }
 
 bool IsDevNull(const char *path) {
-  return path != NULL && *path != 0 && strncmp("/dev/null\0", path, 10) == 0;
+  return path != nullptr && *path != 0 && strncmp("/dev/null\0", path, 10) == 0;
 }
 
 bool IsRootDirectory(const std::string &path) {
diff --git a/src/main/cpp/util/path_windows.cc b/src/main/cpp/util/path_windows.cc
index cc4ff1b..47ada41 100644
--- a/src/main/cpp/util/path_windows.cc
+++ b/src/main/cpp/util/path_windows.cc
@@ -426,7 +426,7 @@
 }
 
 bool IsDevNull(const char* path) {
-  return path != NULL && *path != 0 &&
+  return path != nullptr && *path != 0 &&
          (strncmp("/dev/null\0", path, 10) == 0 ||
           ((path[0] == 'N' || path[0] == 'n') &&
            (path[1] == 'U' || path[1] == 'u') &&
@@ -434,7 +434,7 @@
 }
 
 bool IsDevNull(const wchar_t* path) {
-  return path != NULL && *path != 0 &&
+  return path != nullptr && *path != 0 &&
          (wcsncmp(L"/dev/null\0", path, 10) == 0 ||
           ((path[0] == L'N' || path[0] == L'n') &&
            (path[1] == L'U' || path[1] == L'u') &&
diff --git a/src/main/cpp/util/strings.cc b/src/main/cpp/util/strings.cc
index c797483..136fb05 100644
--- a/src/main/cpp/util/strings.cc
+++ b/src/main/cpp/util/strings.cc
@@ -316,7 +316,7 @@
   }
 
   // The output buffer was too small. Get required buffer size.
-  res = Convert(use_utf8, input, NULL, 0);
+  res = Convert(use_utf8, input, nullptr, 0);
   if (res > 0) {
     buf_size = res;
     buf.reset(new V[buf_size]);
@@ -335,7 +335,7 @@
 static int ConvertWcsToMbs(const bool use_utf8, const std::wstring &input,
                            char *output, const size_t output_size) {
   return WideCharToMultiByte(use_utf8 ? CP_UTF8 : CP_ACP, 0, input.c_str(), -1,
-                             output, output_size, NULL, NULL);
+                             output, output_size, nullptr, nullptr);
 }
 
 static int ConvertMbsToWcs(const bool /* unused */, const std::string &input,
diff --git a/src/main/cpp/util/strings.h b/src/main/cpp/util/strings.h
index 3b89016..a9557f8 100644
--- a/src/main/cpp/util/strings.h
+++ b/src/main/cpp/util/strings.h
@@ -55,30 +55,30 @@
 bool ends_with(const std::wstring &haystack, const std::wstring &needle);
 
 // Matches a prefix (which must be a char* literal!) against the beginning of
-// str. Returns a pointer past the prefix, or NULL if the prefix wasn't matched.
-// (Like the standard strcasecmp(), but for efficiency doesn't call strlen() on
-// prefix, and returns a pointer rather than an int.)
+// str. Returns a pointer past the prefix, or nullptr if the prefix wasn't
+// matched. (Like the standard strcasecmp(), but for efficiency doesn't call
+// strlen() on prefix, and returns a pointer rather than an int.)
 //
 // The ""'s catch people who don't pass in a literal for "prefix"
 #ifndef strprefix
 #define strprefix(str, prefix)                         \
   (strncmp(str, prefix, sizeof("" prefix "") - 1) == 0 \
        ? str + sizeof(prefix) - 1                      \
-       : NULL)
+       : nullptr)
 #endif
 
-// Matches a prefix; returns a pointer past the prefix, or NULL if not found.
+// Matches a prefix; returns a pointer past the prefix, or nullptr if not found.
 // (Like strprefix() and strcaseprefix() but not restricted to searching for
 // char* literals). Templated so searching a const char* returns a const char*,
 // and searching a non-const char* returns a non-const char*.
-// Matches a prefix; returns a pointer past the prefix, or NULL if not found.
+// Matches a prefix; returns a pointer past the prefix, or nullptr if not found.
 // (Like strprefix() and strcaseprefix() but not restricted to searching for
 // char* literals). Templated so searching a const char* returns a const char*,
 // and searching a non-const char* returns a non-const char*.
 template <class CharStar>
 inline CharStar var_strprefix(CharStar str, const char *prefix) {
   const int len = strlen(prefix);
-  return strncmp(str, prefix, len) == 0 ? str + len : NULL;
+  return strncmp(str, prefix, len) == 0 ? str + len : nullptr;
 }
 
 // Join the elements of pieces separated by delimeter.  Returns the joined