Zhangyi Chen 6 éve
szülő
commit
1e2d716f5e
81 módosított fájl, 7 hozzáadás és 12026 törlés
  1. 5 0
      .gitignore
  2. 0 25
      Makefile
  3. 0 55
      src/butil/base_paths.h
  4. 0 25
      src/butil/base_paths_android.h
  5. 0 24
      src/butil/base_paths_mac.h
  6. 0 114
      src/butil/base_paths_mac.mm
  7. 0 116
      src/butil/base_paths_posix.cc
  8. 0 27
      src/butil/base_paths_posix.h
  9. 0 442
      src/butil/command_line.cc
  10. 0 194
      src/butil/command_line.h
  11. 0 1
      src/butil/file_util_posix.cc
  12. 0 1
      src/butil/logging.cc
  13. 0 325
      src/butil/memory/shared_memory.h
  14. 0 479
      src/butil/memory/shared_memory_posix.cc
  15. 0 341
      src/butil/path_service.cc
  16. 0 92
      src/butil/path_service.h
  17. 0 189
      src/butil/process/internal_linux.cc
  18. 0 90
      src/butil/process/internal_linux.h
  19. 0 26
      src/butil/process/kill.cc
  20. 0 162
      src/butil/process/kill.h
  21. 0 172
      src/butil/process/kill_mac.cc
  22. 0 482
      src/butil/process/kill_posix.cc
  23. 0 52
      src/butil/process/launch.cc
  24. 0 275
      src/butil/process/launch.h
  25. 0 48
      src/butil/process/launch_mac.cc
  26. 0 665
      src/butil/process/launch_posix.cc
  27. 0 30
      src/butil/process/memory.cc
  28. 0 82
      src/butil/process/memory.h
  29. 0 213
      src/butil/process/memory_linux.cc
  30. 0 751
      src/butil/process/memory_mac.mm
  31. 0 19
      src/butil/process/memory_stubs.cc
  32. 0 70
      src/butil/process/process.h
  33. 0 94
      src/butil/process/process_handle.h
  34. 0 40
      src/butil/process/process_handle_freebsd.cc
  35. 0 30
      src/butil/process/process_handle_linux.cc
  36. 0 36
      src/butil/process/process_handle_mac.cc
  37. 0 49
      src/butil/process/process_handle_openbsd.cc
  38. 0 49
      src/butil/process/process_handle_posix.cc
  39. 0 25
      src/butil/process/process_info.h
  40. 0 27
      src/butil/process/process_info_linux.cc
  41. 0 31
      src/butil/process/process_info_mac.cc
  42. 0 65
      src/butil/process/process_iterator.cc
  43. 0 185
      src/butil/process/process_iterator.h
  44. 0 126
      src/butil/process/process_iterator_freebsd.cc
  45. 0 137
      src/butil/process/process_iterator_linux.cc
  46. 0 135
      src/butil/process/process_iterator_mac.cc
  47. 0 128
      src/butil/process/process_iterator_openbsd.cc
  48. 0 141
      src/butil/process/process_linux.cc
  49. 0 45
      src/butil/process/process_metrics.cc
  50. 0 379
      src/butil/process/process_metrics.h
  51. 0 122
      src/butil/process/process_metrics_freebsd.cc
  52. 0 812
      src/butil/process/process_metrics_linux.cc
  53. 0 365
      src/butil/process/process_metrics_mac.cc
  54. 0 161
      src/butil/process/process_metrics_openbsd.cc
  55. 0 72
      src/butil/process/process_metrics_posix.cc
  56. 0 73
      src/butil/process/process_posix.cc
  57. 0 56
      src/butil/sys_info.cc
  58. 0 141
      src/butil/sys_info.h
  59. 0 36
      src/butil/sys_info_freebsd.cc
  60. 0 34
      src/butil/sys_info_internal.h
  61. 0 100
      src/butil/sys_info_linux.cc
  62. 0 88
      src/butil/sys_info_mac.cc
  63. 0 75
      src/butil/sys_info_openbsd.cc
  64. 0 133
      src/butil/sys_info_posix.cc
  65. 0 4
      test/Makefile
  66. 0 11
      test/butil_unittest_main.cpp
  67. 0 364
      test/command_line_unittest.cc
  68. 2 0
      test/endpoint_unittest.cpp
  69. 0 2
      test/file_util_unittest.cc
  70. 0 57
      test/multiprocess_func_list.cc
  71. 0 59
      test/multiprocess_test.cc
  72. 0 131
      test/multiprocess_test.h
  73. 0 250
      test/path_service_unittest.cc
  74. 0 368
      test/process_metrics_unittest.cc
  75. 0 883
      test/process_util_unittest.cc
  76. 0 1
      test/singleton_unittest.cc
  77. 0 28
      test/stack_trace_unittest.cc
  78. 0 23
      test/test_file_util.cc
  79. 0 91
      test/test_file_util.h
  80. 0 111
      test/test_timeouts.cc
  81. 0 66
      test/test_timeouts.h

+ 5 - 0
.gitignore

@@ -9,9 +9,14 @@
 *.pb.cc
 *.pb.h
 *.prof
+*.so
 /output
 /test/output
 
 #ignore hidden files
 .*
 *.swp
+
+#ignore auto-generated files
+config.mk
+src/butil/config.h

+ 0 - 25
Makefile

@@ -52,15 +52,12 @@ BUTIL_SOURCES = \
     src/butil/at_exit.cc \
     src/butil/atomicops_internals_x86_gcc.cc \
     src/butil/barrier_closure.cc \
-    src/butil/base_paths.cc \
-    src/butil/base_paths_posix.cc \
     src/butil/base64.cc \
     src/butil/base_switches.cc \
     src/butil/big_endian.cc \
     src/butil/bind_helpers.cc \
     src/butil/callback_helpers.cc \
     src/butil/callback_internal.cc \
-    src/butil/command_line.cc \
     src/butil/cpu.cc \
     src/butil/debug/alias.cc \
     src/butil/debug/asan_invalid_access.cc \
@@ -94,29 +91,10 @@ BUTIL_SOURCES = \
     src/butil/memory/aligned_memory.cc \
     src/butil/memory/ref_counted.cc \
     src/butil/memory/ref_counted_memory.cc \
-    src/butil/memory/shared_memory_posix.cc \
     src/butil/memory/singleton.cc \
     src/butil/memory/weak_ptr.cc \
-    src/butil/nix/mime_util_xdg.cc \
-    src/butil/nix/xdg_util.cc \
-    src/butil/path_service.cc \
     src/butil/posix/file_descriptor_shuffle.cc \
     src/butil/posix/global_descriptors.cc \
-    src/butil/process/internal_linux.cc \
-    src/butil/process/kill.cc \
-    src/butil/process/kill_posix.cc \
-    src/butil/process/launch.cc \
-    src/butil/process/launch_posix.cc \
-    src/butil/process/process_handle_linux.cc \
-    src/butil/process/process_handle_posix.cc \
-    src/butil/process/process_info_linux.cc \
-    src/butil/process/process_iterator.cc \
-    src/butil/process/process_iterator_linux.cc \
-    src/butil/process/process_linux.cc \
-    src/butil/process/process_metrics.cc \
-    src/butil/process/process_metrics_linux.cc \
-    src/butil/process/process_metrics_posix.cc \
-    src/butil/process/process_posix.cc \
     src/butil/rand_util.cc \
     src/butil/rand_util_posix.cc \
     src/butil/fast_rand.cpp \
@@ -139,9 +117,6 @@ BUTIL_SOURCES = \
     src/butil/synchronization/cancellation_flag.cc \
     src/butil/synchronization/condition_variable_posix.cc \
     src/butil/synchronization/waitable_event_posix.cc \
-    src/butil/sys_info.cc \
-    src/butil/sys_info_linux.cc \
-    src/butil/sys_info_posix.cc \
     src/butil/threading/non_thread_safe_impl.cc \
     src/butil/threading/platform_thread_linux.cc \
     src/butil/threading/platform_thread_posix.cc \

+ 0 - 55
src/butil/base_paths.h

@@ -1,55 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_BASE_PATHS_H_
-#define BASE_BASE_PATHS_H_
-
-// This file declares path keys for the base module.  These can be used with
-// the PathService to access various special directories and files.
-
-#include "butil/build_config.h"
-
-#if defined(OS_WIN)
-#include "butil/base_paths_win.h"
-#elif defined(OS_MACOSX)
-#include "butil/base_paths_mac.h"
-#elif defined(OS_ANDROID)
-#include "butil/base_paths_android.h"
-#endif
-
-#if defined(OS_POSIX)
-#include "butil/base_paths_posix.h"
-#endif
-
-namespace butil {
-
-enum BasePathKey {
-  PATH_START = 0,
-
-  DIR_CURRENT,       // Current directory.
-  DIR_EXE,           // Directory containing FILE_EXE.
-  DIR_MODULE,        // Directory containing FILE_MODULE.
-  DIR_TEMP,          // Temporary directory.
-  DIR_HOME,          // User's root home directory. On Windows this will look
-                     // like "C:\Users\you" (or on XP
-                     // "C:\Document and Settings\you") which isn't necessarily
-                     // a great place to put files.
-  FILE_EXE,          // Path and filename of the current executable.
-  FILE_MODULE,       // Path and filename of the module containing the code for
-                     // the PathService (which could differ from FILE_EXE if the
-                     // PathService were compiled into a shared object, for
-                     // example).
-  DIR_SOURCE_ROOT,   // Returns the root of the source tree. This key is useful
-                     // for tests that need to locate various resources. It
-                     // should not be used outside of test code.
-  DIR_USER_DESKTOP,  // The current user's Desktop.
-
-  DIR_TEST_DATA,     // Used only for testing.
-
-  PATH_END
-};
-
-}  // namespace butil
-
-#endif  // BASE_BASE_PATHS_H_

+ 0 - 25
src/butil/base_paths_android.h

@@ -1,25 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_BASE_PATHS_ANDROID_H_
-#define BASE_BASE_PATHS_ANDROID_H_
-
-// This file declares Android-specific path keys for the base module.
-// These can be used with the PathService to access various special
-// directories and files.
-
-namespace butil {
-
-enum {
-  PATH_ANDROID_START = 300,
-
-  DIR_ANDROID_APP_DATA,  // Directory where to put Android app's data.
-  DIR_ANDROID_EXTERNAL_STORAGE,  // Android external storage directory.
-
-  PATH_ANDROID_END
-};
-
-}  // namespace butil
-
-#endif  // BASE_BASE_PATHS_ANDROID_H_

+ 0 - 24
src/butil/base_paths_mac.h

@@ -1,24 +0,0 @@
-// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_BASE_PATHS_MAC_H_
-#define BASE_BASE_PATHS_MAC_H_
-
-// This file declares Mac-specific path keys for the base module.
-// These can be used with the PathService to access various special
-// directories and files.
-
-namespace butil {
-
-enum {
-  PATH_MAC_START = 200,
-
-  DIR_APP_DATA,  // ~/Library/Application Support
-
-  PATH_MAC_END
-};
-
-}  // namespace butil
-
-#endif  // BASE_BASE_PATHS_MAC_H_

+ 0 - 114
src/butil/base_paths_mac.mm

@@ -1,114 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Defines base::PathProviderMac which replaces base::PathProviderPosix for Mac
-// in base/path_service.cc.
-
-#include <dlfcn.h>
-#import <Foundation/Foundation.h>
-#include <mach-o/dyld.h>
-
-#include "base/base_paths.h"
-#include "base/compiler_specific.h"
-#include "base/file_util.h"
-#include "base/files/file_path.h"
-#include "base/logging.h"
-#include "base/mac/foundation_util.h"
-#include "base/path_service.h"
-#include "base/strings/string_util.h"
-#include "base/build_config.h"
-
-namespace {
-
-void GetNSExecutablePath(base::FilePath* path) {
-  DCHECK(path);
-  // Executable path can have relative references ("..") depending on
-  // how the app was launched.
-  uint32_t executable_length = 0;
-  _NSGetExecutablePath(NULL, &executable_length);
-  DCHECK_GT(executable_length, 1u);
-  std::string executable_path;
-  int rv = _NSGetExecutablePath(WriteInto(&executable_path, executable_length),
-                                &executable_length);
-  DCHECK_EQ(rv, 0);
-
-  // _NSGetExecutablePath may return paths containing ./ or ../ which makes
-  // FilePath::DirName() work incorrectly, convert it to absolute path so that
-  // paths such as DIR_SOURCE_ROOT can work, since we expect absolute paths to
-  // be returned here.
-  *path = base::MakeAbsoluteFilePath(base::FilePath(executable_path));
-}
-
-// Returns true if the module for |address| is found. |path| will contain
-// the path to the module. Note that |path| may not be absolute.
-bool GetModulePathForAddress(base::FilePath* path,
-                             const void* address) WARN_UNUSED_RESULT;
-
-bool GetModulePathForAddress(base::FilePath* path, const void* address) {
-  Dl_info info;
-  if (dladdr(address, &info) == 0)
-    return false;
-  *path = base::FilePath(info.dli_fname);
-  return true;
-}
-
-}  // namespace
-
-namespace base {
-
-bool PathProviderMac(int key, base::FilePath* result) {
-  switch (key) {
-    case base::FILE_EXE:
-      GetNSExecutablePath(result);
-      return true;
-    case base::FILE_MODULE:
-      return GetModulePathForAddress(result,
-          reinterpret_cast<const void*>(&base::PathProviderMac));
-    case base::DIR_APP_DATA: {
-      bool success = base::mac::GetUserDirectory(NSApplicationSupportDirectory,
-                                                 result);
-#if defined(OS_IOS)
-      // On IOS, this directory does not exist unless it is created explicitly.
-      if (success && !base::PathExists(*result))
-        success = base::CreateDirectory(*result);
-#endif  // defined(OS_IOS)
-      return success;
-    }
-    case base::DIR_SOURCE_ROOT:
-      // Go through PathService to catch overrides.
-      if (!PathService::Get(base::FILE_EXE, result))
-        return false;
-
-      // Start with the executable's directory.
-      *result = result->DirName();
-
-#if !defined(OS_IOS)
-      if (base::mac::AmIBundled()) {
-        // The bundled app executables (Chromium, TestShell, etc) live five
-        // levels down, eg:
-        // src/xcodebuild/{Debug|Release}/Chromium.app/Contents/MacOS/Chromium
-        *result = result->DirName().DirName().DirName().DirName().DirName();
-      } else {
-        // Unit tests execute two levels deep from the source root, eg:
-        // src/xcodebuild/{Debug|Release}/base_unittests
-        *result = result->DirName().DirName();
-      }
-#endif
-      return true;
-    case base::DIR_USER_DESKTOP:
-#if defined(OS_IOS)
-      // iOS does not have desktop directories.
-      NOTIMPLEMENTED();
-      return false;
-#else
-      return base::mac::GetUserDirectory(NSDesktopDirectory, result);
-#endif
-    case base::DIR_CACHE:
-      return base::mac::GetUserDirectory(NSCachesDirectory, result);
-    default:
-      return false;
-  }
-}
-
-}  // namespace base

+ 0 - 116
src/butil/base_paths_posix.cc

@@ -1,116 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// Defines butil::PathProviderPosix, default path provider on POSIX OSes that
-// don't have their own base_paths_OS.cc implementation (i.e. all but Mac and
-// Android).
-
-#include <ostream>
-#include <string>
-
-#include "butil/base_paths.h"
-#include "butil/environment.h"
-#include "butil/file_util.h"
-#include "butil/files/file_path.h"
-#include "butil/logging.h"
-#include "butil/memory/scoped_ptr.h"
-#include "butil/nix/xdg_util.h"
-#include "butil/path_service.h"
-#include "butil/process/process_metrics.h"
-#include "butil/build_config.h"
-
-#if defined(OS_FREEBSD)
-#include <sys/param.h>
-#include <sys/sysctl.h>
-#elif defined(OS_SOLARIS)
-#include <stdlib.h>
-#endif
-
-namespace butil {
-
-bool PathProviderPosix(int key, FilePath* result) {
-  FilePath path;
-  switch (key) {
-    case butil::FILE_EXE:
-    case butil::FILE_MODULE: {  // TODO(evanm): is this correct?
-#if defined(OS_LINUX)
-      FilePath bin_dir;
-      if (!ReadSymbolicLink(FilePath(kProcSelfExe), &bin_dir)) {
-        NOTREACHED() << "Unable to resolve " << kProcSelfExe << ".";
-        return false;
-      }
-      *result = bin_dir;
-      return true;
-#elif defined(OS_FREEBSD)
-      int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1 };
-      char bin_dir[PATH_MAX + 1];
-      size_t length = sizeof(bin_dir);
-      // Upon return, |length| is the number of bytes written to |bin_dir|
-      // including the string terminator.
-      int error = sysctl(name, 4, bin_dir, &length, NULL, 0);
-      if (error < 0 || length <= 1) {
-        NOTREACHED() << "Unable to resolve path.";
-        return false;
-      }
-      *result = FilePath(FilePath::StringType(bin_dir, length - 1));
-      return true;
-#elif defined(OS_SOLARIS)
-      char bin_dir[PATH_MAX + 1];
-      if (realpath(getexecname(), bin_dir) == NULL) {
-        NOTREACHED() << "Unable to resolve " << getexecname() << ".";
-        return false;
-      }
-      *result = FilePath(bin_dir);
-      return true;
-#elif defined(OS_OPENBSD)
-      // There is currently no way to get the executable path on OpenBSD
-      char* cpath;
-      if ((cpath = getenv("CHROME_EXE_PATH")) != NULL)
-        *result = FilePath(cpath);
-      else
-        *result = FilePath("/usr/local/chrome/chrome");
-      return true;
-#endif
-    }
-    case butil::DIR_SOURCE_ROOT: {
-      // Allow passing this in the environment, for more flexibility in build
-      // tree configurations (sub-project builds, gyp --output_dir, etc.)
-      scoped_ptr<butil::Environment> env(butil::Environment::Create());
-      std::string cr_source_root;
-      if (env->GetVar("CR_SOURCE_ROOT", &cr_source_root)) {
-        path = FilePath(cr_source_root);
-        if (butil::PathExists(path)) {
-          *result = path;
-          return true;
-        } else {
-          DLOG(WARNING) << "CR_SOURCE_ROOT is set, but it appears to not "
-                        << "point to a directory.";
-        }
-      }
-      // On POSIX, unit tests execute two levels deep from the source root.
-      // For example:  out/{Debug|Release}/net_unittest
-      if (PathService::Get(butil::DIR_EXE, &path)) {
-        *result = path.DirName().DirName();
-        return true;
-      }
-
-      DLOG(ERROR) << "Couldn't find your source root.  "
-                  << "Try running from your chromium/src directory.";
-      return false;
-    }
-    case butil::DIR_USER_DESKTOP:
-      *result = butil::nix::GetXDGUserDirectory("DESKTOP", "Desktop");
-      return true;
-    case butil::DIR_CACHE: {
-      scoped_ptr<butil::Environment> env(butil::Environment::Create());
-      FilePath cache_dir(butil::nix::GetXDGDirectory(env.get(), "XDG_CACHE_HOME",
-                                                    ".cache"));
-      *result = cache_dir;
-      return true;
-    }
-  }
-  return false;
-}
-
-}  // namespace butil

+ 0 - 27
src/butil/base_paths_posix.h

@@ -1,27 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_BASE_PATHS_POSIX_H_
-#define BASE_BASE_PATHS_POSIX_H_
-
-// This file declares windows-specific path keys for the base module.
-// These can be used with the PathService to access various special
-// directories and files.
-
-namespace butil {
-
-enum {
-  PATH_POSIX_START = 400,
-
-  DIR_CACHE,    // Directory where to put cache data.  Note this is
-                // *not* where the browser cache lives, but the
-                // browser cache can be a subdirectory.
-                // This is $XDG_CACHE_HOME on Linux and
-                // ~/Library/Caches on Mac.
-  PATH_POSIX_END
-};
-
-}  // namespace butil
-
-#endif  // BASE_BASE_PATHS_POSIX_H_

+ 0 - 442
src/butil/command_line.cc

@@ -1,442 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/command_line.h"
-
-#include <algorithm>
-#include <ostream>
-
-#include "butil/basictypes.h"
-#include "butil/files/file_path.h"
-#include "butil/logging.h"
-#include "butil/strings/string_split.h"
-#include "butil/strings/string_util.h"
-#include "butil/strings/utf_string_conversions.h"
-#include "butil/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#include <shellapi.h>
-#endif
-
-namespace butil {
-
-CommandLine* CommandLine::current_process_commandline_ = NULL;
-
-namespace {
-
-const CommandLine::CharType kSwitchTerminator[] = FILE_PATH_LITERAL("--");
-const CommandLine::CharType kSwitchValueSeparator[] = FILE_PATH_LITERAL("=");
-
-// Since we use a lazy match, make sure that longer versions (like "--") are
-// listed before shorter versions (like "-") of similar prefixes.
-#if defined(OS_WIN)
-// By putting slash last, we can control whether it is treaded as a switch
-// value by changing the value of switch_prefix_count to be one less than
-// the array size.
-const CommandLine::CharType* const kSwitchPrefixes[] = {L"--", L"-", L"/"};
-#elif defined(OS_POSIX)
-// Unixes don't use slash as a switch.
-const CommandLine::CharType* const kSwitchPrefixes[] = {"--", "-"};
-#endif
-size_t switch_prefix_count = arraysize(kSwitchPrefixes);
-
-size_t GetSwitchPrefixLength(const CommandLine::StringType& string) {
-  for (size_t i = 0; i < switch_prefix_count; ++i) {
-    CommandLine::StringType prefix(kSwitchPrefixes[i]);
-    if (string.compare(0, prefix.length(), prefix) == 0)
-      return prefix.length();
-  }
-  return 0;
-}
-
-// Fills in |switch_string| and |switch_value| if |string| is a switch.
-// This will preserve the input switch prefix in the output |switch_string|.
-bool IsSwitch(const CommandLine::StringType& string,
-              CommandLine::StringType* switch_string,
-              CommandLine::StringType* switch_value) {
-  switch_string->clear();
-  switch_value->clear();
-  size_t prefix_length = GetSwitchPrefixLength(string);
-  if (prefix_length == 0 || prefix_length == string.length())
-    return false;
-
-  const size_t equals_position = string.find(kSwitchValueSeparator);
-  *switch_string = string.substr(0, equals_position);
-  if (equals_position != CommandLine::StringType::npos)
-    *switch_value = string.substr(equals_position + 1);
-  return true;
-}
-
-// Append switches and arguments, keeping switches before arguments.
-void AppendSwitchesAndArguments(CommandLine& command_line,
-                                const CommandLine::StringVector& argv) {
-  bool parse_switches = true;
-  for (size_t i = 1; i < argv.size(); ++i) {
-    CommandLine::StringType arg = argv[i];
-    TrimWhitespace(arg, TRIM_ALL, &arg);
-
-    CommandLine::StringType switch_string;
-    CommandLine::StringType switch_value;
-    parse_switches &= (arg != kSwitchTerminator);
-    if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
-#if defined(OS_WIN)
-      command_line.AppendSwitchNative(UTF16ToASCII(switch_string),
-                                      switch_value);
-#elif defined(OS_POSIX)
-      command_line.AppendSwitchNative(switch_string, switch_value);
-#endif
-    } else {
-      command_line.AppendArgNative(arg);
-    }
-  }
-}
-
-// Lowercase switches for backwards compatiblity *on Windows*.
-std::string LowerASCIIOnWindows(const std::string& string) {
-#if defined(OS_WIN)
-  return StringToLowerASCII(string);
-#elif defined(OS_POSIX)
-  return string;
-#endif
-}
-
-
-#if defined(OS_WIN)
-// Quote a string as necessary for CommandLineToArgvW compatiblity *on Windows*.
-std::wstring QuoteForCommandLineToArgvW(const std::wstring& arg) {
-  // We follow the quoting rules of CommandLineToArgvW.
-  // http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
-  if (arg.find_first_of(L" \\\"") == std::wstring::npos) {
-    // No quoting necessary.
-    return arg;
-  }
-
-  std::wstring out;
-  out.push_back(L'"');
-  for (size_t i = 0; i < arg.size(); ++i) {
-    if (arg[i] == '\\') {
-      // Find the extent of this run of backslashes.
-      size_t start = i, end = start + 1;
-      for (; end < arg.size() && arg[end] == '\\'; ++end)
-        /* empty */;
-      size_t backslash_count = end - start;
-
-      // Backslashes are escapes only if the run is followed by a double quote.
-      // Since we also will end the string with a double quote, we escape for
-      // either a double quote or the end of the string.
-      if (end == arg.size() || arg[end] == '"') {
-        // To quote, we need to output 2x as many backslashes.
-        backslash_count *= 2;
-      }
-      for (size_t j = 0; j < backslash_count; ++j)
-        out.push_back('\\');
-
-      // Advance i to one before the end to balance i++ in loop.
-      i = end - 1;
-    } else if (arg[i] == '"') {
-      out.push_back('\\');
-      out.push_back('"');
-    } else {
-      out.push_back(arg[i]);
-    }
-  }
-  out.push_back('"');
-
-  return out;
-}
-#endif
-
-}  // namespace
-
-CommandLine::CommandLine(NoProgram no_program)
-    : argv_(1),
-      begin_args_(1) {
-}
-
-CommandLine::CommandLine(const FilePath& program)
-    : argv_(1),
-      begin_args_(1) {
-  SetProgram(program);
-}
-
-CommandLine::CommandLine(int argc, const CommandLine::CharType* const* argv)
-    : argv_(1),
-      begin_args_(1) {
-  InitFromArgv(argc, argv);
-}
-
-CommandLine::CommandLine(const StringVector& argv)
-    : argv_(1),
-      begin_args_(1) {
-  InitFromArgv(argv);
-}
-
-CommandLine::~CommandLine() {
-}
-
-#if defined(OS_WIN)
-// static
-void CommandLine::set_slash_is_not_a_switch() {
-  // The last switch prefix should be slash, so adjust the size to skip it.
-  DCHECK(wcscmp(kSwitchPrefixes[arraysize(kSwitchPrefixes) - 1], L"/") == 0);
-  switch_prefix_count = arraysize(kSwitchPrefixes) - 1;
-}
-#endif
-
-// static
-bool CommandLine::Init(int argc, const char* const* argv) {
-  if (current_process_commandline_) {
-    // If this is intentional, Reset() must be called first. If we are using
-    // the shared build mode, we have to share a single object across multiple
-    // shared libraries.
-    return false;
-  }
-
-  current_process_commandline_ = new CommandLine(NO_PROGRAM);
-#if defined(OS_WIN)
-  current_process_commandline_->ParseFromString(::GetCommandLineW());
-#elif defined(OS_POSIX)
-  current_process_commandline_->InitFromArgv(argc, argv);
-#endif
-
-  return true;
-}
-
-// static
-void CommandLine::Reset() {
-  DCHECK(current_process_commandline_);
-  delete current_process_commandline_;
-  current_process_commandline_ = NULL;
-}
-
-// static
-CommandLine* CommandLine::ForCurrentProcess() {
-  DCHECK(current_process_commandline_);
-  return current_process_commandline_;
-}
-
-// static
-bool CommandLine::InitializedForCurrentProcess() {
-  return !!current_process_commandline_;
-}
-
-#if defined(OS_WIN)
-// static
-CommandLine CommandLine::FromString(const std::wstring& command_line) {
-  CommandLine cmd(NO_PROGRAM);
-  cmd.ParseFromString(command_line);
-  return cmd;
-}
-#endif
-
-void CommandLine::InitFromArgv(int argc,
-                               const CommandLine::CharType* const* argv) {
-  StringVector new_argv;
-  for (int i = 0; i < argc; ++i)
-    new_argv.push_back(argv[i]);
-  InitFromArgv(new_argv);
-}
-
-void CommandLine::InitFromArgv(const StringVector& argv) {
-  argv_ = StringVector(1);
-  switches_.clear();
-  begin_args_ = 1;
-  SetProgram(argv.empty() ? FilePath() : FilePath(argv[0]));
-  AppendSwitchesAndArguments(*this, argv);
-}
-
-CommandLine::StringType CommandLine::GetCommandLineString() const {
-  StringType string(argv_[0]);
-#if defined(OS_WIN)
-  string = QuoteForCommandLineToArgvW(string);
-#endif
-  StringType params(GetArgumentsString());
-  if (!params.empty()) {
-    string.append(StringType(FILE_PATH_LITERAL(" ")));
-    string.append(params);
-  }
-  return string;
-}
-
-CommandLine::StringType CommandLine::GetArgumentsString() const {
-  StringType params;
-  // Append switches and arguments.
-  bool parse_switches = true;
-  for (size_t i = 1; i < argv_.size(); ++i) {
-    StringType arg = argv_[i];
-    StringType switch_string;
-    StringType switch_value;
-    parse_switches &= arg != kSwitchTerminator;
-    if (i > 1)
-      params.append(StringType(FILE_PATH_LITERAL(" ")));
-    if (parse_switches && IsSwitch(arg, &switch_string, &switch_value)) {
-      params.append(switch_string);
-      if (!switch_value.empty()) {
-#if defined(OS_WIN)
-        switch_value = QuoteForCommandLineToArgvW(switch_value);
-#endif
-        params.append(kSwitchValueSeparator + switch_value);
-      }
-    }
-    else {
-#if defined(OS_WIN)
-      arg = QuoteForCommandLineToArgvW(arg);
-#endif
-      params.append(arg);
-    }
-  }
-  return params;
-}
-
-FilePath CommandLine::GetProgram() const {
-  return FilePath(argv_[0]);
-}
-
-void CommandLine::SetProgram(const FilePath& program) {
-  TrimWhitespace(program.value(), TRIM_ALL, &argv_[0]);
-}
-
-bool CommandLine::HasSwitch(const std::string& switch_string) const {
-  return switches_.find(LowerASCIIOnWindows(switch_string)) != switches_.end();
-}
-
-std::string CommandLine::GetSwitchValueASCII(
-    const std::string& switch_string) const {
-  StringType value = GetSwitchValueNative(switch_string);
-  if (!IsStringASCII(value)) {
-    DLOG(WARNING) << "Value of switch (" << switch_string << ") must be ASCII.";
-    return std::string();
-  }
-#if defined(OS_WIN)
-  return UTF16ToASCII(value);
-#else
-  return value;
-#endif
-}
-
-FilePath CommandLine::GetSwitchValuePath(
-    const std::string& switch_string) const {
-  return FilePath(GetSwitchValueNative(switch_string));
-}
-
-CommandLine::StringType CommandLine::GetSwitchValueNative(
-    const std::string& switch_string) const {
-  SwitchMap::const_iterator result =
-    switches_.find(LowerASCIIOnWindows(switch_string));
-  return result == switches_.end() ? StringType() : result->second;
-}
-
-void CommandLine::AppendSwitch(const std::string& switch_string) {
-  AppendSwitchNative(switch_string, StringType());
-}
-
-void CommandLine::AppendSwitchPath(const std::string& switch_string,
-                                   const FilePath& path) {
-  AppendSwitchNative(switch_string, path.value());
-}
-
-void CommandLine::AppendSwitchNative(const std::string& switch_string,
-                                     const CommandLine::StringType& value) {
-  std::string switch_key(LowerASCIIOnWindows(switch_string));
-#if defined(OS_WIN)
-  StringType combined_switch_string(ASCIIToWide(switch_key));
-#elif defined(OS_POSIX)
-  StringType combined_switch_string(switch_string);
-#endif
-  size_t prefix_length = GetSwitchPrefixLength(combined_switch_string);
-  switches_[switch_key.substr(prefix_length)] = value;
-  // Preserve existing switch prefixes in |argv_|; only append one if necessary.
-  if (prefix_length == 0)
-    combined_switch_string = kSwitchPrefixes[0] + combined_switch_string;
-  if (!value.empty())
-    combined_switch_string += kSwitchValueSeparator + value;
-  // Append the switch and update the switches/arguments divider |begin_args_|.
-  argv_.insert(argv_.begin() + begin_args_++, combined_switch_string);
-}
-
-void CommandLine::AppendSwitchASCII(const std::string& switch_string,
-                                    const std::string& value_string) {
-#if defined(OS_WIN)
-  AppendSwitchNative(switch_string, ASCIIToWide(value_string));
-#elif defined(OS_POSIX)
-  AppendSwitchNative(switch_string, value_string);
-#endif
-}
-
-void CommandLine::CopySwitchesFrom(const CommandLine& source,
-                                   const char* const switches[],
-                                   size_t count) {
-  for (size_t i = 0; i < count; ++i) {
-    if (source.HasSwitch(switches[i]))
-      AppendSwitchNative(switches[i], source.GetSwitchValueNative(switches[i]));
-  }
-}
-
-CommandLine::StringVector CommandLine::GetArgs() const {
-  // Gather all arguments after the last switch (may include kSwitchTerminator).
-  StringVector args(argv_.begin() + begin_args_, argv_.end());
-  // Erase only the first kSwitchTerminator (maybe "--" is a legitimate page?)
-  StringVector::iterator switch_terminator =
-      std::find(args.begin(), args.end(), kSwitchTerminator);
-  if (switch_terminator != args.end())
-    args.erase(switch_terminator);
-  return args;
-}
-
-void CommandLine::AppendArg(const std::string& value) {
-#if defined(OS_WIN)
-  DCHECK(IsStringUTF8(value));
-  AppendArgNative(UTF8ToWide(value));
-#elif defined(OS_POSIX)
-  AppendArgNative(value);
-#endif
-}
-
-void CommandLine::AppendArgPath(const FilePath& path) {
-  AppendArgNative(path.value());
-}
-
-void CommandLine::AppendArgNative(const CommandLine::StringType& value) {
-  argv_.push_back(value);
-}
-
-void CommandLine::AppendArguments(const CommandLine& other,
-                                  bool include_program) {
-  if (include_program)
-    SetProgram(other.GetProgram());
-  AppendSwitchesAndArguments(*this, other.argv());
-}
-
-void CommandLine::PrependWrapper(const CommandLine::StringType& wrapper) {
-  if (wrapper.empty())
-    return;
-  // The wrapper may have embedded arguments (like "gdb --args"). In this case,
-  // we don't pretend to do anything fancy, we just split on spaces.
-  StringVector wrapper_argv;
-  SplitString(wrapper, FILE_PATH_LITERAL(' '), &wrapper_argv);
-  // Prepend the wrapper and update the switches/arguments |begin_args_|.
-  argv_.insert(argv_.begin(), wrapper_argv.begin(), wrapper_argv.end());
-  begin_args_ += wrapper_argv.size();
-}
-
-#if defined(OS_WIN)
-void CommandLine::ParseFromString(const std::wstring& command_line) {
-  std::wstring command_line_string;
-  TrimWhitespace(command_line, TRIM_ALL, &command_line_string);
-  if (command_line_string.empty())
-    return;
-
-  int num_args = 0;
-  wchar_t** args = NULL;
-  args = ::CommandLineToArgvW(command_line_string.c_str(), &num_args);
-
-  DPLOG_IF(FATAL, !args) << "CommandLineToArgvW failed on command line: "
-                         << UTF16ToUTF8(command_line);
-  InitFromArgv(num_args, args);
-  LocalFree(args);
-}
-#endif
-
-}  // namespace butil

+ 0 - 194
src/butil/command_line.h

@@ -1,194 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This class works with command lines: building and parsing.
-// Arguments with prefixes ('--', '-', and on Windows, '/') are switches.
-// Switches will precede all other arguments without switch prefixes.
-// Switches can optionally have values, delimited by '=', e.g., "-switch=value".
-// An argument of "--" will terminate switch parsing during initialization,
-// interpreting subsequent tokens as non-switch arguments, regardless of prefix.
-
-// There is a singleton read-only CommandLine that represents the command line
-// that the current process was started with.  It must be initialized in main().
-
-#ifndef BASE_COMMAND_LINE_H_
-#define BASE_COMMAND_LINE_H_
-
-#include <stddef.h>
-#include <map>
-#include <string>
-#include <vector>
-
-#include "butil/base_export.h"
-#include "butil/build_config.h"
-
-namespace butil {
-
-class FilePath;
-
-class BASE_EXPORT CommandLine {
- public:
-#if defined(OS_WIN)
-  // The native command line string type.
-  typedef std::wstring StringType;
-#elif defined(OS_POSIX)
-  typedef std::string StringType;
-#endif
-
-  typedef StringType::value_type CharType;
-  typedef std::vector<StringType> StringVector;
-  typedef std::map<std::string, StringType> SwitchMap;
-
-  // A constructor for CommandLines that only carry switches and arguments.
-  enum NoProgram { NO_PROGRAM };
-  explicit CommandLine(NoProgram no_program);
-
-  // Construct a new command line with |program| as argv[0].
-  explicit CommandLine(const FilePath& program);
-
-  // Construct a new command line from an argument list.
-  CommandLine(int argc, const CharType* const* argv);
-  explicit CommandLine(const StringVector& argv);
-
-  ~CommandLine();
-
-#if defined(OS_WIN)
-  // By default this class will treat command-line arguments beginning with
-  // slashes as switches on Windows, but not other platforms.
-  //
-  // If this behavior is inappropriate for your application, you can call this
-  // function BEFORE initializing the current process' global command line
-  // object and the behavior will be the same as Posix systems (only hyphens
-  // begin switches, everything else will be an arg).
-  static void set_slash_is_not_a_switch();
-#endif
-
-  // Initialize the current process CommandLine singleton. On Windows, ignores
-  // its arguments (we instead parse GetCommandLineW() directly) because we
-  // don't trust the CRT's parsing of the command line, but it still must be
-  // called to set up the command line. Returns false if initialization has
-  // already occurred, and true otherwise. Only the caller receiving a 'true'
-  // return value should take responsibility for calling Reset.
-  static bool Init(int argc, const char* const* argv);
-
-  // Destroys the current process CommandLine singleton. This is necessary if
-  // you want to reset the base library to its initial state (for example, in an
-  // outer library that needs to be able to terminate, and be re-initialized).
-  // If Init is called only once, as in main(), Reset() is not necessary.
-  static void Reset();
-
-  // Get the singleton CommandLine representing the current process's
-  // command line. Note: returned value is mutable, but not thread safe;
-  // only mutate if you know what you're doing!
-  static CommandLine* ForCurrentProcess();
-
-  // Returns true if the CommandLine has been initialized for the given process.
-  static bool InitializedForCurrentProcess();
-
-#if defined(OS_WIN)
-  static CommandLine FromString(const std::wstring& command_line);
-#endif
-
-  // Initialize from an argv vector.
-  void InitFromArgv(int argc, const CharType* const* argv);
-  void InitFromArgv(const StringVector& argv);
-
-  // Constructs and returns the represented command line string.
-  // CAUTION! This should be avoided on POSIX because quoting behavior is
-  // unclear.
-  StringType GetCommandLineString() const;
-
-  // Constructs and returns the represented arguments string.
-  // CAUTION! This should be avoided on POSIX because quoting behavior is
-  // unclear.
-  StringType GetArgumentsString() const;
-
-  // Returns the original command line string as a vector of strings.
-  const StringVector& argv() const { return argv_; }
-
-  // Get and Set the program part of the command line string (the first item).
-  FilePath GetProgram() const;
-  void SetProgram(const FilePath& program);
-
-  // Returns true if this command line contains the given switch.
-  // (Switch names are case-insensitive).
-  bool HasSwitch(const std::string& switch_string) const;
-
-  // Returns the value associated with the given switch. If the switch has no
-  // value or isn't present, this method returns the empty string.
-  std::string GetSwitchValueASCII(const std::string& switch_string) const;
-  FilePath GetSwitchValuePath(const std::string& switch_string) const;
-  StringType GetSwitchValueNative(const std::string& switch_string) const;
-
-  // Get a copy of all switches, along with their values.
-  const SwitchMap& GetSwitches() const { return switches_; }
-
-  // Append a switch [with optional value] to the command line.
-  // Note: Switches will precede arguments regardless of appending order.
-  void AppendSwitch(const std::string& switch_string);
-  void AppendSwitchPath(const std::string& switch_string,
-                        const FilePath& path);
-  void AppendSwitchNative(const std::string& switch_string,
-                          const StringType& value);
-  void AppendSwitchASCII(const std::string& switch_string,
-                         const std::string& value);
-
-  // Copy a set of switches (and any values) from another command line.
-  // Commonly used when launching a subprocess.
-  void CopySwitchesFrom(const CommandLine& source,
-                        const char* const switches[],
-                        size_t count);
-
-  // Get the remaining arguments to the command.
-  StringVector GetArgs() const;
-
-  // Append an argument to the command line. Note that the argument is quoted
-  // properly such that it is interpreted as one argument to the target command.
-  // AppendArg is primarily for ASCII; non-ASCII input is interpreted as UTF-8.
-  // Note: Switches will precede arguments regardless of appending order.
-  void AppendArg(const std::string& value);
-  void AppendArgPath(const FilePath& value);
-  void AppendArgNative(const StringType& value);
-
-  // Append the switches and arguments from another command line to this one.
-  // If |include_program| is true, include |other|'s program as well.
-  void AppendArguments(const CommandLine& other, bool include_program);
-
-  // Insert a command before the current command.
-  // Common for debuggers, like "valgrind" or "gdb --args".
-  void PrependWrapper(const StringType& wrapper);
-
-#if defined(OS_WIN)
-  // Initialize by parsing the given command line string.
-  // The program name is assumed to be the first item in the string.
-  void ParseFromString(const std::wstring& command_line);
-#endif
-
- private:
-  // Disallow default constructor; a program name must be explicitly specified.
-  CommandLine();
-  // Allow the copy constructor. A common pattern is to copy of the current
-  // process's command line and then add some flags to it. For example:
-  //   CommandLine cl(*CommandLine::ForCurrentProcess());
-  //   cl.AppendSwitch(...);
-
-  // The singleton CommandLine representing the current process's command line.
-  static CommandLine* current_process_commandline_;
-
-  // The argv array: { program, [(--|-|/)switch[=value]]*, [--], [argument]* }
-  StringVector argv_;
-
-  // Parsed-out switch keys and values.
-  SwitchMap switches_;
-
-  // The index after the program and switches, any arguments start here.
-  size_t begin_args_;
-};
-
-}  // namespace butil
-
-// TODO(brettw) remove once all callers specify the namespace properly.
-using butil::CommandLine;
-
-#endif  // BASE_COMMAND_LINE_H_

+ 0 - 1
src/butil/file_util_posix.cc

@@ -43,7 +43,6 @@
 #include "butil/strings/stringprintf.h"
 #include "butil/strings/sys_string_conversions.h"
 #include "butil/strings/utf_string_conversions.h"
-#include "butil/sys_info.h"
 #include "butil/threading/thread_restrictions.h"
 #include "butil/time/time.h"
 

+ 0 - 1
src/butil/logging.cc

@@ -60,7 +60,6 @@ typedef pthread_mutex_t* MutexHandle;
 #include <string>
 
 #include "butil/file_util.h"
-#include "butil/command_line.h"
 #include "butil/debug/alias.h"
 #include "butil/debug/debugger.h"
 #include "butil/debug/stack_trace.h"

+ 0 - 325
src/butil/memory/shared_memory.h

@@ -1,325 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_MEMORY_SHARED_MEMORY_H_
-#define BASE_MEMORY_SHARED_MEMORY_H_
-
-#include "butil/build_config.h"
-
-#include <string>
-
-#if defined(OS_POSIX)
-#include <stdio.h>
-#include <sys/types.h>
-#include <semaphore.h>
-#endif
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/process/process_handle.h"
-
-#if defined(OS_POSIX)
-#include "butil/file_descriptor_posix.h"
-#include "butil/file_util.h"
-#include "butil/files/scoped_file.h"
-#endif
-
-namespace butil {
-
-class FilePath;
-
-// SharedMemoryHandle is a platform specific type which represents
-// the underlying OS handle to a shared memory segment.
-#if defined(OS_WIN)
-typedef HANDLE SharedMemoryHandle;
-#elif defined(OS_POSIX)
-// A SharedMemoryId is sufficient to identify a given shared memory segment on a
-// system, but insufficient to map it.
-typedef FileDescriptor SharedMemoryHandle;
-typedef ino_t SharedMemoryId;
-#endif
-
-// Options for creating a shared memory object.
-struct SharedMemoryCreateOptions {
-  SharedMemoryCreateOptions()
-      : name_deprecated(NULL),
-        size(0),
-        open_existing_deprecated(false),
-        executable(false),
-        share_read_only(false) {}
-
-  // DEPRECATED (crbug.com/345734):
-  // If NULL, the object is anonymous.  This pointer is owned by the caller
-  // and must live through the call to Create().
-  const std::string* name_deprecated;
-
-  // Size of the shared memory object to be created.
-  // When opening an existing object, this has no effect.
-  size_t size;
-
-  // DEPRECATED (crbug.com/345734):
-  // If true, and the shared memory already exists, Create() will open the
-  // existing shared memory and ignore the size parameter.  If false,
-  // shared memory must not exist.  This flag is meaningless unless
-  // name_deprecated is non-NULL.
-  bool open_existing_deprecated;
-
-  // If true, mappings might need to be made executable later.
-  bool executable;
-
-  // If true, the file can be shared read-only to a process.
-  bool share_read_only;
-};
-
-// Platform abstraction for shared memory.  Provides a C++ wrapper
-// around the OS primitive for a memory mapped file.
-class BASE_EXPORT SharedMemory {
- public:
-  SharedMemory();
-
-#if defined(OS_WIN)
-  // Similar to the default constructor, except that this allows for
-  // calling LockDeprecated() to acquire the named mutex before either Create or
-  // Open are called on Windows.
-  explicit SharedMemory(const std::wstring& name);
-#endif
-
-  // Create a new SharedMemory object from an existing, open
-  // shared memory file.
-  //
-  // WARNING: This does not reduce the OS-level permissions on the handle; it
-  // only affects how the SharedMemory will be mmapped.  Use
-  // ShareReadOnlyToProcess to drop permissions.  TODO(jln,jyasskin): DCHECK
-  // that |read_only| matches the permissions of the handle.
-  SharedMemory(SharedMemoryHandle handle, bool read_only);
-
-  // Create a new SharedMemory object from an existing, open
-  // shared memory file that was created by a remote process and not shared
-  // to the current process.
-  SharedMemory(SharedMemoryHandle handle, bool read_only,
-               ProcessHandle process);
-
-  // Closes any open files.
-  ~SharedMemory();
-
-  // Return true iff the given handle is valid (i.e. not the distingished
-  // invalid value; NULL for a HANDLE and -1 for a file descriptor)
-  static bool IsHandleValid(const SharedMemoryHandle& handle);
-
-  // Returns invalid handle (see comment above for exact definition).
-  static SharedMemoryHandle NULLHandle();
-
-  // Closes a shared memory handle.
-  static void CloseHandle(const SharedMemoryHandle& handle);
-
-  // Returns the maximum number of handles that can be open at once per process.
-  static size_t GetHandleLimit();
-
-  // Creates a shared memory object as described by the options struct.
-  // Returns true on success and false on failure.
-  bool Create(const SharedMemoryCreateOptions& options);
-
-  // Creates and maps an anonymous shared memory segment of size size.
-  // Returns true on success and false on failure.
-  bool CreateAndMapAnonymous(size_t size);
-
-  // Creates an anonymous shared memory segment of size size.
-  // Returns true on success and false on failure.
-  bool CreateAnonymous(size_t size) {
-    SharedMemoryCreateOptions options;
-    options.size = size;
-    return Create(options);
-  }
-
-  // DEPRECATED (crbug.com/345734):
-  // Creates or opens a shared memory segment based on a name.
-  // If open_existing is true, and the shared memory already exists,
-  // opens the existing shared memory and ignores the size parameter.
-  // If open_existing is false, shared memory must not exist.
-  // size is the size of the block to be created.
-  // Returns true on success, false on failure.
-  bool CreateNamedDeprecated(
-      const std::string& name, bool open_existing, size_t size) {
-    SharedMemoryCreateOptions options;
-    options.name_deprecated = &name;
-    options.open_existing_deprecated = open_existing;
-    options.size = size;
-    return Create(options);
-  }
-
-  // Deletes resources associated with a shared memory segment based on name.
-  // Not all platforms require this call.
-  bool Delete(const std::string& name);
-
-  // Opens a shared memory segment based on a name.
-  // If read_only is true, opens for read-only access.
-  // Returns true on success, false on failure.
-  bool Open(const std::string& name, bool read_only);
-
-  // Maps the shared memory into the caller's address space.
-  // Returns true on success, false otherwise.  The memory address
-  // is accessed via the memory() accessor.  The mapped address is guaranteed to
-  // have an alignment of at least MAP_MINIMUM_ALIGNMENT. This method will fail
-  // if this object is currently mapped.
-  bool Map(size_t bytes) {
-    return MapAt(0, bytes);
-  }
-
-  // Same as above, but with |offset| to specify from begining of the shared
-  // memory block to map.
-  // |offset| must be alignent to value of |SysInfo::VMAllocationGranularity()|.
-  bool MapAt(off_t offset, size_t bytes);
-  enum { MAP_MINIMUM_ALIGNMENT = 32 };
-
-  // Unmaps the shared memory from the caller's address space.
-  // Returns true if successful; returns false on error or if the
-  // memory is not mapped.
-  bool Unmap();
-
-  // The size requested when the map is first created.
-  size_t requested_size() const { return requested_size_; }
-
-  // The actual size of the mapped memory (may be larger than requested).
-  size_t mapped_size() const { return mapped_size_; }
-
-  // Gets a pointer to the opened memory space if it has been
-  // Mapped via Map().  Returns NULL if it is not mapped.
-  void *memory() const { return memory_; }
-
-  // Returns the underlying OS handle for this segment.
-  // Use of this handle for anything other than an opaque
-  // identifier is not portable.
-  SharedMemoryHandle handle() const;
-
-#if defined(OS_POSIX) && !defined(OS_NACL)
-  // Returns a unique identifier for this shared memory segment. Inode numbers
-  // are technically only unique to a single filesystem. However, we always
-  // allocate shared memory backing files from the same directory, so will end
-  // up on the same filesystem.
-  SharedMemoryId id() const { return inode_; }
-#endif
-
-  // Closes the open shared memory segment.
-  // It is safe to call Close repeatedly.
-  void Close();
-
-  // Shares the shared memory to another process.  Attempts to create a
-  // platform-specific new_handle which can be used in a remote process to read
-  // the shared memory file.  new_handle is an output parameter to receive the
-  // handle for use in the remote process.
-  //
-  // |*this| must have been initialized using one of the Create*() or Open()
-  // methods with share_read_only=true. If it was constructed from a
-  // SharedMemoryHandle, this call will CHECK-fail.
-  //
-  // Returns true on success, false otherwise.
-  bool ShareReadOnlyToProcess(ProcessHandle process,
-                              SharedMemoryHandle* new_handle) {
-    return ShareToProcessCommon(process, new_handle, false, SHARE_READONLY);
-  }
-
-  // Logically equivalent to:
-  //   bool ok = ShareReadOnlyToProcess(process, new_handle);
-  //   Close();
-  //   return ok;
-  // Note that the memory is unmapped by calling this method, regardless of the
-  // return value.
-  bool GiveReadOnlyToProcess(ProcessHandle process,
-                             SharedMemoryHandle* new_handle) {
-    return ShareToProcessCommon(process, new_handle, true, SHARE_READONLY);
-  }
-
-  // Shares the shared memory to another process.  Attempts
-  // to create a platform-specific new_handle which can be
-  // used in a remote process to access the shared memory
-  // file.  new_handle is an output parameter to receive
-  // the handle for use in the remote process.
-  // Returns true on success, false otherwise.
-  bool ShareToProcess(ProcessHandle process,
-                      SharedMemoryHandle* new_handle) {
-    return ShareToProcessCommon(process, new_handle, false, SHARE_CURRENT_MODE);
-  }
-
-  // Logically equivalent to:
-  //   bool ok = ShareToProcess(process, new_handle);
-  //   Close();
-  //   return ok;
-  // Note that the memory is unmapped by calling this method, regardless of the
-  // return value.
-  bool GiveToProcess(ProcessHandle process,
-                     SharedMemoryHandle* new_handle) {
-    return ShareToProcessCommon(process, new_handle, true, SHARE_CURRENT_MODE);
-  }
-
-  // DEPRECATED (crbug.com/345734):
-  // Locks the shared memory.
-  //
-  // WARNING: on POSIX the memory locking primitive only works across
-  // processes, not across threads.  The LockDeprecated method is not currently
-  // used in inner loops, so we protect against multiple threads in a
-  // critical section using a class global lock.
-  void LockDeprecated();
-
-  // DEPRECATED (crbug.com/345734):
-  // Releases the shared memory lock.
-  void UnlockDeprecated();
-
- private:
-#if defined(OS_POSIX) && !defined(OS_NACL)
-#if !defined(OS_ANDROID)
-  bool PrepareMapFile(ScopedFILE fp, ScopedFD readonly);
-  bool FilePathForMemoryName(const std::string& mem_name, FilePath* path);
-#endif
-  void LockOrUnlockCommon(int function);
-#endif  // defined(OS_POSIX) && !defined(OS_NACL)
-  enum ShareMode {
-    SHARE_READONLY,
-    SHARE_CURRENT_MODE,
-  };
-  bool ShareToProcessCommon(ProcessHandle process,
-                            SharedMemoryHandle* new_handle,
-                            bool close_self,
-                            ShareMode);
-
-#if defined(OS_WIN)
-  std::wstring       name_;
-  HANDLE             mapped_file_;
-#elif defined(OS_POSIX)
-  int                mapped_file_;
-  int                readonly_mapped_file_;
-  ino_t              inode_;
-#endif
-  size_t             mapped_size_;
-  void*              memory_;
-  bool               read_only_;
-  size_t             requested_size_;
-#if !defined(OS_POSIX)
-  HANDLE             lock_;
-#endif
-
-  DISALLOW_COPY_AND_ASSIGN(SharedMemory);
-};
-
-// DEPRECATED (crbug.com/345734):
-// A helper class that acquires the shared memory lock while
-// the SharedMemoryAutoLockDeprecated is in scope.
-class SharedMemoryAutoLockDeprecated {
- public:
-  explicit SharedMemoryAutoLockDeprecated(SharedMemory* shared_memory)
-      : shared_memory_(shared_memory) {
-    shared_memory_->LockDeprecated();
-  }
-
-  ~SharedMemoryAutoLockDeprecated() {
-    shared_memory_->UnlockDeprecated();
-  }
-
- private:
-  SharedMemory* shared_memory_;
-  DISALLOW_COPY_AND_ASSIGN(SharedMemoryAutoLockDeprecated);
-};
-
-}  // namespace butil
-
-#endif  // BASE_MEMORY_SHARED_MEMORY_H_

+ 0 - 479
src/butil/memory/shared_memory_posix.cc

@@ -1,479 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/memory/shared_memory.h"
-
-#include <errno.h>
-#include <fcntl.h>
-#include <sys/mman.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "butil/file_util.h"
-#include "butil/files/scoped_file.h"
-#include "butil/lazy_instance.h"
-#include "butil/logging.h"
-#include "butil/process/process_metrics.h"
-#include "butil/safe_strerror_posix.h"
-#include "butil/strings/utf_string_conversions.h"
-#include "butil/synchronization/lock.h"
-#include "butil/threading/platform_thread.h"
-#include "butil/threading/thread_restrictions.h"
-
-#if defined(OS_MACOSX)
-#include "butil/mac/foundation_util.h"
-#endif  // OS_MACOSX
-
-#if defined(OS_ANDROID)
-#include "butil/os_compat_android.h"
-#include "third_party/ashmem/ashmem.h"
-#endif
-
-namespace butil {
-
-namespace {
-
-LazyInstance<Lock>::Leaky g_thread_lock_ = LAZY_INSTANCE_INITIALIZER;
-
-}
-
-SharedMemory::SharedMemory()
-    : mapped_file_(-1),
-      readonly_mapped_file_(-1),
-      inode_(0),
-      mapped_size_(0),
-      memory_(NULL),
-      read_only_(false),
-      requested_size_(0) {
-}
-
-SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only)
-    : mapped_file_(handle.fd),
-      readonly_mapped_file_(-1),
-      inode_(0),
-      mapped_size_(0),
-      memory_(NULL),
-      read_only_(read_only),
-      requested_size_(0) {
-  struct stat st;
-  if (fstat(handle.fd, &st) == 0) {
-    // If fstat fails, then the file descriptor is invalid and we'll learn this
-    // fact when Map() fails.
-    inode_ = st.st_ino;
-  }
-}
-
-SharedMemory::SharedMemory(SharedMemoryHandle handle, bool read_only,
-                           ProcessHandle process)
-    : mapped_file_(handle.fd),
-      readonly_mapped_file_(-1),
-      inode_(0),
-      mapped_size_(0),
-      memory_(NULL),
-      read_only_(read_only),
-      requested_size_(0) {
-  // We don't handle this case yet (note the ignored parameter); let's die if
-  // someone comes calling.
-  NOTREACHED();
-}
-
-SharedMemory::~SharedMemory() {
-  Close();
-}
-
-// static
-bool SharedMemory::IsHandleValid(const SharedMemoryHandle& handle) {
-  return handle.fd >= 0;
-}
-
-// static
-SharedMemoryHandle SharedMemory::NULLHandle() {
-  return SharedMemoryHandle();
-}
-
-// static
-void SharedMemory::CloseHandle(const SharedMemoryHandle& handle) {
-  DCHECK_GE(handle.fd, 0);
-  if (close(handle.fd) < 0)
-    DPLOG(ERROR) << "close";
-}
-
-// static
-size_t SharedMemory::GetHandleLimit() {
-  return butil::GetMaxFds();
-}
-
-bool SharedMemory::CreateAndMapAnonymous(size_t size) {
-  return CreateAnonymous(size) && Map(size);
-}
-
-#if !defined(OS_ANDROID)
-// Chromium mostly only uses the unique/private shmem as specified by
-// "name == L"". The exception is in the StatsTable.
-// TODO(jrg): there is no way to "clean up" all unused named shmem if
-// we restart from a crash.  (That isn't a new problem, but it is a problem.)
-// In case we want to delete it later, it may be useful to save the value
-// of mem_filename after FilePathForMemoryName().
-bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
-  DCHECK_EQ(-1, mapped_file_);
-  if (options.size == 0) return false;
-
-  if (options.size > static_cast<size_t>(std::numeric_limits<int>::max()))
-    return false;
-
-  // This function theoretically can block on the disk, but realistically
-  // the temporary files we create will just go into the buffer cache
-  // and be deleted before they ever make it out to disk.
-  butil::ThreadRestrictions::ScopedAllowIO allow_io;
-
-  ScopedFILE fp;
-  bool fix_size = true;
-  ScopedFD readonly_fd;
-
-  FilePath path;
-  if (options.name_deprecated == NULL || options.name_deprecated->empty()) {
-    // It doesn't make sense to have a open-existing private piece of shmem
-    DCHECK(!options.open_existing_deprecated);
-    // Q: Why not use the shm_open() etc. APIs?
-    // A: Because they're limited to 4mb on OS X.  FFFFFFFUUUUUUUUUUU
-    FilePath directory;
-    if (GetShmemTempDir(options.executable, &directory))
-      fp.reset(CreateAndOpenTemporaryFileInDir(directory, &path));
-
-    if (fp) {
-      if (options.share_read_only) {
-        // Also open as readonly so that we can ShareReadOnlyToProcess.
-        readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
-        if (!readonly_fd.is_valid()) {
-          DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
-          fp.reset();
-          return false;
-        }
-      }
-      // Deleting the file prevents anyone else from mapping it in (making it
-      // private), and prevents the need for cleanup (once the last fd is
-      // closed, it is truly freed).
-      if (unlink(path.value().c_str()))
-        PLOG(WARNING) << "unlink";
-    }
-  } else {
-    if (!FilePathForMemoryName(*options.name_deprecated, &path))
-      return false;
-
-    // Make sure that the file is opened without any permission
-    // to other users on the system.
-    const mode_t kOwnerOnly = S_IRUSR | S_IWUSR;
-
-    // First, try to create the file.
-    int fd = HANDLE_EINTR(
-        open(path.value().c_str(), O_RDWR | O_CREAT | O_EXCL, kOwnerOnly));
-    if (fd == -1 && options.open_existing_deprecated) {
-      // If this doesn't work, try and open an existing file in append mode.
-      // Opening an existing file in a world writable directory has two main
-      // security implications:
-      // - Attackers could plant a file under their control, so ownership of
-      //   the file is checked below.
-      // - Attackers could plant a symbolic link so that an unexpected file
-      //   is opened, so O_NOFOLLOW is passed to open().
-      fd = HANDLE_EINTR(
-          open(path.value().c_str(), O_RDWR | O_APPEND | O_NOFOLLOW));
-
-      // Check that the current user owns the file.
-      // If uid != euid, then a more complex permission model is used and this
-      // API is not appropriate.
-      const uid_t real_uid = getuid();
-      const uid_t effective_uid = geteuid();
-      struct stat sb;
-      if (fd >= 0 &&
-          (fstat(fd, &sb) != 0 || sb.st_uid != real_uid ||
-           sb.st_uid != effective_uid)) {
-        LOG(ERROR) <<
-            "Invalid owner when opening existing shared memory file.";
-        close(fd);
-        return false;
-      }
-
-      // An existing file was opened, so its size should not be fixed.
-      fix_size = false;
-    }
-
-    if (options.share_read_only) {
-      // Also open as readonly so that we can ShareReadOnlyToProcess.
-      readonly_fd.reset(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
-      if (!readonly_fd.is_valid()) {
-        DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
-        close(fd);
-        fd = -1;
-        return false;
-      }
-    }
-    if (fd >= 0) {
-      // "a+" is always appropriate: if it's a new file, a+ is similar to w+.
-      fp.reset(fdopen(fd, "a+"));
-    }
-  }
-  if (fp && fix_size) {
-    // Get current size.
-    struct stat stat;
-    if (fstat(fileno(fp.get()), &stat) != 0)
-      return false;
-    const size_t current_size = stat.st_size;
-    if (current_size != options.size) {
-      if (HANDLE_EINTR(ftruncate(fileno(fp.get()), options.size)) != 0)
-        return false;
-    }
-    requested_size_ = options.size;
-  }
-  if (fp == NULL) {
-#if !defined(OS_MACOSX)
-    PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
-    FilePath dir = path.DirName();
-    if (access(dir.value().c_str(), W_OK | X_OK) < 0) {
-      PLOG(ERROR) << "Unable to access(W_OK|X_OK) " << dir.value();
-      if (dir.value() == "/dev/shm") {
-        LOG(FATAL) << "This is frequently caused by incorrect permissions on "
-                   << "/dev/shm.  Try 'sudo chmod 1777 /dev/shm' to fix.";
-      }
-    }
-#else
-    PLOG(ERROR) << "Creating shared memory in " << path.value() << " failed";
-#endif
-    return false;
-  }
-
-  return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
-}
-
-// Our current implementation of shmem is with mmap()ing of files.
-// These files need to be deleted explicitly.
-// In practice this call is only needed for unit tests.
-bool SharedMemory::Delete(const std::string& name) {
-  FilePath path;
-  if (!FilePathForMemoryName(name, &path))
-    return false;
-
-  if (PathExists(path))
-    return butil::DeleteFile(path, false);
-
-  // Doesn't exist, so success.
-  return true;
-}
-
-bool SharedMemory::Open(const std::string& name, bool read_only) {
-  FilePath path;
-  if (!FilePathForMemoryName(name, &path))
-    return false;
-
-  read_only_ = read_only;
-
-  const char *mode = read_only ? "r" : "r+";
-  ScopedFILE fp(butil::OpenFile(path, mode));
-  ScopedFD readonly_fd(HANDLE_EINTR(open(path.value().c_str(), O_RDONLY)));
-  if (!readonly_fd.is_valid()) {
-    DPLOG(ERROR) << "open(\"" << path.value() << "\", O_RDONLY) failed";
-    return false;
-  }
-  return PrepareMapFile(fp.Pass(), readonly_fd.Pass());
-}
-#endif  // !defined(OS_ANDROID)
-
-bool SharedMemory::MapAt(off_t offset, size_t bytes) {
-  if (mapped_file_ == -1)
-    return false;
-
-  if (bytes > static_cast<size_t>(std::numeric_limits<int>::max()))
-    return false;
-
-  if (memory_)
-    return false;
-
-#if defined(OS_ANDROID)
-  // On Android, Map can be called with a size and offset of zero to use the
-  // ashmem-determined size.
-  if (bytes == 0) {
-    DCHECK_EQ(0, offset);
-    int ashmem_bytes = ashmem_get_size_region(mapped_file_);
-    if (ashmem_bytes < 0)
-      return false;
-    bytes = ashmem_bytes;
-  }
-#endif
-
-  memory_ = mmap(NULL, bytes, PROT_READ | (read_only_ ? 0 : PROT_WRITE),
-                 MAP_SHARED, mapped_file_, offset);
-
-  bool mmap_succeeded = memory_ != (void*)-1 && memory_ != NULL;
-  if (mmap_succeeded) {
-    mapped_size_ = bytes;
-    DCHECK_EQ(0U, reinterpret_cast<uintptr_t>(memory_) &
-        (SharedMemory::MAP_MINIMUM_ALIGNMENT - 1));
-  } else {
-    memory_ = NULL;
-  }
-
-  return mmap_succeeded;
-}
-
-bool SharedMemory::Unmap() {
-  if (memory_ == NULL)
-    return false;
-
-  munmap(memory_, mapped_size_);
-  memory_ = NULL;
-  mapped_size_ = 0;
-  return true;
-}
-
-SharedMemoryHandle SharedMemory::handle() const {
-  return FileDescriptor(mapped_file_, false);
-}
-
-void SharedMemory::Close() {
-  Unmap();
-
-  if (mapped_file_ > 0) {
-    if (close(mapped_file_) < 0)
-      PLOG(ERROR) << "close";
-    mapped_file_ = -1;
-  }
-  if (readonly_mapped_file_ > 0) {
-    if (close(readonly_mapped_file_) < 0)
-      PLOG(ERROR) << "close";
-    readonly_mapped_file_ = -1;
-  }
-}
-
-void SharedMemory::LockDeprecated() {
-  g_thread_lock_.Get().Acquire();
-  LockOrUnlockCommon(F_LOCK);
-}
-
-void SharedMemory::UnlockDeprecated() {
-  LockOrUnlockCommon(F_ULOCK);
-  g_thread_lock_.Get().Release();
-}
-
-#if !defined(OS_ANDROID)
-bool SharedMemory::PrepareMapFile(ScopedFILE fp, ScopedFD readonly_fd) {
-  DCHECK_EQ(-1, mapped_file_);
-  DCHECK_EQ(-1, readonly_mapped_file_);
-  if (fp == NULL)
-    return false;
-
-  // This function theoretically can block on the disk, but realistically
-  // the temporary files we create will just go into the buffer cache
-  // and be deleted before they ever make it out to disk.
-  butil::ThreadRestrictions::ScopedAllowIO allow_io;
-
-  struct stat st;
-  memset(&st, 0, sizeof(st));
-  if (fstat(fileno(fp.get()), &st))
-    NOTREACHED();
-  if (readonly_fd.is_valid()) {
-    struct stat readonly_st;
-    memset(&readonly_st, 0, sizeof(readonly_st));
-    if (fstat(readonly_fd.get(), &readonly_st))
-      NOTREACHED();
-    if (st.st_dev != readonly_st.st_dev || st.st_ino != readonly_st.st_ino) {
-      LOG(ERROR) << "writable and read-only inodes don't match; bailing";
-      return false;
-    }
-  }
-
-  mapped_file_ = dup(fileno(fp.get()));
-  if (mapped_file_ == -1) {
-    if (errno == EMFILE) {
-      LOG(WARNING) << "Shared memory creation failed; out of file descriptors";
-      return false;
-    } else {
-      NOTREACHED() << "Call to dup failed, errno=" << errno;
-    }
-  }
-  inode_ = st.st_ino;
-  readonly_mapped_file_ = readonly_fd.release();
-
-  return true;
-}
-
-// For the given shmem named |mem_name|, return a filename to mmap()
-// (and possibly create).  Modifies |filename|.  Return false on
-// error, or true of we are happy.
-bool SharedMemory::FilePathForMemoryName(const std::string& mem_name,
-                                         FilePath* path) {
-  // mem_name will be used for a filename; make sure it doesn't
-  // contain anything which will confuse us.
-  DCHECK_EQ(std::string::npos, mem_name.find('/'));
-  DCHECK_EQ(std::string::npos, mem_name.find('\0'));
-
-  FilePath temp_dir;
-  if (!GetShmemTempDir(false, &temp_dir))
-    return false;
-
-#if !defined(OS_MACOSX)
-#if defined(GOOGLE_CHROME_BUILD)
-  std::string name_base = std::string("com.google.Chrome");
-#else
-  std::string name_base = std::string("org.chromium.Chromium");
-#endif
-#else  // OS_MACOSX
-  std::string name_base = std::string(butil::mac::BaseBundleID());
-#endif  // OS_MACOSX
-  *path = temp_dir.AppendASCII(name_base + ".shmem." + mem_name);
-  return true;
-}
-#endif  // !defined(OS_ANDROID)
-
-void SharedMemory::LockOrUnlockCommon(int function) {
-  DCHECK_GE(mapped_file_, 0);
-  while (lockf(mapped_file_, function, 0) < 0) {
-    if (errno == EINTR) {
-      continue;
-    } else if (errno == ENOLCK) {
-      // temporary kernel resource exaustion
-      butil::PlatformThread::Sleep(butil::TimeDelta::FromMilliseconds(500));
-      continue;
-    } else {
-      NOTREACHED() << "lockf() failed."
-                   << " function:" << function
-                   << " fd:" << mapped_file_
-                   << " errno:" << errno
-                   << " msg:" << safe_strerror(errno);
-    }
-  }
-}
-
-bool SharedMemory::ShareToProcessCommon(ProcessHandle process,
-                                        SharedMemoryHandle* new_handle,
-                                        bool close_self,
-                                        ShareMode share_mode) {
-  int handle_to_dup = -1;
-  switch(share_mode) {
-    case SHARE_CURRENT_MODE:
-      handle_to_dup = mapped_file_;
-      break;
-    case SHARE_READONLY:
-      // We could imagine re-opening the file from /dev/fd, but that can't make
-      // it readonly on Mac: https://codereview.chromium.org/27265002/#msg10
-      CHECK(readonly_mapped_file_ >= 0);
-      handle_to_dup = readonly_mapped_file_;
-      break;
-  }
-
-  const int new_fd = dup(handle_to_dup);
-  if (new_fd < 0) {
-    DPLOG(ERROR) << "dup() failed.";
-    return false;
-  }
-
-  new_handle->fd = new_fd;
-  new_handle->auto_close = true;
-
-  if (close_self)
-    Close();
-
-  return true;
-}
-
-}  // namespace butil

+ 0 - 341
src/butil/path_service.cc

@@ -1,341 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/path_service.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#include <shellapi.h>
-#include <shlobj.h>
-#endif
-
-#include "butil/containers/hash_tables.h"
-#include "butil/file_util.h"
-#include "butil/files/file_path.h"
-#include "butil/lazy_instance.h"
-#include "butil/logging.h"
-#include "butil/synchronization/lock.h"
-
-using butil::FilePath;
-using butil::MakeAbsoluteFilePath;
-
-namespace butil {
-  bool PathProvider(int key, FilePath* result);
-#if defined(OS_WIN)
-  bool PathProviderWin(int key, FilePath* result);
-#elif defined(OS_MACOSX)
-  bool PathProviderMac(int key, FilePath* result);
-#elif defined(OS_ANDROID)
-  bool PathProviderAndroid(int key, FilePath* result);
-#elif defined(OS_POSIX)
-  // PathProviderPosix is the default path provider on POSIX OSes other than
-  // Mac and Android.
-  bool PathProviderPosix(int key, FilePath* result);
-#endif
-}
-
-namespace {
-
-typedef butil::hash_map<int, FilePath> PathMap;
-
-// We keep a linked list of providers.  In a debug build we ensure that no two
-// providers claim overlapping keys.
-struct Provider {
-  PathService::ProviderFunc func;
-  struct Provider* next;
-#ifndef NDEBUG
-  int key_start;
-  int key_end;
-#endif
-  bool is_static;
-};
-
-Provider base_provider = {
-  butil::PathProvider,
-  NULL,
-#ifndef NDEBUG
-  butil::PATH_START,
-  butil::PATH_END,
-#endif
-  true
-};
-
-#if defined(OS_WIN)
-Provider base_provider_win = {
-  butil::PathProviderWin,
-  &base_provider,
-#ifndef NDEBUG
-  butil::PATH_WIN_START,
-  butil::PATH_WIN_END,
-#endif
-  true
-};
-#endif
-
-#if defined(OS_MACOSX)
-Provider base_provider_mac = {
-  butil::PathProviderMac,
-  &base_provider,
-#ifndef NDEBUG
-  butil::PATH_MAC_START,
-  butil::PATH_MAC_END,
-#endif
-  true
-};
-#endif
-
-#if defined(OS_ANDROID)
-Provider base_provider_android = {
-  butil::PathProviderAndroid,
-  &base_provider,
-#ifndef NDEBUG
-  butil::PATH_ANDROID_START,
-  butil::PATH_ANDROID_END,
-#endif
-  true
-};
-#endif
-
-#if defined(OS_POSIX) && !defined(OS_MACOSX) && !defined(OS_ANDROID)
-Provider base_provider_posix = {
-  butil::PathProviderPosix,
-  &base_provider,
-#ifndef NDEBUG
-  butil::PATH_POSIX_START,
-  butil::PATH_POSIX_END,
-#endif
-  true
-};
-#endif
-
-
-struct PathData {
-  butil::Lock lock;
-  PathMap cache;        // Cache mappings from path key to path value.
-  PathMap overrides;    // Track path overrides.
-  Provider* providers;  // Linked list of path service providers.
-  bool cache_disabled;  // Don't use cache if true;
-
-  PathData() : cache_disabled(false) {
-#if defined(OS_WIN)
-    providers = &base_provider_win;
-#elif defined(OS_MACOSX)
-    providers = &base_provider_mac;
-#elif defined(OS_ANDROID)
-    providers = &base_provider_android;
-#elif defined(OS_POSIX)
-    providers = &base_provider_posix;
-#endif
-  }
-
-  ~PathData() {
-    Provider* p = providers;
-    while (p) {
-      Provider* next = p->next;
-      if (!p->is_static)
-        delete p;
-      p = next;
-    }
-  }
-};
-
-static butil::LazyInstance<PathData> g_path_data = LAZY_INSTANCE_INITIALIZER;
-
-static PathData* GetPathData() {
-  return g_path_data.Pointer();
-}
-
-// Tries to find |key| in the cache. |path_data| should be locked by the caller!
-bool LockedGetFromCache(int key, const PathData* path_data, FilePath* result) {
-  if (path_data->cache_disabled)
-    return false;
-  // check for a cached version
-  PathMap::const_iterator it = path_data->cache.find(key);
-  if (it != path_data->cache.end()) {
-    *result = it->second;
-    return true;
-  }
-  return false;
-}
-
-// Tries to find |key| in the overrides map. |path_data| should be locked by the
-// caller!
-bool LockedGetFromOverrides(int key, PathData* path_data, FilePath* result) {
-  // check for an overridden version.
-  PathMap::const_iterator it = path_data->overrides.find(key);
-  if (it != path_data->overrides.end()) {
-    if (!path_data->cache_disabled)
-      path_data->cache[key] = it->second;
-    *result = it->second;
-    return true;
-  }
-  return false;
-}
-
-}  // namespace
-
-// TODO(brettw): this function does not handle long paths (filename > MAX_PATH)
-// characters). This isn't supported very well by Windows right now, so it is
-// moot, but we should keep this in mind for the future.
-// static
-bool PathService::Get(int key, FilePath* result) {
-  PathData* path_data = GetPathData();
-  DCHECK(path_data);
-  DCHECK(result);
-  DCHECK_GE(key, butil::DIR_CURRENT);
-
-  // special case the current directory because it can never be cached
-  if (key == butil::DIR_CURRENT)
-    return butil::GetCurrentDirectory(result);
-
-  Provider* provider = NULL;
-  {
-    butil::AutoLock scoped_lock(path_data->lock);
-    if (LockedGetFromCache(key, path_data, result))
-      return true;
-
-    if (LockedGetFromOverrides(key, path_data, result))
-      return true;
-
-    // Get the beginning of the list while it is still locked.
-    provider = path_data->providers;
-  }
-
-  FilePath path;
-
-  // Iterating does not need the lock because only the list head might be
-  // modified on another thread.
-  while (provider) {
-    if (provider->func(key, &path))
-      break;
-    DCHECK(path.empty()) << "provider should not have modified path";
-    provider = provider->next;
-  }
-
-  if (path.empty())
-    return false;
-
-  if (path.ReferencesParent()) {
-    // Make sure path service never returns a path with ".." in it.
-    path = MakeAbsoluteFilePath(path);
-    if (path.empty())
-      return false;
-  }
-  *result = path;
-
-  butil::AutoLock scoped_lock(path_data->lock);
-  if (!path_data->cache_disabled)
-    path_data->cache[key] = path;
-
-  return true;
-}
-
-// static
-bool PathService::Override(int key, const FilePath& path) {
-  // Just call the full function with true for the value of |create|, and
-  // assume that |path| may not be absolute yet.
-  return OverrideAndCreateIfNeeded(key, path, false, true);
-}
-
-// static
-bool PathService::OverrideAndCreateIfNeeded(int key,
-                                            const FilePath& path,
-                                            bool is_absolute,
-                                            bool create) {
-  PathData* path_data = GetPathData();
-  DCHECK(path_data);
-  DCHECK_GT(key, butil::DIR_CURRENT) << "invalid path key";
-
-  FilePath file_path = path;
-
-  // For some locations this will fail if called from inside the sandbox there-
-  // fore we protect this call with a flag.
-  if (create) {
-    // Make sure the directory exists. We need to do this before we translate
-    // this to the absolute path because on POSIX, MakeAbsoluteFilePath fails
-    // if called on a non-existent path.
-    if (!butil::PathExists(file_path) &&
-        !butil::CreateDirectory(file_path))
-      return false;
-  }
-
-  // We need to have an absolute path.
-  if (!is_absolute) {
-    file_path = MakeAbsoluteFilePath(file_path);
-    if (file_path.empty())
-      return false;
-  }
-  DCHECK(file_path.IsAbsolute());
-
-  butil::AutoLock scoped_lock(path_data->lock);
-
-  // Clear the cache now. Some of its entries could have depended
-  // on the value we are overriding, and are now out of sync with reality.
-  path_data->cache.clear();
-
-  path_data->overrides[key] = file_path;
-
-  return true;
-}
-
-// static
-bool PathService::RemoveOverride(int key) {
-  PathData* path_data = GetPathData();
-  DCHECK(path_data);
-
-  butil::AutoLock scoped_lock(path_data->lock);
-
-  if (path_data->overrides.find(key) == path_data->overrides.end())
-    return false;
-
-  // Clear the cache now. Some of its entries could have depended on the value
-  // we are going to remove, and are now out of sync.
-  path_data->cache.clear();
-
-  path_data->overrides.erase(key);
-
-  return true;
-}
-
-// static
-void PathService::RegisterProvider(ProviderFunc func, int key_start,
-                                   int key_end) {
-  PathData* path_data = GetPathData();
-  DCHECK(path_data);
-  DCHECK_GT(key_end, key_start);
-
-  Provider* p;
-
-  p = new Provider;
-  p->is_static = false;
-  p->func = func;
-#ifndef NDEBUG
-  p->key_start = key_start;
-  p->key_end = key_end;
-#endif
-
-  butil::AutoLock scoped_lock(path_data->lock);
-
-#ifndef NDEBUG
-  Provider *iter = path_data->providers;
-  while (iter) {
-    DCHECK(key_start >= iter->key_end || key_end <= iter->key_start) <<
-      "path provider collision";
-    iter = iter->next;
-  }
-#endif
-
-  p->next = path_data->providers;
-  path_data->providers = p;
-}
-
-// static
-void PathService::DisableCache() {
-  PathData* path_data = GetPathData();
-  DCHECK(path_data);
-
-  butil::AutoLock scoped_lock(path_data->lock);
-  path_data->cache.clear();
-  path_data->cache_disabled = true;
-}

+ 0 - 92
src/butil/path_service.h

@@ -1,92 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_PATH_SERVICE_H_
-#define BASE_PATH_SERVICE_H_
-
-#include <string>
-
-#include "butil/base_export.h"
-#include "butil/base_paths.h"
-#include "butil/gtest_prod_util.h"
-#include "butil/build_config.h"
-
-namespace butil {
-class FilePath;
-class ScopedPathOverride;
-}  // namespace
-
-// The path service is a global table mapping keys to file system paths.  It is
-// OK to use this service from multiple threads.
-//
-class BASE_EXPORT PathService {
- public:
-  // Retrieves a path to a special directory or file and places it into the
-  // string pointed to by 'path'. If you ask for a directory it is guaranteed
-  // to NOT have a path separator at the end. For example, "c:\windows\temp"
-  // Directories are also guaranteed to exist when this function succeeds.
-  //
-  // Returns true if the directory or file was successfully retrieved. On
-  // failure, 'path' will not be changed.
-  static bool Get(int key, butil::FilePath* path);
-
-  // Overrides the path to a special directory or file.  This cannot be used to
-  // change the value of DIR_CURRENT, but that should be obvious.  Also, if the
-  // path specifies a directory that does not exist, the directory will be
-  // created by this method.  This method returns true if successful.
-  //
-  // If the given path is relative, then it will be resolved against
-  // DIR_CURRENT.
-  //
-  // WARNING: Consumers of PathService::Get may expect paths to be constant
-  // over the lifetime of the app, so this method should be used with caution.
-  //
-  // Unit tests generally should use ScopedPathOverride instead. Overrides from
-  // one test should not carry over to another.
-  static bool Override(int key, const butil::FilePath& path);
-
-  // This function does the same as PathService::Override but it takes extra
-  // parameters:
-  // - |is_absolute| indicates that |path| has already been expanded into an
-  // absolute path, otherwise MakeAbsoluteFilePath() will be used. This is
-  // useful to override paths that may not exist yet, since MakeAbsoluteFilePath
-  // fails for those. Note that MakeAbsoluteFilePath also expands symbolic
-  // links, even if path.IsAbsolute() is already true.
-  // - |create| guides whether the directory to be overriden must
-  // be created in case it doesn't exist already.
-  static bool OverrideAndCreateIfNeeded(int key,
-                                        const butil::FilePath& path,
-                                        bool is_absolute,
-                                        bool create);
-
-  // To extend the set of supported keys, you can register a path provider,
-  // which is just a function mirroring PathService::Get.  The ProviderFunc
-  // returns false if it cannot provide a non-empty path for the given key.
-  // Otherwise, true is returned.
-  //
-  // WARNING: This function could be called on any thread from which the
-  // PathService is used, so a the ProviderFunc MUST BE THREADSAFE.
-  //
-  typedef bool (*ProviderFunc)(int, butil::FilePath*);
-
-  // Call to register a path provider.  You must specify the range "[key_start,
-  // key_end)" of supported path keys.
-  static void RegisterProvider(ProviderFunc provider,
-                               int key_start,
-                               int key_end);
-
-  // Disable internal cache.
-  static void DisableCache();
-
- private:
-  friend class butil::ScopedPathOverride;
-  FRIEND_TEST_ALL_PREFIXES(PathServiceTest, RemoveOverride);
-
-  // Removes an override for a special directory or file. Returns true if there
-  // was an override to remove or false if none was present.
-  // NOTE: This function is intended to be used by tests only!
-  static bool RemoveOverride(int key);
-};
-
-#endif  // BASE_PATH_SERVICE_H_

+ 0 - 189
src/butil/process/internal_linux.cc

@@ -1,189 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/internal_linux.h"
-
-#include <unistd.h>
-
-#include <map>
-#include <string>
-#include <vector>
-
-#include "butil/file_util.h"
-#include "butil/logging.h"
-#include "butil/strings/string_number_conversions.h"
-#include "butil/strings/string_split.h"
-#include "butil/strings/string_util.h"
-#include "butil/threading/thread_restrictions.h"
-#include "butil/time/time.h"
-
-namespace butil {
-namespace internal {
-
-const char kProcDir[] = "/proc";
-
-const char kStatFile[] = "stat";
-
-butil::FilePath GetProcPidDir(pid_t pid) {
-  return butil::FilePath(kProcDir).Append(IntToString(pid));
-}
-
-pid_t ProcDirSlotToPid(const char* d_name) {
-  int i;
-  for (i = 0; i < NAME_MAX && d_name[i]; ++i) {
-    if (!IsAsciiDigit(d_name[i])) {
-      return 0;
-    }
-  }
-  if (i == NAME_MAX)
-    return 0;
-
-  // Read the process's command line.
-  pid_t pid;
-  std::string pid_string(d_name);
-  if (!StringToInt(pid_string, &pid)) {
-    NOTREACHED();
-    return 0;
-  }
-  return pid;
-}
-
-bool ReadProcFile(const FilePath& file, std::string* buffer) {
-  buffer->clear();
-  // Synchronously reading files in /proc is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  if (!ReadFileToString(file, buffer)) {
-    DLOG(WARNING) << "Failed to read " << file.MaybeAsASCII();
-    return false;
-  }
-  return !buffer->empty();
-}
-
-bool ReadProcStats(pid_t pid, std::string* buffer) {
-  FilePath stat_file = internal::GetProcPidDir(pid).Append(kStatFile);
-  return ReadProcFile(stat_file, buffer);
-}
-
-bool ParseProcStats(const std::string& stats_data,
-                    std::vector<std::string>* proc_stats) {
-  // |stats_data| may be empty if the process disappeared somehow.
-  // e.g. http://crbug.com/145811
-  if (stats_data.empty())
-    return false;
-
-  // The stat file is formatted as:
-  // pid (process name) data1 data2 .... dataN
-  // Look for the closing paren by scanning backwards, to avoid being fooled by
-  // processes with ')' in the name.
-  size_t open_parens_idx = stats_data.find(" (");
-  size_t close_parens_idx = stats_data.rfind(") ");
-  if (open_parens_idx == std::string::npos ||
-      close_parens_idx == std::string::npos ||
-      open_parens_idx > close_parens_idx) {
-    DLOG(WARNING) << "Failed to find matched parens in '" << stats_data << "'";
-    NOTREACHED();
-    return false;
-  }
-  open_parens_idx++;
-
-  proc_stats->clear();
-  // PID.
-  proc_stats->push_back(stats_data.substr(0, open_parens_idx));
-  // Process name without parentheses.
-  proc_stats->push_back(
-      stats_data.substr(open_parens_idx + 1,
-                        close_parens_idx - (open_parens_idx + 1)));
-
-  // Split the rest.
-  std::vector<std::string> other_stats;
-  SplitString(stats_data.substr(close_parens_idx + 2), ' ', &other_stats);
-  for (size_t i = 0; i < other_stats.size(); ++i)
-    proc_stats->push_back(other_stats[i]);
-  return true;
-}
-
-typedef std::map<std::string, std::string> ProcStatMap;
-void ParseProcStat(const std::string& contents, ProcStatMap* output) {
-  typedef std::pair<std::string, std::string> StringPair;
-  std::vector<StringPair> key_value_pairs;
-  SplitStringIntoKeyValuePairs(contents, ' ', '\n', &key_value_pairs);
-  for (size_t i = 0; i < key_value_pairs.size(); ++i) {
-    const StringPair& key_value_pair = key_value_pairs[i];
-    output->insert(key_value_pair);
-  }
-}
-
-int64_t GetProcStatsFieldAsInt64(const std::vector<std::string>& proc_stats,
-                               ProcStatsFields field_num) {
-  DCHECK_GE(field_num, VM_PPID);
-  CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
-
-  int64_t value;
-  return StringToInt64(proc_stats[field_num], &value) ? value : 0;
-}
-
-size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
-                                ProcStatsFields field_num) {
-  DCHECK_GE(field_num, VM_PPID);
-  CHECK_LT(static_cast<size_t>(field_num), proc_stats.size());
-
-  size_t value;
-  return StringToSizeT(proc_stats[field_num], &value) ? value : 0;
-}
-
-int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num) {
-  std::string stats_data;
-  if (!ReadProcStats(pid, &stats_data))
-    return 0;
-  std::vector<std::string> proc_stats;
-  if (!ParseProcStats(stats_data, &proc_stats))
-    return 0;
-  return GetProcStatsFieldAsInt64(proc_stats, field_num);
-}
-
-size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
-                                       ProcStatsFields field_num) {
-  std::string stats_data;
-  if (!ReadProcStats(pid, &stats_data))
-    return 0;
-  std::vector<std::string> proc_stats;
-  if (!ParseProcStats(stats_data, &proc_stats))
-    return 0;
-  return GetProcStatsFieldAsSizeT(proc_stats, field_num);
-}
-
-Time GetBootTime() {
-  FilePath path("/proc/stat");
-  std::string contents;
-  if (!ReadProcFile(path, &contents))
-    return Time();
-  ProcStatMap proc_stat;
-  ParseProcStat(contents, &proc_stat);
-  ProcStatMap::const_iterator btime_it = proc_stat.find("btime");
-  if (btime_it == proc_stat.end())
-    return Time();
-  int btime;
-  if (!StringToInt(btime_it->second, &btime))
-    return Time();
-  return Time::FromTimeT(btime);
-}
-
-TimeDelta ClockTicksToTimeDelta(int clock_ticks) {
-  // This queries the /proc-specific scaling factor which is
-  // conceptually the system hertz.  To dump this value on another
-  // system, try
-  //   od -t dL /proc/self/auxv
-  // and look for the number after 17 in the output; mine is
-  //   0000040          17         100           3   134512692
-  // which means the answer is 100.
-  // It may be the case that this value is always 100.
-  static const int kHertz = sysconf(_SC_CLK_TCK);
-
-  return TimeDelta::FromMicroseconds(
-      Time::kMicrosecondsPerSecond * clock_ticks / kHertz);
-}
-
-}  // namespace internal
-}  // namespace butil

+ 0 - 90
src/butil/process/internal_linux.h

@@ -1,90 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains internal routines that are called by other files in
-// butil/process/.
-
-#ifndef BASE_PROCESS_LINUX_INTERNAL_H_
-#define BASE_PROCESS_LINUX_INTERNAL_H_
-
-#include <unistd.h>
-
-#include "butil/files/file_path.h"
-
-namespace butil {
-
-class Time;
-class TimeDelta;
-
-namespace internal {
-
-// "/proc"
-extern const char kProcDir[];
-
-// "stat"
-extern const char kStatFile[];
-
-// Returns a FilePath to "/proc/pid".
-butil::FilePath GetProcPidDir(pid_t pid);
-
-// Take a /proc directory entry named |d_name|, and if it is the directory for
-// a process, convert it to a pid_t.
-// Returns 0 on failure.
-// e.g. /proc/self/ will return 0, whereas /proc/1234 will return 1234.
-pid_t ProcDirSlotToPid(const char* d_name);
-
-// Reads /proc/<pid>/stat into |buffer|. Returns true if the file can be read
-// and is non-empty.
-bool ReadProcStats(pid_t pid, std::string* buffer);
-
-// Takes |stats_data| and populates |proc_stats| with the values split by
-// spaces. Taking into account the 2nd field may, in itself, contain spaces.
-// Returns true if successful.
-bool ParseProcStats(const std::string& stats_data,
-                    std::vector<std::string>* proc_stats);
-
-// Fields from /proc/<pid>/stat, 0-based. See man 5 proc.
-// If the ordering ever changes, carefully review functions that use these
-// values.
-enum ProcStatsFields {
-  VM_COMM           = 1,   // Filename of executable, without parentheses.
-  VM_STATE          = 2,   // Letter indicating the state of the process.
-  VM_PPID           = 3,   // PID of the parent.
-  VM_PGRP           = 4,   // Process group id.
-  VM_UTIME          = 13,  // Time scheduled in user mode in clock ticks.
-  VM_STIME          = 14,  // Time scheduled in kernel mode in clock ticks.
-  VM_NUMTHREADS     = 19,  // Number of threads.
-  VM_STARTTIME      = 21,  // The time the process started in clock ticks.
-  VM_VSIZE          = 22,  // Virtual memory size in bytes.
-  VM_RSS            = 23,  // Resident Set Size in pages.
-};
-
-// Reads the |field_num|th field from |proc_stats|. Returns 0 on failure.
-// This version does not handle the first 3 values, since the first value is
-// simply |pid|, and the next two values are strings.
-int64_t GetProcStatsFieldAsInt64(const std::vector<std::string>& proc_stats,
-                               ProcStatsFields field_num);
-
-// Same as GetProcStatsFieldAsInt64(), but for size_t values.
-size_t GetProcStatsFieldAsSizeT(const std::vector<std::string>& proc_stats,
-                                ProcStatsFields field_num);
-
-// Convenience wrapper around GetProcStatsFieldAsInt64(), ParseProcStats() and
-// ReadProcStats(). See GetProcStatsFieldAsInt64() for details.
-int64_t ReadProcStatsAndGetFieldAsInt64(pid_t pid, ProcStatsFields field_num);
-
-// Same as ReadProcStatsAndGetFieldAsInt64() but for size_t values.
-size_t ReadProcStatsAndGetFieldAsSizeT(pid_t pid,
-                                       ProcStatsFields field_num);
-
-// Returns the time that the OS started. Clock ticks are relative to this.
-Time GetBootTime();
-
-// Converts Linux clock ticks to a wall time delta.
-TimeDelta ClockTicksToTimeDelta(int clock_ticks);
-
-}  // namespace internal
-}  // namespace butil
-
-#endif  // BASE_PROCESS_LINUX_INTERNAL_H_

+ 0 - 26
src/butil/process/kill.cc

@@ -1,26 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/kill.h"
-
-#include "butil/process/process_iterator.h"
-
-namespace butil {
-
-bool KillProcesses(const FilePath::StringType& executable_name,
-                   int exit_code,
-                   const ProcessFilter* filter) {
-  bool result = true;
-  NamedProcessIterator iter(executable_name, filter);
-  while (const ProcessEntry* entry = iter.NextProcessEntry()) {
-#if defined(OS_WIN)
-    result &= KillProcessById(entry->pid(), exit_code, true);
-#else
-    result &= KillProcess(entry->pid(), exit_code, true);
-#endif
-  }
-  return result;
-}
-
-}  // namespace butil

+ 0 - 162
src/butil/process/kill.h

@@ -1,162 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains routines to kill processes and get the exit code and
-// termination status.
-
-#ifndef BASE_PROCESS_KILL_H_
-#define BASE_PROCESS_KILL_H_
-
-#include "butil/files/file_path.h"
-#include "butil/process/process_handle.h"
-#include "butil/time/time.h"
-
-namespace butil {
-
-class ProcessFilter;
-
-// Return status values from GetTerminationStatus.  Don't use these as
-// exit code arguments to KillProcess*(), use platform/application
-// specific values instead.
-enum TerminationStatus {
-  TERMINATION_STATUS_NORMAL_TERMINATION,   // zero exit status
-  TERMINATION_STATUS_ABNORMAL_TERMINATION, // non-zero exit status
-  TERMINATION_STATUS_PROCESS_WAS_KILLED,   // e.g. SIGKILL or task manager kill
-  TERMINATION_STATUS_PROCESS_CRASHED,      // e.g. Segmentation fault
-  TERMINATION_STATUS_STILL_RUNNING,        // child hasn't exited yet
-#if defined(OS_ANDROID)
-  // On Android processes are spawned from the system Zygote and we do not get
-  // the termination status.  We can't know if the termination was a crash or an
-  // oom kill for sure, but we can use status of the strong process bindings as
-  // a hint.
-  TERMINATION_STATUS_OOM_PROTECTED,        // child was protected from oom kill
-#endif
-  TERMINATION_STATUS_MAX_ENUM
-};
-
-// Attempts to kill all the processes on the current machine that were launched
-// from the given executable name, ending them with the given exit code.  If
-// filter is non-null, then only processes selected by the filter are killed.
-// Returns true if all processes were able to be killed off, false if at least
-// one couldn't be killed.
-BASE_EXPORT bool KillProcesses(const FilePath::StringType& executable_name,
-                               int exit_code,
-                               const ProcessFilter* filter);
-
-// Attempts to kill the process identified by the given process
-// entry structure, giving it the specified exit code. If |wait| is true, wait
-// for the process to be actually terminated before returning.
-// Returns true if this is successful, false otherwise.
-BASE_EXPORT bool KillProcess(ProcessHandle process, int exit_code, bool wait);
-
-#if defined(OS_POSIX)
-// Attempts to kill the process group identified by |process_group_id|. Returns
-// true on success.
-BASE_EXPORT bool KillProcessGroup(ProcessHandle process_group_id);
-#endif  // defined(OS_POSIX)
-
-#if defined(OS_WIN)
-BASE_EXPORT bool KillProcessById(ProcessId process_id,
-                                 int exit_code,
-                                 bool wait);
-#endif  // defined(OS_WIN)
-
-// Get the termination status of the process by interpreting the
-// circumstances of the child process' death. |exit_code| is set to
-// the status returned by waitpid() on POSIX, and from
-// GetExitCodeProcess() on Windows.  |exit_code| may be NULL if the
-// caller is not interested in it.  Note that on Linux, this function
-// will only return a useful result the first time it is called after
-// the child exits (because it will reap the child and the information
-// will no longer be available).
-BASE_EXPORT TerminationStatus GetTerminationStatus(ProcessHandle handle,
-                                                   int* exit_code);
-
-#if defined(OS_POSIX)
-// Send a kill signal to the process and then wait for the process to exit
-// and get the termination status.
-//
-// This is used in situations where it is believed that the process is dead
-// or dying (because communication with the child process has been cut).
-// In order to avoid erroneously returning that the process is still running
-// because the kernel is still cleaning it up, this will wait for the process
-// to terminate. In order to avoid the risk of hanging while waiting for the
-// process to terminate, send a SIGKILL to the process before waiting for the
-// termination status.
-//
-// Note that it is not an option to call WaitForExitCode and then
-// GetTerminationStatus as the child will be reaped when WaitForExitCode
-// returns, and this information will be lost.
-//
-BASE_EXPORT TerminationStatus GetKnownDeadTerminationStatus(
-    ProcessHandle handle, int* exit_code);
-#endif  // defined(OS_POSIX)
-
-// Waits for process to exit. On POSIX systems, if the process hasn't been
-// signaled then puts the exit code in |exit_code|; otherwise it's considered
-// a failure. On Windows |exit_code| is always filled. Returns true on success,
-// and closes |handle| in any case.
-BASE_EXPORT bool WaitForExitCode(ProcessHandle handle, int* exit_code);
-
-// Waits for process to exit. If it did exit within |timeout_milliseconds|,
-// then puts the exit code in |exit_code|, and returns true.
-// In POSIX systems, if the process has been signaled then |exit_code| is set
-// to -1. Returns false on failure (the caller is then responsible for closing
-// |handle|).
-// The caller is always responsible for closing the |handle|.
-BASE_EXPORT bool WaitForExitCodeWithTimeout(ProcessHandle handle,
-                                            int* exit_code,
-                                            butil::TimeDelta timeout);
-
-// Wait for all the processes based on the named executable to exit.  If filter
-// is non-null, then only processes selected by the filter are waited on.
-// Returns after all processes have exited or wait_milliseconds have expired.
-// Returns true if all the processes exited, false otherwise.
-BASE_EXPORT bool WaitForProcessesToExit(
-    const FilePath::StringType& executable_name,
-    butil::TimeDelta wait,
-    const ProcessFilter* filter);
-
-// Wait for a single process to exit. Return true if it exited cleanly within
-// the given time limit. On Linux |handle| must be a child process, however
-// on Mac and Windows it can be any process.
-BASE_EXPORT bool WaitForSingleProcess(ProcessHandle handle,
-                                      butil::TimeDelta wait);
-
-// Waits a certain amount of time (can be 0) for all the processes with a given
-// executable name to exit, then kills off any of them that are still around.
-// If filter is non-null, then only processes selected by the filter are waited
-// on.  Killed processes are ended with the given exit code.  Returns false if
-// any processes needed to be killed, true if they all exited cleanly within
-// the wait_milliseconds delay.
-BASE_EXPORT bool CleanupProcesses(const FilePath::StringType& executable_name,
-                                  butil::TimeDelta wait,
-                                  int exit_code,
-                                  const ProcessFilter* filter);
-
-// This method ensures that the specified process eventually terminates, and
-// then it closes the given process handle.
-//
-// It assumes that the process has already been signalled to exit, and it
-// begins by waiting a small amount of time for it to exit.  If the process
-// does not appear to have exited, then this function starts to become
-// aggressive about ensuring that the process terminates.
-//
-// On Linux this method does not block the calling thread.
-// On OS X this method may block for up to 2 seconds.
-//
-// NOTE: The process handle must have been opened with the PROCESS_TERMINATE
-// and SYNCHRONIZE permissions.
-//
-BASE_EXPORT void EnsureProcessTerminated(ProcessHandle process_handle);
-
-#if defined(OS_POSIX) && !defined(OS_MACOSX)
-// The nicer version of EnsureProcessTerminated() that is patient and will
-// wait for |process_handle| to finish and then reap it.
-BASE_EXPORT void EnsureProcessGetsReaped(ProcessHandle process_handle);
-#endif
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_KILL_H_

+ 0 - 172
src/butil/process/kill_mac.cc

@@ -1,172 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/kill.h"
-
-#include <signal.h>
-#include <sys/event.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-
-#include "butil/file_util.h"
-#include "butil/files/scoped_file.h"
-#include "butil/logging.h"
-#include "butil/posix/eintr_wrapper.h"
-
-namespace butil {
-
-namespace {
-
-const int kWaitBeforeKillSeconds = 2;
-
-// Reap |child| process. This call blocks until completion.
-void BlockingReap(pid_t child) {
-  const pid_t result = HANDLE_EINTR(waitpid(child, NULL, 0));
-  if (result == -1) {
-    DPLOG(ERROR) << "waitpid(" << child << ", NULL, 0)";
-  }
-}
-
-// Waits for |timeout| seconds for the given |child| to exit and reap it. If
-// the child doesn't exit within the time specified, kills it.
-//
-// This function takes two approaches: first, it tries to use kqueue to
-// observe when the process exits. kevent can monitor a kqueue with a
-// timeout, so this method is preferred to wait for a specified period of
-// time. Once the kqueue indicates the process has exited, waitpid will reap
-// the exited child. If the kqueue doesn't provide an exit event notification,
-// before the timeout expires, or if the kqueue fails or misbehaves, the
-// process will be mercilessly killed and reaped.
-//
-// A child process passed to this function may be in one of several states:
-// running, terminated and not yet reaped, and (apparently, and unfortunately)
-// terminated and already reaped. Normally, a process will at least have been
-// asked to exit before this function is called, but this is not required.
-// If a process is terminating and unreaped, there may be a window between the
-// time that kqueue will no longer recognize it and when it becomes an actual
-// zombie that a non-blocking (WNOHANG) waitpid can reap. This condition is
-// detected when kqueue indicates that the process is not running and a
-// non-blocking waitpid fails to reap the process but indicates that it is
-// still running. In this event, a blocking attempt to reap the process
-// collects the known-dying child, preventing zombies from congregating.
-//
-// In the event that the kqueue misbehaves entirely, as it might under a
-// EMFILE condition ("too many open files", or out of file descriptors), this
-// function will forcibly kill and reap the child without delay. This
-// eliminates another potential zombie vector. (If you're out of file
-// descriptors, you're probably deep into something else, but that doesn't
-// mean that zombies be allowed to kick you while you're down.)
-//
-// The fact that this function seemingly can be called to wait on a child
-// that's not only already terminated but already reaped is a bit of a
-// problem: a reaped child's pid can be reclaimed and may refer to a distinct
-// process in that case. The fact that this function can seemingly be called
-// to wait on a process that's not even a child is also a problem: kqueue will
-// work in that case, but waitpid won't, and killing a non-child might not be
-// the best approach.
-void WaitForChildToDie(pid_t child, int timeout) {
-  DCHECK(child > 0);
-  DCHECK(timeout > 0);
-
-  // DON'T ADD ANY EARLY RETURNS TO THIS FUNCTION without ensuring that
-  // |child| has been reaped. Specifically, even if a kqueue, kevent, or other
-  // call fails, this function should fall back to the last resort of trying
-  // to kill and reap the process. Not observing this rule will resurrect
-  // zombies.
-
-  int result;
-
-  ScopedFD kq(HANDLE_EINTR(kqueue()));
-  if (!kq.is_valid()) {
-    DPLOG(ERROR) << "kqueue()";
-  } else {
-    struct kevent change = {0};
-    EV_SET(&change, child, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
-    result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
-
-    if (result == -1) {
-      if (errno != ESRCH) {
-        DPLOG(ERROR) << "kevent (setup " << child << ")";
-      } else {
-        // At this point, one of the following has occurred:
-        // 1. The process has died but has not yet been reaped.
-        // 2. The process has died and has already been reaped.
-        // 3. The process is in the process of dying. It's no longer
-        //    kqueueable, but it may not be waitable yet either. Mark calls
-        //    this case the "zombie death race".
-
-        result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
-
-        if (result != 0) {
-          // A positive result indicates case 1. waitpid succeeded and reaped
-          // the child. A result of -1 indicates case 2. The child has already
-          // been reaped. In both of these cases, no further action is
-          // necessary.
-          return;
-        }
-
-        // |result| is 0, indicating case 3. The process will be waitable in
-        // short order. Fall back out of the kqueue code to kill it (for good
-        // measure) and reap it.
-      }
-    } else {
-      // Keep track of the elapsed time to be able to restart kevent if it's
-      // interrupted.
-      TimeDelta remaining_delta = TimeDelta::FromSeconds(timeout);
-      TimeTicks deadline = TimeTicks::Now() + remaining_delta;
-      result = -1;
-      struct kevent event = {0};
-      while (remaining_delta.InMilliseconds() > 0) {
-        const struct timespec remaining_timespec = remaining_delta.ToTimeSpec();
-        result = kevent(kq.get(), NULL, 0, &event, 1, &remaining_timespec);
-        if (result == -1 && errno == EINTR) {
-          remaining_delta = deadline - TimeTicks::Now();
-          result = 0;
-        } else {
-          break;
-        }
-      }
-
-      if (result == -1) {
-        DPLOG(ERROR) << "kevent (wait " << child << ")";
-      } else if (result > 1) {
-        DLOG(ERROR) << "kevent (wait " << child << "): unexpected result "
-                    << result;
-      } else if (result == 1) {
-        if ((event.fflags & NOTE_EXIT) &&
-            (event.ident == static_cast<uintptr_t>(child))) {
-          // The process is dead or dying. This won't block for long, if at
-          // all.
-          BlockingReap(child);
-          return;
-        } else {
-          DLOG(ERROR) << "kevent (wait " << child
-                      << "): unexpected event: fflags=" << event.fflags
-                      << ", ident=" << event.ident;
-        }
-      }
-    }
-  }
-
-  // The child is still alive, or is very freshly dead. Be sure by sending it
-  // a signal. This is safe even if it's freshly dead, because it will be a
-  // zombie (or on the way to zombiedom) and kill will return 0 even if the
-  // signal is not delivered to a live process.
-  result = kill(child, SIGKILL);
-  if (result == -1) {
-    DPLOG(ERROR) << "kill(" << child << ", SIGKILL)";
-  } else {
-    // The child is definitely on the way out now. BlockingReap won't need to
-    // wait for long, if at all.
-    BlockingReap(child);
-  }
-}
-
-}  // namespace
-
-void EnsureProcessTerminated(ProcessHandle process) {
-  WaitForChildToDie(process, kWaitBeforeKillSeconds);
-}
-
-}  // namespace butil

+ 0 - 482
src/butil/process/kill_posix.cc

@@ -1,482 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/kill.h"
-
-#include <signal.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include "butil/file_util.h"
-#include "butil/files/scoped_file.h"
-#include "butil/logging.h"
-#include "butil/posix/eintr_wrapper.h"
-#include "butil/process/process_iterator.h"
-#include "butil/synchronization/waitable_event.h"
-#include "butil/third_party/dynamic_annotations/dynamic_annotations.h"
-#include "butil/threading/platform_thread.h"
-
-namespace butil {
-
-namespace {
-
-bool WaitpidWithTimeout(ProcessHandle handle,
-                        int* status,
-                        butil::TimeDelta wait) {
-  // This POSIX version of this function only guarantees that we wait no less
-  // than |wait| for the process to exit.  The child process may
-  // exit sometime before the timeout has ended but we may still block for up
-  // to 256 milliseconds after the fact.
-  //
-  // waitpid() has no direct support on POSIX for specifying a timeout, you can
-  // either ask it to block indefinitely or return immediately (WNOHANG).
-  // When a child process terminates a SIGCHLD signal is sent to the parent.
-  // Catching this signal would involve installing a signal handler which may
-  // affect other parts of the application and would be difficult to debug.
-  //
-  // Our strategy is to call waitpid() once up front to check if the process
-  // has already exited, otherwise to loop for |wait|, sleeping for
-  // at most 256 milliseconds each time using usleep() and then calling
-  // waitpid().  The amount of time we sleep starts out at 1 milliseconds, and
-  // we double it every 4 sleep cycles.
-  //
-  // usleep() is speced to exit if a signal is received for which a handler
-  // has been installed.  This means that when a SIGCHLD is sent, it will exit
-  // depending on behavior external to this function.
-  //
-  // This function is used primarily for unit tests, if we want to use it in
-  // the application itself it would probably be best to examine other routes.
-
-  if (wait.InMilliseconds() == butil::kNoTimeout) {
-    return HANDLE_EINTR(waitpid(handle, status, 0)) > 0;
-  }
-
-  pid_t ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
-  static const int64_t kMaxSleepInMicroseconds = 1 << 18;  // ~256 milliseconds.
-  int64_t max_sleep_time_usecs = 1 << 10;  // ~1 milliseconds.
-  int64_t double_sleep_time = 0;
-
-  // If the process hasn't exited yet, then sleep and try again.
-  TimeTicks wakeup_time = TimeTicks::Now() + wait;
-  while (ret_pid == 0) {
-    TimeTicks now = TimeTicks::Now();
-    if (now > wakeup_time)
-      break;
-    // Guaranteed to be non-negative!
-    int64_t sleep_time_usecs = (wakeup_time - now).InMicroseconds();
-    // Sleep for a bit while we wait for the process to finish.
-    if (sleep_time_usecs > max_sleep_time_usecs)
-      sleep_time_usecs = max_sleep_time_usecs;
-
-    // usleep() will return 0 and set errno to EINTR on receipt of a signal
-    // such as SIGCHLD.
-    usleep(sleep_time_usecs);
-    ret_pid = HANDLE_EINTR(waitpid(handle, status, WNOHANG));
-
-    if ((max_sleep_time_usecs < kMaxSleepInMicroseconds) &&
-        (double_sleep_time++ % 4 == 0)) {
-      max_sleep_time_usecs *= 2;
-    }
-  }
-
-  return ret_pid > 0;
-}
-
-TerminationStatus GetTerminationStatusImpl(ProcessHandle handle,
-                                           bool can_block,
-                                           int* exit_code) {
-  int status = 0;
-  const pid_t result = HANDLE_EINTR(waitpid(handle, &status,
-                                            can_block ? 0 : WNOHANG));
-  if (result == -1) {
-    DPLOG(ERROR) << "waitpid(" << handle << ")";
-    if (exit_code)
-      *exit_code = 0;
-    return TERMINATION_STATUS_NORMAL_TERMINATION;
-  } else if (result == 0) {
-    // the child hasn't exited yet.
-    if (exit_code)
-      *exit_code = 0;
-    return TERMINATION_STATUS_STILL_RUNNING;
-  }
-
-  if (exit_code)
-    *exit_code = status;
-
-  if (WIFSIGNALED(status)) {
-    switch (WTERMSIG(status)) {
-      case SIGABRT:
-      case SIGBUS:
-      case SIGFPE:
-      case SIGILL:
-      case SIGSEGV:
-        return TERMINATION_STATUS_PROCESS_CRASHED;
-      case SIGINT:
-      case SIGKILL:
-      case SIGTERM:
-        return TERMINATION_STATUS_PROCESS_WAS_KILLED;
-      default:
-        break;
-    }
-  }
-
-  if (WIFEXITED(status) && WEXITSTATUS(status) != 0)
-    return TERMINATION_STATUS_ABNORMAL_TERMINATION;
-
-  return TERMINATION_STATUS_NORMAL_TERMINATION;
-}
-
-}  // namespace
-
-// Attempts to kill the process identified by the given process
-// entry structure.  Ignores specified exit_code; posix can't force that.
-// Returns true if this is successful, false otherwise.
-bool KillProcess(ProcessHandle process_id, int exit_code, bool wait) {
-  DCHECK_GT(process_id, 1) << " tried to kill invalid process_id";
-  if (process_id <= 1)
-    return false;
-  bool result = kill(process_id, SIGTERM) == 0;
-  if (result && wait) {
-    int tries = 60;
-
-    if (RunningOnValgrind()) {
-      // Wait for some extra time when running under Valgrind since the child
-      // processes may take some time doing leak checking.
-      tries *= 2;
-    }
-
-    unsigned sleep_ms = 4;
-
-    // The process may not end immediately due to pending I/O
-    bool exited = false;
-    while (tries-- > 0) {
-      pid_t pid = HANDLE_EINTR(waitpid(process_id, NULL, WNOHANG));
-      if (pid == process_id) {
-        exited = true;
-        break;
-      }
-      if (pid == -1) {
-        if (errno == ECHILD) {
-          // The wait may fail with ECHILD if another process also waited for
-          // the same pid, causing the process state to get cleaned up.
-          exited = true;
-          break;
-        }
-        DPLOG(ERROR) << "Error waiting for process " << process_id;
-      }
-
-      usleep(sleep_ms * 1000);
-      const unsigned kMaxSleepMs = 1000;
-      if (sleep_ms < kMaxSleepMs)
-        sleep_ms *= 2;
-    }
-
-    // If we're waiting and the child hasn't died by now, force it
-    // with a SIGKILL.
-    if (!exited)
-      result = kill(process_id, SIGKILL) == 0;
-  }
-
-  if (!result)
-    DPLOG(ERROR) << "Unable to terminate process " << process_id;
-
-  return result;
-}
-
-bool KillProcessGroup(ProcessHandle process_group_id) {
-  bool result = kill(-1 * process_group_id, SIGKILL) == 0;
-  if (!result)
-    DPLOG(ERROR) << "Unable to terminate process group " << process_group_id;
-  return result;
-}
-
-TerminationStatus GetTerminationStatus(ProcessHandle handle, int* exit_code) {
-  return GetTerminationStatusImpl(handle, false /* can_block */, exit_code);
-}
-
-TerminationStatus GetKnownDeadTerminationStatus(ProcessHandle handle,
-                                                int* exit_code) {
-  bool result = kill(handle, SIGKILL) == 0;
-
-  if (!result)
-    DPLOG(ERROR) << "Unable to terminate process " << handle;
-
-  return GetTerminationStatusImpl(handle, true /* can_block */, exit_code);
-}
-
-bool WaitForExitCode(ProcessHandle handle, int* exit_code) {
-  int status;
-  if (HANDLE_EINTR(waitpid(handle, &status, 0)) == -1) {
-    NOTREACHED();
-    return false;
-  }
-
-  if (WIFEXITED(status)) {
-    *exit_code = WEXITSTATUS(status);
-    return true;
-  }
-
-  // If it didn't exit cleanly, it must have been signaled.
-  DCHECK(WIFSIGNALED(status));
-  return false;
-}
-
-bool WaitForExitCodeWithTimeout(ProcessHandle handle,
-                                int* exit_code,
-                                butil::TimeDelta timeout) {
-  int status;
-  if (!WaitpidWithTimeout(handle, &status, timeout))
-    return false;
-  if (WIFSIGNALED(status)) {
-    *exit_code = -1;
-    return true;
-  }
-  if (WIFEXITED(status)) {
-    *exit_code = WEXITSTATUS(status);
-    return true;
-  }
-  return false;
-}
-
-bool WaitForProcessesToExit(const FilePath::StringType& executable_name,
-                            butil::TimeDelta wait,
-                            const ProcessFilter* filter) {
-  bool result = false;
-
-  // TODO(port): This is inefficient, but works if there are multiple procs.
-  // TODO(port): use waitpid to avoid leaving zombies around
-
-  butil::TimeTicks end_time = butil::TimeTicks::Now() + wait;
-  do {
-    NamedProcessIterator iter(executable_name, filter);
-    if (!iter.NextProcessEntry()) {
-      result = true;
-      break;
-    }
-    butil::PlatformThread::Sleep(butil::TimeDelta::FromMilliseconds(100));
-  } while ((end_time - butil::TimeTicks::Now()) > butil::TimeDelta());
-
-  return result;
-}
-
-#if defined(OS_MACOSX)
-// Using kqueue on Mac so that we can wait on non-child processes.
-// We can't use kqueues on child processes because we need to reap
-// our own children using wait.
-static bool WaitForSingleNonChildProcess(ProcessHandle handle,
-                                         butil::TimeDelta wait) {
-  DCHECK_GT(handle, 0);
-  DCHECK(wait.InMilliseconds() == butil::kNoTimeout || wait > butil::TimeDelta());
-
-  ScopedFD kq(kqueue());
-  if (!kq.is_valid()) {
-    DPLOG(ERROR) << "kqueue";
-    return false;
-  }
-
-  struct kevent change = {0};
-  EV_SET(&change, handle, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL);
-  int result = HANDLE_EINTR(kevent(kq.get(), &change, 1, NULL, 0, NULL));
-  if (result == -1) {
-    if (errno == ESRCH) {
-      // If the process wasn't found, it must be dead.
-      return true;
-    }
-
-    DPLOG(ERROR) << "kevent (setup " << handle << ")";
-    return false;
-  }
-
-  // Keep track of the elapsed time to be able to restart kevent if it's
-  // interrupted.
-  bool wait_forever = wait.InMilliseconds() == butil::kNoTimeout;
-  butil::TimeDelta remaining_delta;
-  butil::TimeTicks deadline;
-  if (!wait_forever) {
-    remaining_delta = wait;
-    deadline = butil::TimeTicks::Now() + remaining_delta;
-  }
-
-  result = -1;
-  struct kevent event = {0};
-
-  while (wait_forever || remaining_delta > butil::TimeDelta()) {
-    struct timespec remaining_timespec;
-    struct timespec* remaining_timespec_ptr;
-    if (wait_forever) {
-      remaining_timespec_ptr = NULL;
-    } else {
-      remaining_timespec = remaining_delta.ToTimeSpec();
-      remaining_timespec_ptr = &remaining_timespec;
-    }
-
-    result = kevent(kq.get(), NULL, 0, &event, 1, remaining_timespec_ptr);
-
-    if (result == -1 && errno == EINTR) {
-      if (!wait_forever) {
-        remaining_delta = deadline - butil::TimeTicks::Now();
-      }
-      result = 0;
-    } else {
-      break;
-    }
-  }
-
-  if (result < 0) {
-    DPLOG(ERROR) << "kevent (wait " << handle << ")";
-    return false;
-  } else if (result > 1) {
-    DLOG(ERROR) << "kevent (wait " << handle << "): unexpected result "
-                << result;
-    return false;
-  } else if (result == 0) {
-    // Timed out.
-    return false;
-  }
-
-  DCHECK_EQ(result, 1);
-
-  if (event.filter != EVFILT_PROC ||
-      (event.fflags & NOTE_EXIT) == 0 ||
-      event.ident != static_cast<uintptr_t>(handle)) {
-    DLOG(ERROR) << "kevent (wait " << handle
-                << "): unexpected event: filter=" << event.filter
-                << ", fflags=" << event.fflags
-                << ", ident=" << event.ident;
-    return false;
-  }
-
-  return true;
-}
-#endif  // OS_MACOSX
-
-bool WaitForSingleProcess(ProcessHandle handle, butil::TimeDelta wait) {
-  ProcessHandle parent_pid = GetParentProcessId(handle);
-  ProcessHandle our_pid = Process::Current().handle();
-  if (parent_pid != our_pid) {
-#if defined(OS_MACOSX)
-    // On Mac we can wait on non child processes.
-    return WaitForSingleNonChildProcess(handle, wait);
-#else
-    // Currently on Linux we can't handle non child processes.
-    NOTIMPLEMENTED();
-#endif  // OS_MACOSX
-  }
-
-  int status;
-  if (!WaitpidWithTimeout(handle, &status, wait))
-    return false;
-  return WIFEXITED(status);
-}
-
-bool CleanupProcesses(const FilePath::StringType& executable_name,
-                      butil::TimeDelta wait,
-                      int exit_code,
-                      const ProcessFilter* filter) {
-  bool exited_cleanly = WaitForProcessesToExit(executable_name, wait, filter);
-  if (!exited_cleanly)
-    KillProcesses(executable_name, exit_code, filter);
-  return exited_cleanly;
-}
-
-#if !defined(OS_MACOSX)
-
-namespace {
-
-// Return true if the given child is dead. This will also reap the process.
-// Doesn't block.
-static bool IsChildDead(pid_t child) {
-  const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
-  if (result == -1) {
-    DPLOG(ERROR) << "waitpid(" << child << ")";
-    NOTREACHED();
-  } else if (result > 0) {
-    // The child has died.
-    return true;
-  }
-
-  return false;
-}
-
-// A thread class which waits for the given child to exit and reaps it.
-// If the child doesn't exit within a couple of seconds, kill it.
-class BackgroundReaper : public PlatformThread::Delegate {
- public:
-  BackgroundReaper(pid_t child, unsigned timeout)
-      : child_(child),
-        timeout_(timeout) {
-  }
-
-  // Overridden from PlatformThread::Delegate:
-  virtual void ThreadMain() OVERRIDE {
-    WaitForChildToDie();
-    delete this;
-  }
-
-  void WaitForChildToDie() {
-    // Wait forever case.
-    if (timeout_ == 0) {
-      pid_t r = HANDLE_EINTR(waitpid(child_, NULL, 0));
-      if (r != child_) {
-        DPLOG(ERROR) << "While waiting for " << child_
-                     << " to terminate, we got the following result: " << r;
-      }
-      return;
-    }
-
-    // There's no good way to wait for a specific child to exit in a timed
-    // fashion. (No kqueue on Linux), so we just loop and sleep.
-
-    // Wait for 2 * timeout_ 500 milliseconds intervals.
-    for (unsigned i = 0; i < 2 * timeout_; ++i) {
-      PlatformThread::Sleep(TimeDelta::FromMilliseconds(500));
-      if (IsChildDead(child_))
-        return;
-    }
-
-    if (kill(child_, SIGKILL) == 0) {
-      // SIGKILL is uncatchable. Since the signal was delivered, we can
-      // just wait for the process to die now in a blocking manner.
-      if (HANDLE_EINTR(waitpid(child_, NULL, 0)) < 0)
-        DPLOG(WARNING) << "waitpid";
-    } else {
-      DLOG(ERROR) << "While waiting for " << child_ << " to terminate we"
-                  << " failed to deliver a SIGKILL signal (" << errno << ").";
-    }
-  }
-
- private:
-  const pid_t child_;
-  // Number of seconds to wait, if 0 then wait forever and do not attempt to
-  // kill |child_|.
-  const unsigned timeout_;
-
-  DISALLOW_COPY_AND_ASSIGN(BackgroundReaper);
-};
-
-}  // namespace
-
-void EnsureProcessTerminated(ProcessHandle process) {
-  // If the child is already dead, then there's nothing to do.
-  if (IsChildDead(process))
-    return;
-
-  const unsigned timeout = 2;  // seconds
-  BackgroundReaper* reaper = new BackgroundReaper(process, timeout);
-  PlatformThread::CreateNonJoinable(0, reaper);
-}
-
-void EnsureProcessGetsReaped(ProcessHandle process) {
-  // If the child is already dead, then there's nothing to do.
-  if (IsChildDead(process))
-    return;
-
-  BackgroundReaper* reaper = new BackgroundReaper(process, 0);
-  PlatformThread::CreateNonJoinable(0, reaper);
-}
-
-#endif  // !defined(OS_MACOSX)
-
-}  // namespace butil

+ 0 - 52
src/butil/process/launch.cc

@@ -1,52 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/launch.h"
-
-namespace butil {
-
-LaunchOptions::LaunchOptions()
-    : wait(false),
-#if defined(OS_WIN)
-      start_hidden(false),
-      handles_to_inherit(NULL),
-      inherit_handles(false),
-      as_user(NULL),
-      empty_desktop_name(false),
-      job_handle(NULL),
-      stdin_handle(NULL),
-      stdout_handle(NULL),
-      stderr_handle(NULL),
-      force_breakaway_from_job_(false)
-#else
-      clear_environ(false),
-      fds_to_remap(NULL),
-      maximize_rlimits(NULL),
-      new_process_group(false)
-#if defined(OS_LINUX)
-      , clone_flags(0)
-      , allow_new_privs(false)
-#endif  // OS_LINUX
-#if defined(OS_CHROMEOS)
-      , ctrl_terminal_fd(-1)
-#endif  // OS_CHROMEOS
-#endif  // !defined(OS_WIN)
-    {
-}
-
-LaunchOptions::~LaunchOptions() {
-}
-
-LaunchOptions LaunchOptionsForTest() {
-  LaunchOptions options;
-#if defined(OS_LINUX)
-  // To prevent accidental privilege sharing to an untrusted child, processes
-  // are started with PR_SET_NO_NEW_PRIVS. Do not set that here, since this
-  // new child will be used for testing only.
-  options.allow_new_privs = true;
-#endif
-  return options;
-}
-
-}  // namespace butil

+ 0 - 275
src/butil/process/launch.h

@@ -1,275 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains functions for launching subprocesses.
-
-#ifndef BASE_PROCESS_LAUNCH_H_
-#define BASE_PROCESS_LAUNCH_H_
-
-#include <string>
-#include <utility>
-#include <vector>
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/environment.h"
-#include "butil/process/process_handle.h"
-#include "butil/strings/string_piece.h"
-
-#if defined(OS_POSIX)
-#include "butil/posix/file_descriptor_shuffle.h"
-#elif defined(OS_WIN)
-#include <windows.h>
-#include "butil/win/scoped_handle.h"
-#endif
-
-namespace butil {
-
-class CommandLine;
-
-#if defined(OS_WIN)
-typedef std::vector<HANDLE> HandlesToInheritVector;
-#endif
-// TODO(viettrungluu): Only define this on POSIX?
-typedef std::vector<std::pair<int, int> > FileHandleMappingVector;
-
-// Options for launching a subprocess that are passed to LaunchProcess().
-// The default constructor constructs the object with default options.
-struct BASE_EXPORT LaunchOptions {
-  LaunchOptions();
-  ~LaunchOptions();
-
-  // If true, wait for the process to complete.
-  bool wait;
-
-#if defined(OS_WIN)
-  bool start_hidden;
-
-  // If non-null, inherit exactly the list of handles in this vector (these
-  // handles must be inheritable). This is only supported on Vista and higher.
-  HandlesToInheritVector* handles_to_inherit;
-
-  // If true, the new process inherits handles from the parent. In production
-  // code this flag should be used only when running short-lived, trusted
-  // binaries, because open handles from other libraries and subsystems will
-  // leak to the child process, causing errors such as open socket hangs.
-  // Note: If |handles_to_inherit| is non-null, this flag is ignored and only
-  // those handles will be inherited (on Vista and higher).
-  bool inherit_handles;
-
-  // If non-null, runs as if the user represented by the token had launched it.
-  // Whether the application is visible on the interactive desktop depends on
-  // the token belonging to an interactive logon session.
-  //
-  // To avoid hard to diagnose problems, when specified this loads the
-  // environment variables associated with the user and if this operation fails
-  // the entire call fails as well.
-  UserTokenHandle as_user;
-
-  // If true, use an empty string for the desktop name.
-  bool empty_desktop_name;
-
-  // If non-null, launches the application in that job object. The process will
-  // be terminated immediately and LaunchProcess() will fail if assignment to
-  // the job object fails.
-  HANDLE job_handle;
-
-  // Handles for the redirection of stdin, stdout and stderr. The handles must
-  // be inheritable. Caller should either set all three of them or none (i.e.
-  // there is no way to redirect stderr without redirecting stdin). The
-  // |inherit_handles| flag must be set to true when redirecting stdio stream.
-  HANDLE stdin_handle;
-  HANDLE stdout_handle;
-  HANDLE stderr_handle;
-
-  // If set to true, ensures that the child process is launched with the
-  // CREATE_BREAKAWAY_FROM_JOB flag which allows it to breakout of the parent
-  // job if any.
-  bool force_breakaway_from_job_;
-#else
-  // Set/unset environment variables. These are applied on top of the parent
-  // process environment.  Empty (the default) means to inherit the same
-  // environment. See AlterEnvironment().
-  EnvironmentMap environ;
-
-  // Clear the environment for the new process before processing changes from
-  // |environ|.
-  bool clear_environ;
-
-  // If non-null, remap file descriptors according to the mapping of
-  // src fd->dest fd to propagate FDs into the child process.
-  // This pointer is owned by the caller and must live through the
-  // call to LaunchProcess().
-  const FileHandleMappingVector* fds_to_remap;
-
-  // Each element is an RLIMIT_* constant that should be raised to its
-  // rlim_max.  This pointer is owned by the caller and must live through
-  // the call to LaunchProcess().
-  const std::vector<int>* maximize_rlimits;
-
-  // If true, start the process in a new process group, instead of
-  // inheriting the parent's process group.  The pgid of the child process
-  // will be the same as its pid.
-  bool new_process_group;
-
-#if defined(OS_LINUX)
-  // If non-zero, start the process using clone(), using flags as provided.
-  int clone_flags;
-
-  // By default, child processes will have the PR_SET_NO_NEW_PRIVS bit set. If
-  // true, then this bit will not be set in the new child process.
-  bool allow_new_privs;
-#endif  // defined(OS_LINUX)
-
-#if defined(OS_CHROMEOS)
-  // If non-negative, the specified file descriptor will be set as the launched
-  // process' controlling terminal.
-  int ctrl_terminal_fd;
-#endif  // defined(OS_CHROMEOS)
-
-#if defined(OS_MACOSX)
-  // If this name is non-empty, the new child, after fork() but before exec(),
-  // will look up this server name in the bootstrap namespace. The resulting
-  // service port will be replaced as the bootstrap port in the child. Because
-  // the process's IPC space is cleared on exec(), any rights to the old
-  // bootstrap port will not be transferred to the new process.
-  std::string replacement_bootstrap_name;
-#endif
-
-#endif  // !defined(OS_WIN)
-};
-
-// Launch a process via the command line |cmdline|.
-// See the documentation of LaunchOptions for details on |options|.
-//
-// Returns true upon success.
-//
-// Upon success, if |process_handle| is non-null, it will be filled in with the
-// handle of the launched process.  NOTE: In this case, the caller is
-// responsible for closing the handle so that it doesn't leak!
-// Otherwise, the process handle will be implicitly closed.
-//
-// Unix-specific notes:
-// - All file descriptors open in the parent process will be closed in the
-//   child process except for any preserved by options::fds_to_remap, and
-//   stdin, stdout, and stderr. If not remapped by options::fds_to_remap,
-//   stdin is reopened as /dev/null, and the child is allowed to inherit its
-//   parent's stdout and stderr.
-// - If the first argument on the command line does not contain a slash,
-//   PATH will be searched.  (See man execvp.)
-BASE_EXPORT bool LaunchProcess(const CommandLine& cmdline,
-                               const LaunchOptions& options,
-                               ProcessHandle* process_handle);
-
-#if defined(OS_WIN)
-// Windows-specific LaunchProcess that takes the command line as a
-// string.  Useful for situations where you need to control the
-// command line arguments directly, but prefer the CommandLine version
-// if launching Chrome itself.
-//
-// The first command line argument should be the path to the process,
-// and don't forget to quote it.
-//
-// Example (including literal quotes)
-//  cmdline = "c:\windows\explorer.exe" -foo "c:\bar\"
-BASE_EXPORT bool LaunchProcess(const string16& cmdline,
-                               const LaunchOptions& options,
-                               win::ScopedHandle* process_handle);
-
-// Launches a process with elevated privileges.  This does not behave exactly
-// like LaunchProcess as it uses ShellExecuteEx instead of CreateProcess to
-// create the process.  This means the process will have elevated privileges
-// and thus some common operations like OpenProcess will fail. The process will
-// be available through the |process_handle| argument.  Currently the only
-// supported LaunchOptions are |start_hidden| and |wait|.
-BASE_EXPORT bool LaunchElevatedProcess(const CommandLine& cmdline,
-                                       const LaunchOptions& options,
-                                       ProcessHandle* process_handle);
-
-#elif defined(OS_POSIX)
-// A POSIX-specific version of LaunchProcess that takes an argv array
-// instead of a CommandLine.  Useful for situations where you need to
-// control the command line arguments directly, but prefer the
-// CommandLine version if launching Chrome itself.
-BASE_EXPORT bool LaunchProcess(const std::vector<std::string>& argv,
-                               const LaunchOptions& options,
-                               ProcessHandle* process_handle);
-
-// Close all file descriptors, except those which are a destination in the
-// given multimap. Only call this function in a child process where you know
-// that there aren't any other threads.
-BASE_EXPORT void CloseSuperfluousFds(const InjectiveMultimap& saved_map);
-#endif  // defined(OS_POSIX)
-
-#if defined(OS_WIN)
-// Set |job_object|'s JOBOBJECT_EXTENDED_LIMIT_INFORMATION
-// BasicLimitInformation.LimitFlags to |limit_flags|.
-BASE_EXPORT bool SetJobObjectLimitFlags(HANDLE job_object, DWORD limit_flags);
-
-// Output multi-process printf, cout, cerr, etc to the cmd.exe console that ran
-// chrome. This is not thread-safe: only call from main thread.
-BASE_EXPORT void RouteStdioToConsole();
-#endif  // defined(OS_WIN)
-
-// Executes the application specified by |cl| and wait for it to exit. Stores
-// the output (stdout) in |output|. Redirects stderr to /dev/null. Returns true
-// on success (application launched and exited cleanly, with exit code
-// indicating success).
-BASE_EXPORT bool GetAppOutput(const CommandLine& cl, std::string* output);
-
-#if defined(OS_WIN)
-// A Windows-specific version of GetAppOutput that takes a command line string
-// instead of a CommandLine object. Useful for situations where you need to
-// control the command line arguments directly.
-BASE_EXPORT bool GetAppOutput(const StringPiece16& cl, std::string* output);
-#endif
-
-#if defined(OS_POSIX)
-// A POSIX-specific version of GetAppOutput that takes an argv array
-// instead of a CommandLine.  Useful for situations where you need to
-// control the command line arguments directly.
-BASE_EXPORT bool GetAppOutput(const std::vector<std::string>& argv,
-                              std::string* output);
-
-// A restricted version of |GetAppOutput()| which (a) clears the environment,
-// and (b) stores at most |max_output| bytes; also, it doesn't search the path
-// for the command.
-BASE_EXPORT bool GetAppOutputRestricted(const CommandLine& cl,
-                                        std::string* output, size_t max_output);
-
-// A version of |GetAppOutput()| which also returns the exit code of the
-// executed command. Returns true if the application runs and exits cleanly. If
-// this is the case the exit code of the application is available in
-// |*exit_code|.
-BASE_EXPORT bool GetAppOutputWithExitCode(const CommandLine& cl,
-                                          std::string* output, int* exit_code);
-#endif  // defined(OS_POSIX)
-
-// If supported on the platform, and the user has sufficent rights, increase
-// the current process's scheduling priority to a high priority.
-BASE_EXPORT void RaiseProcessToHighPriority();
-
-#if defined(OS_MACOSX)
-// Restore the default exception handler, setting it to Apple Crash Reporter
-// (ReportCrash).  When forking and execing a new process, the child will
-// inherit the parent's exception ports, which may be set to the Breakpad
-// instance running inside the parent.  The parent's Breakpad instance should
-// not handle the child's exceptions.  Calling RestoreDefaultExceptionHandler
-// in the child after forking will restore the standard exception handler.
-// See http://crbug.com/20371/ for more details.
-void RestoreDefaultExceptionHandler();
-
-// Look up the bootstrap server named |replacement_bootstrap_name| via the
-// current |bootstrap_port|. Then replace the task's bootstrap port with the
-// received right.
-void ReplaceBootstrapPort(const std::string& replacement_bootstrap_name);
-#endif  // defined(OS_MACOSX)
-
-// Creates a LaunchOptions object suitable for launching processes in a test
-// binary. This should not be called in production/released code.
-BASE_EXPORT LaunchOptions LaunchOptionsForTest();
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_LAUNCH_H_

+ 0 - 48
src/butil/process/launch_mac.cc

@@ -1,48 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/launch.h"
-
-#include <mach/mach.h>
-#include <servers/bootstrap.h>
-
-#include "butil/logging.h"
-
-namespace butil {
-
-void RestoreDefaultExceptionHandler() {
-  // This function is tailored to remove the Breakpad exception handler.
-  // exception_mask matches s_exception_mask in
-  // breakpad/src/client/mac/handler/exception_handler.cc
-  const exception_mask_t exception_mask = EXC_MASK_BAD_ACCESS |
-                                          EXC_MASK_BAD_INSTRUCTION |
-                                          EXC_MASK_ARITHMETIC |
-                                          EXC_MASK_BREAKPOINT;
-
-  // Setting the exception port to MACH_PORT_NULL may not be entirely
-  // kosher to restore the default exception handler, but in practice,
-  // it results in the exception port being set to Apple Crash Reporter,
-  // the desired behavior.
-  task_set_exception_ports(mach_task_self(), exception_mask, MACH_PORT_NULL,
-                           EXCEPTION_DEFAULT, THREAD_STATE_NONE);
-}
-
-void ReplaceBootstrapPort(const std::string& new_bootstrap_name) {
-  // This function is called between fork() and exec(), so it should take care
-  // to run properly in that situation.
-
-  mach_port_t port = MACH_PORT_NULL;
-  kern_return_t kr = bootstrap_look_up(bootstrap_port,
-      new_bootstrap_name.c_str(), &port);
-  if (kr != KERN_SUCCESS) {
-    RAW_LOG(FATAL, "Failed to look up replacement bootstrap port.");
-  }
-
-  kr = task_set_bootstrap_port(mach_task_self(), port);
-  if (kr != KERN_SUCCESS) {
-    RAW_LOG(FATAL, "Failed to replace bootstrap port.");
-  }
-}
-
-}  // namespace butil

+ 0 - 665
src/butil/process/launch_posix.cc

@@ -1,665 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/launch.h"
-
-#include <dirent.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <sys/resource.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <sys/wait.h>
-#include <unistd.h>
-
-#include <iterator>
-#include <limits>
-#include <set>
-
-#include "butil/allocator/type_profiler_control.h"
-#include "butil/command_line.h"
-#include "butil/compiler_specific.h"
-#include "butil/debug/debugger.h"
-#include "butil/debug/stack_trace.h"
-#include "butil/file_util.h"
-#include "butil/files/dir_reader_posix.h"
-#include "butil/files/scoped_file.h"
-#include "butil/logging.h"
-#include "butil/memory/scoped_ptr.h"
-#include "butil/posix/eintr_wrapper.h"
-#include "butil/process/kill.h"
-#include "butil/process/process_metrics.h"
-#include "butil/strings/stringprintf.h"
-#include "butil/synchronization/waitable_event.h"
-#include "butil/third_party/dynamic_annotations/dynamic_annotations.h"
-#include "butil/threading/platform_thread.h"
-#include "butil/threading/thread_restrictions.h"
-
-#if defined(OS_LINUX)
-#include <sys/prctl.h>
-#endif
-
-#if defined(OS_CHROMEOS)
-#include <sys/ioctl.h>
-#endif
-
-#if defined(OS_FREEBSD)
-#include <sys/event.h>
-#include <sys/ucontext.h>
-#endif
-
-#if defined(OS_MACOSX)
-#include <crt_externs.h>
-#include <sys/event.h>
-#else
-extern char** environ;
-#endif
-
-namespace butil {
-
-namespace {
-
-// Get the process's "environment" (i.e. the thing that setenv/getenv
-// work with).
-char** GetEnvironment() {
-#if defined(OS_MACOSX)
-  return *_NSGetEnviron();
-#else
-  return environ;
-#endif
-}
-
-// Set the process's "environment" (i.e. the thing that setenv/getenv
-// work with).
-void SetEnvironment(char** env) {
-#if defined(OS_MACOSX)
-  *_NSGetEnviron() = env;
-#else
-  environ = env;
-#endif
-}
-
-// Set the calling thread's signal mask to new_sigmask and return
-// the previous signal mask.
-sigset_t SetSignalMask(const sigset_t& new_sigmask) {
-  sigset_t old_sigmask;
-#if defined(OS_ANDROID)
-  // POSIX says pthread_sigmask() must be used in multi-threaded processes,
-  // but Android's pthread_sigmask() was broken until 4.1:
-  // https://code.google.com/p/android/issues/detail?id=15337
-  // http://stackoverflow.com/questions/13777109/pthread-sigmask-on-android-not-working
-  RAW_CHECK(sigprocmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0, "");
-#else
-  RAW_CHECK(pthread_sigmask(SIG_SETMASK, &new_sigmask, &old_sigmask) == 0, "");
-#endif
-  return old_sigmask;
-}
-
-#if !defined(OS_LINUX) || \
-    (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
-void ResetChildSignalHandlersToDefaults() {
-  // The previous signal handlers are likely to be meaningless in the child's
-  // context so we reset them to the defaults for now. http://crbug.com/44953
-  // These signal handlers are set up at least in browser_main_posix.cc:
-  // BrowserMainPartsPosix::PreEarlyInitialization and stack_trace_posix.cc:
-  // EnableInProcessStackDumping.
-  signal(SIGHUP, SIG_DFL);
-  signal(SIGINT, SIG_DFL);
-  signal(SIGILL, SIG_DFL);
-  signal(SIGABRT, SIG_DFL);
-  signal(SIGFPE, SIG_DFL);
-  signal(SIGBUS, SIG_DFL);
-  signal(SIGSEGV, SIG_DFL);
-  signal(SIGSYS, SIG_DFL);
-  signal(SIGTERM, SIG_DFL);
-}
-
-#else
-
-// TODO(jln): remove the Linux special case once kernels are fixed.
-
-// Internally the kernel makes sigset_t an array of long large enough to have
-// one bit per signal.
-typedef uint64_t kernel_sigset_t;
-
-// This is what struct sigaction looks like to the kernel at least on X86 and
-// ARM. MIPS, for instance, is very different.
-struct kernel_sigaction {
-  void* k_sa_handler;  // For this usage it only needs to be a generic pointer.
-  unsigned long k_sa_flags;
-  void* k_sa_restorer;  // For this usage it only needs to be a generic pointer.
-  kernel_sigset_t k_sa_mask;
-};
-
-// glibc's sigaction() will prevent access to sa_restorer, so we need to roll
-// our own.
-int sys_rt_sigaction(int sig, const struct kernel_sigaction* act,
-                     struct kernel_sigaction* oact) {
-  return syscall(SYS_rt_sigaction, sig, act, oact, sizeof(kernel_sigset_t));
-}
-
-// This function is intended to be used in between fork() and execve() and will
-// reset all signal handlers to the default.
-// The motivation for going through all of them is that sa_restorer can leak
-// from parents and help defeat ASLR on buggy kernels.  We reset it to NULL.
-// See crbug.com/177956.
-void ResetChildSignalHandlersToDefaults(void) {
-  for (int signum = 1; ; ++signum) {
-    struct kernel_sigaction act;
-    memset(&act, 0, sizeof(act));
-    int sigaction_get_ret = sys_rt_sigaction(signum, NULL, &act);
-    if (sigaction_get_ret && errno == EINVAL) {
-#if !defined(NDEBUG)
-      // Linux supports 32 real-time signals from 33 to 64.
-      // If the number of signals in the Linux kernel changes, someone should
-      // look at this code.
-      const int kNumberOfSignals = 64;
-      RAW_CHECK(signum == kNumberOfSignals + 1, "");
-#endif  // !defined(NDEBUG)
-      break;
-    }
-    // All other failures are fatal.
-    if (sigaction_get_ret) {
-      RAW_LOG(FATAL, "sigaction (get) failed.");
-    }
-
-    // The kernel won't allow to re-set SIGKILL or SIGSTOP.
-    if (signum != SIGSTOP && signum != SIGKILL) {
-      act.k_sa_handler = (void*)SIG_DFL;
-      act.k_sa_restorer = NULL;
-      if (sys_rt_sigaction(signum, &act, NULL)) {
-        RAW_LOG(FATAL, "sigaction (set) failed.");
-      }
-    }
-#if !defined(NDEBUG)
-    // Now ask the kernel again and check that no restorer will leak.
-    if (sys_rt_sigaction(signum, NULL, &act) || act.k_sa_restorer) {
-      RAW_LOG(FATAL, "Cound not fix sa_restorer.");
-    }
-#endif  // !defined(NDEBUG)
-  }
-}
-#endif  // !defined(OS_LINUX) ||
-        // (!defined(__i386__) && !defined(__x86_64__) && !defined(__arm__))
-
-}  // anonymous namespace
-
-// Functor for |ScopedDIR| (below).
-struct ScopedDIRClose {
-  inline void operator()(DIR* x) const {
-    if (x)
-      closedir(x);
-  }
-};
-
-// Automatically closes |DIR*|s.
-typedef scoped_ptr<DIR, ScopedDIRClose> ScopedDIR;
-
-#if defined(OS_LINUX)
-static const char kFDDir[] = "/proc/self/fd";
-#elif defined(OS_MACOSX)
-static const char kFDDir[] = "/dev/fd";
-#elif defined(OS_SOLARIS)
-static const char kFDDir[] = "/dev/fd";
-#elif defined(OS_FREEBSD)
-static const char kFDDir[] = "/dev/fd";
-#elif defined(OS_OPENBSD)
-static const char kFDDir[] = "/dev/fd";
-#elif defined(OS_ANDROID)
-static const char kFDDir[] = "/proc/self/fd";
-#endif
-
-void CloseSuperfluousFds(const butil::InjectiveMultimap& saved_mapping) {
-  // DANGER: no calls to malloc or locks are allowed from now on:
-  // http://crbug.com/36678
-
-  // Get the maximum number of FDs possible.
-  size_t max_fds = GetMaxFds();
-
-  DirReaderPosix fd_dir(kFDDir);
-  if (!fd_dir.IsValid()) {
-    // Fallback case: Try every possible fd.
-    for (size_t i = 0; i < max_fds; ++i) {
-      const int fd = static_cast<int>(i);
-      if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
-        continue;
-      // Cannot use STL iterators here, since debug iterators use locks.
-      size_t j;
-      for (j = 0; j < saved_mapping.size(); j++) {
-        if (fd == saved_mapping[j].dest)
-          break;
-      }
-      if (j < saved_mapping.size())
-        continue;
-
-      // Since we're just trying to close anything we can find,
-      // ignore any error return values of close().
-      close(fd);
-    }
-    return;
-  }
-
-  const int dir_fd = fd_dir.fd();
-
-  for ( ; fd_dir.Next(); ) {
-    // Skip . and .. entries.
-    if (fd_dir.name()[0] == '.')
-      continue;
-
-    char *endptr;
-    errno = 0;
-    const long int fd = strtol(fd_dir.name(), &endptr, 10);
-    if (fd_dir.name()[0] == 0 || *endptr || fd < 0 || errno)
-      continue;
-    if (fd == STDIN_FILENO || fd == STDOUT_FILENO || fd == STDERR_FILENO)
-      continue;
-    // Cannot use STL iterators here, since debug iterators use locks.
-    size_t i;
-    for (i = 0; i < saved_mapping.size(); i++) {
-      if (fd == saved_mapping[i].dest)
-        break;
-    }
-    if (i < saved_mapping.size())
-      continue;
-    if (fd == dir_fd)
-      continue;
-
-    // When running under Valgrind, Valgrind opens several FDs for its
-    // own use and will complain if we try to close them.  All of
-    // these FDs are >= |max_fds|, so we can check against that here
-    // before closing.  See https://bugs.kde.org/show_bug.cgi?id=191758
-    if (fd < static_cast<int>(max_fds)) {
-      int ret = IGNORE_EINTR(close(fd));
-      DPCHECK(ret == 0);
-    }
-  }
-}
-
-bool LaunchProcess(const std::vector<std::string>& argv,
-                   const LaunchOptions& options,
-                   ProcessHandle* process_handle) {
-  size_t fd_shuffle_size = 0;
-  if (options.fds_to_remap) {
-    fd_shuffle_size = options.fds_to_remap->size();
-  }
-
-  InjectiveMultimap fd_shuffle1;
-  InjectiveMultimap fd_shuffle2;
-  fd_shuffle1.reserve(fd_shuffle_size);
-  fd_shuffle2.reserve(fd_shuffle_size);
-
-  scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
-  scoped_ptr<char*[]> new_environ;
-  char* const empty_environ = NULL;
-  char* const* old_environ = GetEnvironment();
-  if (options.clear_environ)
-    old_environ = &empty_environ;
-  if (!options.environ.empty())
-    new_environ = AlterEnvironment(old_environ, options.environ);
-
-  sigset_t full_sigset;
-  sigfillset(&full_sigset);
-  const sigset_t orig_sigmask = SetSignalMask(full_sigset);
-
-  pid_t pid;
-#if defined(OS_LINUX)
-  if (options.clone_flags) {
-    // Signal handling in this function assumes the creation of a new
-    // process, so we check that a thread is not being created by mistake
-    // and that signal handling follows the process-creation rules.
-    RAW_CHECK(
-        !(options.clone_flags & (CLONE_SIGHAND | CLONE_THREAD | CLONE_VM)), "");
-    pid = syscall(__NR_clone, options.clone_flags, 0, 0, 0);
-  } else
-#endif
-  {
-    pid = fork();
-  }
-
-  // Always restore the original signal mask in the parent.
-  if (pid != 0) {
-    SetSignalMask(orig_sigmask);
-  }
-
-  if (pid < 0) {
-    DPLOG(ERROR) << "fork";
-    return false;
-  } else if (pid == 0) {
-    // Child process
-
-    // DANGER: no calls to malloc or locks are allowed from now on:
-    // http://crbug.com/36678
-
-    // DANGER: fork() rule: in the child, if you don't end up doing exec*(),
-    // you call _exit() instead of exit(). This is because _exit() does not
-    // call any previously-registered (in the parent) exit handlers, which
-    // might do things like block waiting for threads that don't even exist
-    // in the child.
-
-    // If a child process uses the readline library, the process block forever.
-    // In BSD like OSes including OS X it is safe to assign /dev/null as stdin.
-    // See http://crbug.com/56596.
-    butil::ScopedFD null_fd(HANDLE_EINTR(open("/dev/null", O_RDONLY)));
-    if (!null_fd.is_valid()) {
-      RAW_LOG(ERROR, "Failed to open /dev/null");
-      _exit(127);
-    }
-
-    int new_fd = HANDLE_EINTR(dup2(null_fd.get(), STDIN_FILENO));
-    if (new_fd != STDIN_FILENO) {
-      RAW_LOG(ERROR, "Failed to dup /dev/null for stdin");
-      _exit(127);
-    }
-
-    if (options.new_process_group) {
-      // Instead of inheriting the process group ID of the parent, the child
-      // starts off a new process group with pgid equal to its process ID.
-      if (setpgid(0, 0) < 0) {
-        RAW_LOG(ERROR, "setpgid failed");
-        _exit(127);
-      }
-    }
-
-    // Stop type-profiler.
-    // The profiler should be stopped between fork and exec since it inserts
-    // locks at new/delete expressions.  See http://crbug.com/36678.
-    butil::type_profiler::Controller::Stop();
-
-    if (options.maximize_rlimits) {
-      // Some resource limits need to be maximal in this child.
-      for (size_t i = 0; i < options.maximize_rlimits->size(); ++i) {
-        const int resource = (*options.maximize_rlimits)[i];
-        struct rlimit limit;
-        if (getrlimit(resource, &limit) < 0) {
-          RAW_LOG(WARNING, "getrlimit failed");
-        } else if (limit.rlim_cur < limit.rlim_max) {
-          limit.rlim_cur = limit.rlim_max;
-          if (setrlimit(resource, &limit) < 0) {
-            RAW_LOG(WARNING, "setrlimit failed");
-          }
-        }
-      }
-    }
-
-#if defined(OS_MACOSX)
-    RestoreDefaultExceptionHandler();
-    if (!options.replacement_bootstrap_name.empty())
-      ReplaceBootstrapPort(options.replacement_bootstrap_name);
-#endif  // defined(OS_MACOSX)
-
-    ResetChildSignalHandlersToDefaults();
-    SetSignalMask(orig_sigmask);
-
-#if 0
-    // When debugging it can be helpful to check that we really aren't making
-    // any hidden calls to malloc.
-    void *malloc_thunk =
-        reinterpret_cast<void*>(reinterpret_cast<intptr_t>(malloc) & ~4095);
-    mprotect(malloc_thunk, 4096, PROT_READ | PROT_WRITE | PROT_EXEC);
-    memset(reinterpret_cast<void*>(malloc), 0xff, 8);
-#endif  // 0
-
-#if defined(OS_CHROMEOS)
-    if (options.ctrl_terminal_fd >= 0) {
-      // Set process' controlling terminal.
-      if (HANDLE_EINTR(setsid()) != -1) {
-        if (HANDLE_EINTR(
-                ioctl(options.ctrl_terminal_fd, TIOCSCTTY, NULL)) == -1) {
-          RAW_LOG(WARNING, "ioctl(TIOCSCTTY), ctrl terminal not set");
-        }
-      } else {
-        RAW_LOG(WARNING, "setsid failed, ctrl terminal not set");
-      }
-    }
-#endif  // defined(OS_CHROMEOS)
-
-    if (options.fds_to_remap) {
-      // Cannot use STL iterators here, since debug iterators use locks.
-      for (size_t i = 0; i < options.fds_to_remap->size(); ++i) {
-        const FileHandleMappingVector::value_type& value =
-            (*options.fds_to_remap)[i];
-        fd_shuffle1.push_back(InjectionArc(value.first, value.second, false));
-        fd_shuffle2.push_back(InjectionArc(value.first, value.second, false));
-      }
-    }
-
-    if (!options.environ.empty() || options.clear_environ)
-      SetEnvironment(new_environ.get());
-
-    // fd_shuffle1 is mutated by this call because it cannot malloc.
-    if (!ShuffleFileDescriptors(&fd_shuffle1))
-      _exit(127);
-
-    CloseSuperfluousFds(fd_shuffle2);
-
-    // Set NO_NEW_PRIVS by default. Since NO_NEW_PRIVS only exists in kernel
-    // 3.5+, do not check the return value of prctl here.
-#if defined(OS_LINUX)
-#ifndef PR_SET_NO_NEW_PRIVS
-#define PR_SET_NO_NEW_PRIVS 38
-#endif
-    if (!options.allow_new_privs) {
-      if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) && errno != EINVAL) {
-        // Only log if the error is not EINVAL (i.e. not supported).
-        RAW_LOG(FATAL, "prctl(PR_SET_NO_NEW_PRIVS) failed");
-      }
-    }
-#endif
-
-    for (size_t i = 0; i < argv.size(); i++)
-      argv_cstr[i] = const_cast<char*>(argv[i].c_str());
-    argv_cstr[argv.size()] = NULL;
-    execvp(argv_cstr[0], argv_cstr.get());
-
-    RAW_LOG(ERROR, "LaunchProcess: failed to execvp:");
-    RAW_LOG(ERROR, argv_cstr[0]);
-    _exit(127);
-  } else {
-    // Parent process
-    if (options.wait) {
-      // While this isn't strictly disk IO, waiting for another process to
-      // finish is the sort of thing ThreadRestrictions is trying to prevent.
-      butil::ThreadRestrictions::AssertIOAllowed();
-      pid_t ret = HANDLE_EINTR(waitpid(pid, 0, 0));
-      DPCHECK(ret > 0);
-    }
-
-    if (process_handle)
-      *process_handle = pid;
-  }
-
-  return true;
-}
-
-
-bool LaunchProcess(const CommandLine& cmdline,
-                   const LaunchOptions& options,
-                   ProcessHandle* process_handle) {
-  return LaunchProcess(cmdline.argv(), options, process_handle);
-}
-
-void RaiseProcessToHighPriority() {
-  // On POSIX, we don't actually do anything here.  We could try to nice() or
-  // setpriority() or sched_getscheduler, but these all require extra rights.
-}
-
-// Return value used by GetAppOutputInternal to encapsulate the various exit
-// scenarios from the function.
-enum GetAppOutputInternalResult {
-  EXECUTE_FAILURE,
-  EXECUTE_SUCCESS,
-  GOT_MAX_OUTPUT,
-};
-
-// Executes the application specified by |argv| and wait for it to exit. Stores
-// the output (stdout) in |output|. If |do_search_path| is set, it searches the
-// path for the application; in that case, |envp| must be null, and it will use
-// the current environment. If |do_search_path| is false, |argv[0]| should fully
-// specify the path of the application, and |envp| will be used as the
-// environment. Redirects stderr to /dev/null.
-// If we successfully start the application and get all requested output, we
-// return GOT_MAX_OUTPUT, or if there is a problem starting or exiting
-// the application we return RUN_FAILURE. Otherwise we return EXECUTE_SUCCESS.
-// The GOT_MAX_OUTPUT return value exists so a caller that asks for limited
-// output can treat this as a success, despite having an exit code of SIG_PIPE
-// due to us closing the output pipe.
-// In the case of EXECUTE_SUCCESS, the application exit code will be returned
-// in |*exit_code|, which should be checked to determine if the application
-// ran successfully.
-static GetAppOutputInternalResult GetAppOutputInternal(
-    const std::vector<std::string>& argv,
-    char* const envp[],
-    std::string* output,
-    size_t max_output,
-    bool do_search_path,
-    int* exit_code) {
-  // Doing a blocking wait for another command to finish counts as IO.
-  butil::ThreadRestrictions::AssertIOAllowed();
-  // exit_code must be supplied so calling function can determine success.
-  DCHECK(exit_code);
-  *exit_code = EXIT_FAILURE;
-
-  int pipe_fd[2];
-  pid_t pid;
-  InjectiveMultimap fd_shuffle1, fd_shuffle2;
-  scoped_ptr<char*[]> argv_cstr(new char*[argv.size() + 1]);
-
-  fd_shuffle1.reserve(3);
-  fd_shuffle2.reserve(3);
-
-  // Either |do_search_path| should be false or |envp| should be null, but not
-  // both.
-  DCHECK(!do_search_path ^ !envp);
-
-  if (pipe(pipe_fd) < 0)
-    return EXECUTE_FAILURE;
-
-  switch (pid = fork()) {
-    case -1:  // error
-      close(pipe_fd[0]);
-      close(pipe_fd[1]);
-      return EXECUTE_FAILURE;
-    case 0:  // child
-      {
-        // DANGER: no calls to malloc or locks are allowed from now on:
-        // http://crbug.com/36678
-
-#if defined(OS_MACOSX)
-        RestoreDefaultExceptionHandler();
-#endif
-
-        // Obscure fork() rule: in the child, if you don't end up doing exec*(),
-        // you call _exit() instead of exit(). This is because _exit() does not
-        // call any previously-registered (in the parent) exit handlers, which
-        // might do things like block waiting for threads that don't even exist
-        // in the child.
-        int dev_null = open("/dev/null", O_WRONLY);
-        if (dev_null < 0)
-          _exit(127);
-
-        // Stop type-profiler.
-        // The profiler should be stopped between fork and exec since it inserts
-        // locks at new/delete expressions.  See http://crbug.com/36678.
-        butil::type_profiler::Controller::Stop();
-
-        fd_shuffle1.push_back(InjectionArc(pipe_fd[1], STDOUT_FILENO, true));
-        fd_shuffle1.push_back(InjectionArc(dev_null, STDERR_FILENO, true));
-        fd_shuffle1.push_back(InjectionArc(dev_null, STDIN_FILENO, true));
-        // Adding another element here? Remeber to increase the argument to
-        // reserve(), above.
-
-        for (size_t i = 0; i < fd_shuffle1.size(); ++i)
-          fd_shuffle2.push_back(fd_shuffle1[i]);
-
-        if (!ShuffleFileDescriptors(&fd_shuffle1))
-          _exit(127);
-
-        CloseSuperfluousFds(fd_shuffle2);
-
-        for (size_t i = 0; i < argv.size(); i++)
-          argv_cstr[i] = const_cast<char*>(argv[i].c_str());
-        argv_cstr[argv.size()] = NULL;
-        if (do_search_path)
-          execvp(argv_cstr[0], argv_cstr.get());
-        else
-          execve(argv_cstr[0], argv_cstr.get(), envp);
-        _exit(127);
-      }
-    default:  // parent
-      {
-        // Close our writing end of pipe now. Otherwise later read would not
-        // be able to detect end of child's output (in theory we could still
-        // write to the pipe).
-        close(pipe_fd[1]);
-
-        output->clear();
-        char buffer[256];
-        size_t output_buf_left = max_output;
-        ssize_t bytes_read = 1;  // A lie to properly handle |max_output == 0|
-                                 // case in the logic below.
-
-        while (output_buf_left > 0) {
-          bytes_read = HANDLE_EINTR(read(pipe_fd[0], buffer,
-                                    std::min(output_buf_left, sizeof(buffer))));
-          if (bytes_read <= 0)
-            break;
-          output->append(buffer, bytes_read);
-          output_buf_left -= static_cast<size_t>(bytes_read);
-        }
-        close(pipe_fd[0]);
-
-        // Always wait for exit code (even if we know we'll declare
-        // GOT_MAX_OUTPUT).
-        bool success = WaitForExitCode(pid, exit_code);
-
-        // If we stopped because we read as much as we wanted, we return
-        // GOT_MAX_OUTPUT (because the child may exit due to |SIGPIPE|).
-        if (!output_buf_left && bytes_read > 0)
-          return GOT_MAX_OUTPUT;
-        else if (success)
-          return EXECUTE_SUCCESS;
-        return EXECUTE_FAILURE;
-      }
-  }
-}
-
-bool GetAppOutput(const CommandLine& cl, std::string* output) {
-  return GetAppOutput(cl.argv(), output);
-}
-
-bool GetAppOutput(const std::vector<std::string>& argv, std::string* output) {
-  // Run |execve()| with the current environment and store "unlimited" data.
-  int exit_code;
-  GetAppOutputInternalResult result = GetAppOutputInternal(
-      argv, NULL, output, std::numeric_limits<std::size_t>::max(), true,
-      &exit_code);
-  return result == EXECUTE_SUCCESS && exit_code == EXIT_SUCCESS;
-}
-
-// TODO(viettrungluu): Conceivably, we should have a timeout as well, so we
-// don't hang if what we're calling hangs.
-bool GetAppOutputRestricted(const CommandLine& cl,
-                            std::string* output, size_t max_output) {
-  // Run |execve()| with the empty environment.
-  char* const empty_environ = NULL;
-  int exit_code;
-  GetAppOutputInternalResult result = GetAppOutputInternal(
-      cl.argv(), &empty_environ, output, max_output, false, &exit_code);
-  return result == GOT_MAX_OUTPUT || (result == EXECUTE_SUCCESS &&
-                                      exit_code == EXIT_SUCCESS);
-}
-
-bool GetAppOutputWithExitCode(const CommandLine& cl,
-                              std::string* output,
-                              int* exit_code) {
-  // Run |execve()| with the current environment and store "unlimited" data.
-  GetAppOutputInternalResult result = GetAppOutputInternal(
-      cl.argv(), NULL, output, std::numeric_limits<std::size_t>::max(), true,
-      exit_code);
-  return result == EXECUTE_SUCCESS;
-}
-
-}  // namespace butil

+ 0 - 30
src/butil/process/memory.cc

@@ -1,30 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/memory.h"
-
-namespace butil {
-
-// Defined in memory_mac.mm for Mac.
-#if !defined(OS_MACOSX)
-
-bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
-  const size_t alloc_size = num_items * size;
-
-  // Overflow check
-  if (size && ((alloc_size / size) != num_items)) {
-    *result = NULL;
-    return false;
-  }
-
-  if (!UncheckedMalloc(alloc_size, result))
-    return false;
-
-  memset(*result, 0, alloc_size);
-  return true;
-}
-
-#endif
-
-}

+ 0 - 82
src/butil/process/memory.h

@@ -1,82 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_PROCESS_MEMORY_H_
-#define BASE_PROCESS_MEMORY_H_
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/process/process_handle.h"
-#include "butil/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
-#ifdef PVALLOC_AVAILABLE
-// Build config explicitly tells us whether or not pvalloc is available.
-#elif defined(LIBC_GLIBC) && !defined(USE_TCMALLOC)
-#define PVALLOC_AVAILABLE 1
-#else
-#define PVALLOC_AVAILABLE 0
-#endif
-
-namespace butil {
-
-// Enables low fragmentation heap (LFH) for every heaps of this process. This
-// won't have any effect on heaps created after this function call. It will not
-// modify data allocated in the heaps before calling this function. So it is
-// better to call this function early in initialization and again before
-// entering the main loop.
-// Note: Returns true on Windows 2000 without doing anything.
-BASE_EXPORT bool EnableLowFragmentationHeap();
-
-// Enables 'terminate on heap corruption' flag. Helps protect against heap
-// overflow. Has no effect if the OS doesn't provide the necessary facility.
-BASE_EXPORT void EnableTerminationOnHeapCorruption();
-
-// Turns on process termination if memory runs out.
-BASE_EXPORT void EnableTerminationOnOutOfMemory();
-
-#if defined(OS_WIN)
-// Returns the module handle to which an address belongs. The reference count
-// of the module is not incremented.
-BASE_EXPORT HMODULE GetModuleFromAddress(void* address);
-#endif
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-BASE_EXPORT extern size_t g_oom_size;
-
-// The maximum allowed value for the OOM score.
-const int kMaxOomScore = 1000;
-
-// This adjusts /proc/<pid>/oom_score_adj so the Linux OOM killer will
-// prefer to kill certain process types over others. The range for the
-// adjustment is [-1000, 1000], with [0, 1000] being user accessible.
-// If the Linux system doesn't support the newer oom_score_adj range
-// of [0, 1000], then we revert to using the older oom_adj, and
-// translate the given value into [0, 15].  Some aliasing of values
-// may occur in that case, of course.
-BASE_EXPORT bool AdjustOOMScore(ProcessId process, int score);
-#endif
-
-// Special allocator functions for callers that want to check for OOM.
-// These will not abort if the allocation fails even if
-// EnableTerminationOnOutOfMemory has been called.
-// This can be useful for huge and/or unpredictable size memory allocations.
-// Please only use this if you really handle the case when the allocation
-// fails. Doing otherwise would risk security.
-// These functions may still crash on OOM when running under memory tools,
-// specifically ASan and other sanitizers.
-// Return value tells whether the allocation succeeded. If it fails |result| is
-// set to NULL, otherwise it holds the memory address.
-BASE_EXPORT WARN_UNUSED_RESULT bool UncheckedMalloc(size_t size,
-                                                    void** result);
-BASE_EXPORT WARN_UNUSED_RESULT bool UncheckedCalloc(size_t num_items,
-                                                    size_t size,
-                                                    void** result);
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_MEMORY_H_

+ 0 - 213
src/butil/process/memory_linux.cc

@@ -1,213 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/memory.h"
-
-#include <new>
-
-#include "butil/file_util.h"
-#include "butil/files/file_path.h"
-#include "butil/logging.h"
-#include "butil/process/internal_linux.h"
-#include "butil/strings/string_number_conversions.h"
-
-#if defined(USE_TCMALLOC)
-// Used by UncheckedMalloc. If tcmalloc is linked to the executable
-// this will be replaced by a strong symbol that actually implement
-// the semantics and don't call new handler in case the allocation fails.
-extern "C" {
-
-__attribute__((weak, visibility("default")))
-void* tc_malloc_skip_new_handler_weak(size_t size);
-
-void* tc_malloc_skip_new_handler_weak(size_t size) {
-  return malloc(size);
-}
-
-}
-#endif
-
-namespace butil {
-
-size_t g_oom_size = 0U;
-
-namespace {
-
-#if !defined(OS_ANDROID)
-void OnNoMemorySize(size_t size) {
-  g_oom_size = size;
-
-  if (size != 0)
-    LOG(FATAL) << "Out of memory, size = " << size;
-  LOG(FATAL) << "Out of memory.";
-}
-
-void OnNoMemory() {
-  OnNoMemorySize(0);
-}
-#endif  // !defined(OS_ANDROID)
-
-}  // namespace
-
-#if !defined(ADDRESS_SANITIZER) && !defined(MEMORY_SANITIZER) && \
-    !defined(THREAD_SANITIZER) && !defined(LEAK_SANITIZER)
-
-#if defined(LIBC_GLIBC) && !defined(USE_TCMALLOC)
-
-extern "C" {
-void* __libc_malloc(size_t size);
-void* __libc_realloc(void* ptr, size_t size);
-void* __libc_calloc(size_t nmemb, size_t size);
-void* __libc_valloc(size_t size);
-#if PVALLOC_AVAILABLE == 1
-void* __libc_pvalloc(size_t size);
-#endif
-void* __libc_memalign(size_t alignment, size_t size);
-
-// Overriding the system memory allocation functions:
-//
-// For security reasons, we want malloc failures to be fatal. Too much code
-// doesn't check for a NULL return value from malloc and unconditionally uses
-// the resulting pointer. If the first offset that they try to access is
-// attacker controlled, then the attacker can direct the code to access any
-// part of memory.
-//
-// Thus, we define all the standard malloc functions here and mark them as
-// visibility 'default'. This means that they replace the malloc functions for
-// all Chromium code and also for all code in shared libraries. There are tests
-// for this in process_util_unittest.cc.
-//
-// If we are using tcmalloc, then the problem is moot since tcmalloc handles
-// this for us. Thus this code is in a !defined(USE_TCMALLOC) block.
-//
-// If we are testing the binary with AddressSanitizer, we should not
-// redefine malloc and let AddressSanitizer do it instead.
-//
-// We call the real libc functions in this code by using __libc_malloc etc.
-// Previously we tried using dlsym(RTLD_NEXT, ...) but that failed depending on
-// the link order. Since ld.so needs calloc during symbol resolution, it
-// defines its own versions of several of these functions in dl-minimal.c.
-// Depending on the runtime library order, dlsym ended up giving us those
-// functions and bad things happened. See crbug.com/31809
-//
-// This means that any code which calls __libc_* gets the raw libc versions of
-// these functions.
-
-#define DIE_ON_OOM_1(function_name) \
-  void* function_name(size_t) __attribute__ ((visibility("default"))); \
-  \
-  void* function_name(size_t size) { \
-    void* ret = __libc_##function_name(size); \
-    if (ret == NULL && size != 0) \
-      OnNoMemorySize(size); \
-    return ret; \
-  }
-
-#define DIE_ON_OOM_2(function_name, arg1_type) \
-  void* function_name(arg1_type, size_t) \
-      __attribute__ ((visibility("default"))); \
-  \
-  void* function_name(arg1_type arg1, size_t size) { \
-    void* ret = __libc_##function_name(arg1, size); \
-    if (ret == NULL && size != 0) \
-      OnNoMemorySize(size); \
-    return ret; \
-  }
-
-DIE_ON_OOM_1(malloc)
-DIE_ON_OOM_1(valloc)
-#if PVALLOC_AVAILABLE == 1
-DIE_ON_OOM_1(pvalloc)
-#endif
-
-DIE_ON_OOM_2(calloc, size_t)
-DIE_ON_OOM_2(realloc, void*)
-DIE_ON_OOM_2(memalign, size_t)
-
-// posix_memalign has a unique signature and doesn't have a __libc_ variant.
-int posix_memalign(void** ptr, size_t alignment, size_t size)
-    __attribute__ ((visibility("default")));
-
-int posix_memalign(void** ptr, size_t alignment, size_t size) {
-  // This will use the safe version of memalign, above.
-  *ptr = memalign(alignment, size);
-  return 0;
-}
-
-}  // extern C
-
-#else
-
-// TODO(mostynb@opera.com): dlsym dance
-
-#endif  // LIBC_GLIBC && !USE_TCMALLOC
-
-#endif  // !*_SANITIZER
-
-void EnableTerminationOnHeapCorruption() {
-  // On Linux, there nothing to do AFAIK.
-}
-
-void EnableTerminationOnOutOfMemory() {
-#if defined(OS_ANDROID)
-  // Android doesn't support setting a new handler.
-  DLOG(WARNING) << "Not feasible.";
-#else
-  // Set the new-out of memory handler.
-  std::set_new_handler(&OnNoMemory);
-  // If we're using glibc's allocator, the above functions will override
-  // malloc and friends and make them die on out of memory.
-#endif
-}
-
-// NOTE: This is not the only version of this function in the source:
-// the setuid sandbox (in process_util_linux.c, in the sandbox source)
-// also has its own C version.
-bool AdjustOOMScore(ProcessId process, int score) {
-  if (score < 0 || score > kMaxOomScore)
-    return false;
-
-  FilePath oom_path(internal::GetProcPidDir(process));
-
-  // Attempt to write the newer oom_score_adj file first.
-  FilePath oom_file = oom_path.AppendASCII("oom_score_adj");
-  if (PathExists(oom_file)) {
-    std::string score_str = IntToString(score);
-    DVLOG(1) << "Adjusting oom_score_adj of " << process << " to "
-             << score_str;
-    int score_len = static_cast<int>(score_str.length());
-    return (score_len == WriteFile(oom_file, score_str.c_str(), score_len));
-  }
-
-  // If the oom_score_adj file doesn't exist, then we write the old
-  // style file and translate the oom_adj score to the range 0-15.
-  oom_file = oom_path.AppendASCII("oom_adj");
-  if (PathExists(oom_file)) {
-    // Max score for the old oom_adj range.  Used for conversion of new
-    // values to old values.
-    const int kMaxOldOomScore = 15;
-
-    int converted_score = score * kMaxOldOomScore / kMaxOomScore;
-    std::string score_str = IntToString(converted_score);
-    DVLOG(1) << "Adjusting oom_adj of " << process << " to " << score_str;
-    int score_len = static_cast<int>(score_str.length());
-    return (score_len == WriteFile(oom_file, score_str.c_str(), score_len));
-  }
-
-  return false;
-}
-
-bool UncheckedMalloc(size_t size, void** result) {
-#if defined(MEMORY_TOOL_REPLACES_ALLOCATOR) || \
-    (!defined(LIBC_GLIBC) && !defined(USE_TCMALLOC))
-  *result = malloc(size);
-#elif defined(LIBC_GLIBC) && !defined(USE_TCMALLOC)
-  *result = __libc_malloc(size);
-#elif defined(USE_TCMALLOC)
-  *result = tc_malloc_skip_new_handler_weak(size);
-#endif
-  return *result != NULL;
-}
-
-}  // namespace butil

+ 0 - 751
src/butil/process/memory_mac.mm

@@ -1,751 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "base/process/memory.h"
-
-#include <CoreFoundation/CoreFoundation.h>
-#include <errno.h>
-#include <mach/mach.h>
-#include <mach/mach_vm.h>
-#include <malloc/malloc.h>
-#import <objc/runtime.h>
-
-#include <new>
-
-#include "base/lazy_instance.h"
-#include "base/logging.h"
-#include "base/mac/mac_util.h"
-#include "base/mac/mach_logging.h"
-#include "base/scoped_clear_errno.h"
-#include "third_party/apple_apsl/CFBase.h"
-#include "third_party/apple_apsl/malloc.h"
-
-#if ARCH_CPU_32_BITS
-#include <dlfcn.h>
-#include <mach-o/nlist.h>
-
-#include "base/threading/thread_local.h"
-#include "third_party/mach_override/mach_override.h"
-#endif  // ARCH_CPU_32_BITS
-
-namespace base {
-
-// These are helpers for EnableTerminationOnHeapCorruption, which is a no-op
-// on 64 bit Macs.
-#if ARCH_CPU_32_BITS
-namespace {
-
-// Finds the library path for malloc() and thus the libC part of libSystem,
-// which in Lion is in a separate image.
-const char* LookUpLibCPath() {
-  const void* addr = reinterpret_cast<void*>(&malloc);
-
-  Dl_info info;
-  if (dladdr(addr, &info))
-    return info.dli_fname;
-
-  DLOG(WARNING) << "Could not find image path for malloc()";
-  return NULL;
-}
-
-typedef void(*malloc_error_break_t)(void);
-malloc_error_break_t g_original_malloc_error_break = NULL;
-
-// Returns the function pointer for malloc_error_break. This symbol is declared
-// as __private_extern__ and cannot be dlsym()ed. Instead, use nlist() to
-// get it.
-malloc_error_break_t LookUpMallocErrorBreak() {
-  const char* lib_c_path = LookUpLibCPath();
-  if (!lib_c_path)
-    return NULL;
-
-  // Only need to look up two symbols, but nlist() requires a NULL-terminated
-  // array and takes no count.
-  struct nlist nl[3];
-  bzero(&nl, sizeof(nl));
-
-  // The symbol to find.
-  nl[0].n_un.n_name = const_cast<char*>("_malloc_error_break");
-
-  // A reference symbol by which the address of the desired symbol will be
-  // calculated.
-  nl[1].n_un.n_name = const_cast<char*>("_malloc");
-
-  int rv = nlist(lib_c_path, nl);
-  if (rv != 0 || nl[0].n_type == N_UNDF || nl[1].n_type == N_UNDF) {
-    return NULL;
-  }
-
-  // nlist() returns addresses as offsets in the image, not the instruction
-  // pointer in memory. Use the known in-memory address of malloc()
-  // to compute the offset for malloc_error_break().
-  uintptr_t reference_addr = reinterpret_cast<uintptr_t>(&malloc);
-  reference_addr -= nl[1].n_value;
-  reference_addr += nl[0].n_value;
-
-  return reinterpret_cast<malloc_error_break_t>(reference_addr);
-}
-
-// Combines ThreadLocalBoolean with AutoReset.  It would be convenient
-// to compose ThreadLocalPointer<bool> with base::AutoReset<bool>, but that
-// would require allocating some storage for the bool.
-class ThreadLocalBooleanAutoReset {
- public:
-  ThreadLocalBooleanAutoReset(ThreadLocalBoolean* tlb, bool new_value)
-      : scoped_tlb_(tlb),
-        original_value_(tlb->Get()) {
-    scoped_tlb_->Set(new_value);
-  }
-  ~ThreadLocalBooleanAutoReset() {
-    scoped_tlb_->Set(original_value_);
-  }
-
- private:
-  ThreadLocalBoolean* scoped_tlb_;
-  bool original_value_;
-
-  DISALLOW_COPY_AND_ASSIGN(ThreadLocalBooleanAutoReset);
-};
-
-base::LazyInstance<ThreadLocalBoolean>::Leaky
-    g_unchecked_alloc = LAZY_INSTANCE_INITIALIZER;
-
-// NOTE(shess): This is called when the malloc library noticed that the heap
-// is fubar.  Avoid calls which will re-enter the malloc library.
-void CrMallocErrorBreak() {
-  g_original_malloc_error_break();
-
-  // Out of memory is certainly not heap corruption, and not necessarily
-  // something for which the process should be terminated. Leave that decision
-  // to the OOM killer.
-  if (errno == ENOMEM)
-    return;
-
-  // The malloc library attempts to log to ASL (syslog) before calling this
-  // code, which fails accessing a Unix-domain socket when sandboxed.  The
-  // failed socket results in writing to a -1 fd, leaving EBADF in errno.  If
-  // UncheckedMalloc() is on the stack, for large allocations (15k and up) only
-  // an OOM failure leads here.  Smaller allocations could also arrive here due
-  // to freelist corruption, but there is no way to distinguish that from OOM at
-  // this point.
-  //
-  // NOTE(shess): I hypothesize that EPERM case in 10.9 is the same root cause
-  // as EBADF.  Unfortunately, 10.9's opensource releases don't include malloc
-  // source code at this time.
-  // <http://crbug.com/312234>
-  if ((errno == EBADF || errno == EPERM) && g_unchecked_alloc.Get().Get())
-    return;
-
-  // A unit test checks this error message, so it needs to be in release builds.
-  char buf[1024] =
-      "Terminating process due to a potential for future heap corruption: "
-      "errno=";
-  char errnobuf[] = {
-    '0' + ((errno / 100) % 10),
-    '0' + ((errno / 10) % 10),
-    '0' + (errno % 10),
-    '\000'
-  };
-  COMPILE_ASSERT(ELAST <= 999, errno_too_large_to_encode);
-  strlcat(buf, errnobuf, sizeof(buf));
-  RAW_LOG(ERROR, buf);
-
-  // Crash by writing to NULL+errno to allow analyzing errno from
-  // crash dump info (setting a breakpad key would re-enter the malloc
-  // library).  Max documented errno in intro(2) is actually 102, but
-  // it really just needs to be "small" to stay on the right vm page.
-  const int kMaxErrno = 256;
-  char* volatile death_ptr = NULL;
-  death_ptr += std::min(errno, kMaxErrno);
-  *death_ptr = '!';
-}
-
-}  // namespace
-#endif  // ARCH_CPU_32_BITS
-
-void EnableTerminationOnHeapCorruption() {
-#if defined(ADDRESS_SANITIZER) || ARCH_CPU_64_BITS
-  // AddressSanitizer handles heap corruption, and on 64 bit Macs, the malloc
-  // system automatically abort()s on heap corruption.
-  return;
-#else
-  // Only override once, otherwise CrMallocErrorBreak() will recurse
-  // to itself.
-  if (g_original_malloc_error_break)
-    return;
-
-  malloc_error_break_t malloc_error_break = LookUpMallocErrorBreak();
-  if (!malloc_error_break) {
-    DLOG(WARNING) << "Could not find malloc_error_break";
-    return;
-  }
-
-  mach_error_t err = mach_override_ptr(
-     (void*)malloc_error_break,
-     (void*)&CrMallocErrorBreak,
-     (void**)&g_original_malloc_error_break);
-
-  if (err != err_none)
-    DLOG(WARNING) << "Could not override malloc_error_break; error = " << err;
-#endif  // defined(ADDRESS_SANITIZER) || ARCH_CPU_64_BITS
-}
-
-// ------------------------------------------------------------------------
-
-namespace {
-
-bool g_oom_killer_enabled;
-
-// Starting with Mac OS X 10.7, the zone allocators set up by the system are
-// read-only, to prevent them from being overwritten in an attack. However,
-// blindly unprotecting and reprotecting the zone allocators fails with
-// GuardMalloc because GuardMalloc sets up its zone allocator using a block of
-// memory in its bss. Explicit saving/restoring of the protection is required.
-//
-// This function takes a pointer to a malloc zone, de-protects it if necessary,
-// and returns (in the out parameters) a region of memory (if any) to be
-// re-protected when modifications are complete. This approach assumes that
-// there is no contention for the protection of this memory.
-void DeprotectMallocZone(ChromeMallocZone* default_zone,
-                         mach_vm_address_t* reprotection_start,
-                         mach_vm_size_t* reprotection_length,
-                         vm_prot_t* reprotection_value) {
-  mach_port_t unused;
-  *reprotection_start = reinterpret_cast<mach_vm_address_t>(default_zone);
-  struct vm_region_basic_info_64 info;
-  mach_msg_type_number_t count = VM_REGION_BASIC_INFO_COUNT_64;
-  kern_return_t result =
-      mach_vm_region(mach_task_self(),
-                     reprotection_start,
-                     reprotection_length,
-                     VM_REGION_BASIC_INFO_64,
-                     reinterpret_cast<vm_region_info_t>(&info),
-                     &count,
-                     &unused);
-  MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_region";
-
-  // The kernel always returns a null object for VM_REGION_BASIC_INFO_64, but
-  // balance it with a deallocate in case this ever changes. See 10.9.2
-  // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
-  mach_port_deallocate(mach_task_self(), unused);
-
-  // Does the region fully enclose the zone pointers? Possibly unwarranted
-  // simplification used: using the size of a full version 8 malloc zone rather
-  // than the actual smaller size if the passed-in zone is not version 8.
-  CHECK(*reprotection_start <=
-            reinterpret_cast<mach_vm_address_t>(default_zone));
-  mach_vm_size_t zone_offset = reinterpret_cast<mach_vm_size_t>(default_zone) -
-      reinterpret_cast<mach_vm_size_t>(*reprotection_start);
-  CHECK(zone_offset + sizeof(ChromeMallocZone) <= *reprotection_length);
-
-  if (info.protection & VM_PROT_WRITE) {
-    // No change needed; the zone is already writable.
-    *reprotection_start = 0;
-    *reprotection_length = 0;
-    *reprotection_value = VM_PROT_NONE;
-  } else {
-    *reprotection_value = info.protection;
-    result = mach_vm_protect(mach_task_self(),
-                             *reprotection_start,
-                             *reprotection_length,
-                             false,
-                             info.protection | VM_PROT_WRITE);
-    MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
-  }
-}
-
-// === C malloc/calloc/valloc/realloc/posix_memalign ===
-
-typedef void* (*malloc_type)(struct _malloc_zone_t* zone,
-                             size_t size);
-typedef void* (*calloc_type)(struct _malloc_zone_t* zone,
-                             size_t num_items,
-                             size_t size);
-typedef void* (*valloc_type)(struct _malloc_zone_t* zone,
-                             size_t size);
-typedef void (*free_type)(struct _malloc_zone_t* zone,
-                          void* ptr);
-typedef void* (*realloc_type)(struct _malloc_zone_t* zone,
-                              void* ptr,
-                              size_t size);
-typedef void* (*memalign_type)(struct _malloc_zone_t* zone,
-                               size_t alignment,
-                               size_t size);
-
-malloc_type g_old_malloc;
-calloc_type g_old_calloc;
-valloc_type g_old_valloc;
-free_type g_old_free;
-realloc_type g_old_realloc;
-memalign_type g_old_memalign;
-
-malloc_type g_old_malloc_purgeable;
-calloc_type g_old_calloc_purgeable;
-valloc_type g_old_valloc_purgeable;
-free_type g_old_free_purgeable;
-realloc_type g_old_realloc_purgeable;
-memalign_type g_old_memalign_purgeable;
-
-void* oom_killer_malloc(struct _malloc_zone_t* zone,
-                        size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_malloc(zone, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_calloc(struct _malloc_zone_t* zone,
-                        size_t num_items,
-                        size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_calloc(zone, num_items, size);
-  if (!result && num_items && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_valloc(struct _malloc_zone_t* zone,
-                        size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_valloc(zone, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void oom_killer_free(struct _malloc_zone_t* zone,
-                     void* ptr) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  g_old_free(zone, ptr);
-}
-
-void* oom_killer_realloc(struct _malloc_zone_t* zone,
-                         void* ptr,
-                         size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_realloc(zone, ptr, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_memalign(struct _malloc_zone_t* zone,
-                          size_t alignment,
-                          size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_memalign(zone, alignment, size);
-  // Only die if posix_memalign would have returned ENOMEM, since there are
-  // other reasons why NULL might be returned (see
-  // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
-  if (!result && size && alignment >= sizeof(void*)
-      && (alignment & (alignment - 1)) == 0) {
-    debug::BreakDebugger();
-  }
-  return result;
-}
-
-void* oom_killer_malloc_purgeable(struct _malloc_zone_t* zone,
-                                  size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_malloc_purgeable(zone, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_calloc_purgeable(struct _malloc_zone_t* zone,
-                                  size_t num_items,
-                                  size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_calloc_purgeable(zone, num_items, size);
-  if (!result && num_items && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_valloc_purgeable(struct _malloc_zone_t* zone,
-                                  size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_valloc_purgeable(zone, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void oom_killer_free_purgeable(struct _malloc_zone_t* zone,
-                               void* ptr) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  g_old_free_purgeable(zone, ptr);
-}
-
-void* oom_killer_realloc_purgeable(struct _malloc_zone_t* zone,
-                                   void* ptr,
-                                   size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_realloc_purgeable(zone, ptr, size);
-  if (!result && size)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_memalign_purgeable(struct _malloc_zone_t* zone,
-                                    size_t alignment,
-                                    size_t size) {
-#if ARCH_CPU_32_BITS
-  ScopedClearErrno clear_errno;
-#endif  // ARCH_CPU_32_BITS
-  void* result = g_old_memalign_purgeable(zone, alignment, size);
-  // Only die if posix_memalign would have returned ENOMEM, since there are
-  // other reasons why NULL might be returned (see
-  // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c ).
-  if (!result && size && alignment >= sizeof(void*)
-      && (alignment & (alignment - 1)) == 0) {
-    debug::BreakDebugger();
-  }
-  return result;
-}
-
-// === C++ operator new ===
-
-void oom_killer_new() {
-  debug::BreakDebugger();
-}
-
-// === Core Foundation CFAllocators ===
-
-bool CanGetContextForCFAllocator() {
-  return !base::mac::IsOSLaterThanYosemite_DontCallThis();
-}
-
-CFAllocatorContext* ContextForCFAllocator(CFAllocatorRef allocator) {
-  if (base::mac::IsOSSnowLeopard()) {
-    ChromeCFAllocatorLeopards* our_allocator =
-        const_cast<ChromeCFAllocatorLeopards*>(
-            reinterpret_cast<const ChromeCFAllocatorLeopards*>(allocator));
-    return &our_allocator->_context;
-  } else if (base::mac::IsOSLion() ||
-             base::mac::IsOSMountainLion() ||
-             base::mac::IsOSMavericks() ||
-             base::mac::IsOSYosemite()) {
-    ChromeCFAllocatorLions* our_allocator =
-        const_cast<ChromeCFAllocatorLions*>(
-            reinterpret_cast<const ChromeCFAllocatorLions*>(allocator));
-    return &our_allocator->_context;
-  } else {
-    return NULL;
-  }
-}
-
-CFAllocatorAllocateCallBack g_old_cfallocator_system_default;
-CFAllocatorAllocateCallBack g_old_cfallocator_malloc;
-CFAllocatorAllocateCallBack g_old_cfallocator_malloc_zone;
-
-void* oom_killer_cfallocator_system_default(CFIndex alloc_size,
-                                            CFOptionFlags hint,
-                                            void* info) {
-  void* result = g_old_cfallocator_system_default(alloc_size, hint, info);
-  if (!result)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_cfallocator_malloc(CFIndex alloc_size,
-                                    CFOptionFlags hint,
-                                    void* info) {
-  void* result = g_old_cfallocator_malloc(alloc_size, hint, info);
-  if (!result)
-    debug::BreakDebugger();
-  return result;
-}
-
-void* oom_killer_cfallocator_malloc_zone(CFIndex alloc_size,
-                                         CFOptionFlags hint,
-                                         void* info) {
-  void* result = g_old_cfallocator_malloc_zone(alloc_size, hint, info);
-  if (!result)
-    debug::BreakDebugger();
-  return result;
-}
-
-// === Cocoa NSObject allocation ===
-
-typedef id (*allocWithZone_t)(id, SEL, NSZone*);
-allocWithZone_t g_old_allocWithZone;
-
-id oom_killer_allocWithZone(id self, SEL _cmd, NSZone* zone)
-{
-  id result = g_old_allocWithZone(self, _cmd, zone);
-  if (!result)
-    debug::BreakDebugger();
-  return result;
-}
-
-}  // namespace
-
-bool UncheckedMalloc(size_t size, void** result) {
-  if (g_old_malloc) {
-#if ARCH_CPU_32_BITS
-    ScopedClearErrno clear_errno;
-    ThreadLocalBooleanAutoReset flag(g_unchecked_alloc.Pointer(), true);
-#endif  // ARCH_CPU_32_BITS
-    *result = g_old_malloc(malloc_default_zone(), size);
-  } else {
-    *result = malloc(size);
-  }
-
-  return *result != NULL;
-}
-
-bool UncheckedCalloc(size_t num_items, size_t size, void** result) {
-  if (g_old_calloc) {
-#if ARCH_CPU_32_BITS
-    ScopedClearErrno clear_errno;
-    ThreadLocalBooleanAutoReset flag(g_unchecked_alloc.Pointer(), true);
-#endif  // ARCH_CPU_32_BITS
-    *result = g_old_calloc(malloc_default_zone(), num_items, size);
-  } else {
-    *result = calloc(num_items, size);
-  }
-
-  return *result != NULL;
-}
-
-void* UncheckedMalloc(size_t size) {
-  void* address;
-  return UncheckedMalloc(size, &address) ? address : NULL;
-}
-
-void* UncheckedCalloc(size_t num_items, size_t size) {
-  void* address;
-  return UncheckedCalloc(num_items, size, &address) ? address : NULL;
-}
-
-void EnableTerminationOnOutOfMemory() {
-  if (g_oom_killer_enabled)
-    return;
-
-  g_oom_killer_enabled = true;
-
-  // === C malloc/calloc/valloc/realloc/posix_memalign ===
-
-  // This approach is not perfect, as requests for amounts of memory larger than
-  // MALLOC_ABSOLUTE_MAX_SIZE (currently SIZE_T_MAX - (2 * PAGE_SIZE)) will
-  // still fail with a NULL rather than dying (see
-  // http://opensource.apple.com/source/Libc/Libc-583/gen/malloc.c for details).
-  // Unfortunately, it's the best we can do. Also note that this does not affect
-  // allocations from non-default zones.
-
-  CHECK(!g_old_malloc && !g_old_calloc && !g_old_valloc && !g_old_realloc &&
-        !g_old_memalign) << "Old allocators unexpectedly non-null";
-
-  CHECK(!g_old_malloc_purgeable && !g_old_calloc_purgeable &&
-        !g_old_valloc_purgeable && !g_old_realloc_purgeable &&
-        !g_old_memalign_purgeable) << "Old allocators unexpectedly non-null";
-
-#if !defined(ADDRESS_SANITIZER)
-  // Don't do anything special on OOM for the malloc zones replaced by
-  // AddressSanitizer, as modifying or protecting them may not work correctly.
-
-  ChromeMallocZone* default_zone =
-      reinterpret_cast<ChromeMallocZone*>(malloc_default_zone());
-  ChromeMallocZone* purgeable_zone =
-      reinterpret_cast<ChromeMallocZone*>(malloc_default_purgeable_zone());
-
-  mach_vm_address_t default_reprotection_start = 0;
-  mach_vm_size_t default_reprotection_length = 0;
-  vm_prot_t default_reprotection_value = VM_PROT_NONE;
-  DeprotectMallocZone(default_zone,
-                      &default_reprotection_start,
-                      &default_reprotection_length,
-                      &default_reprotection_value);
-
-  mach_vm_address_t purgeable_reprotection_start = 0;
-  mach_vm_size_t purgeable_reprotection_length = 0;
-  vm_prot_t purgeable_reprotection_value = VM_PROT_NONE;
-  if (purgeable_zone) {
-    DeprotectMallocZone(purgeable_zone,
-                        &purgeable_reprotection_start,
-                        &purgeable_reprotection_length,
-                        &purgeable_reprotection_value);
-  }
-
-  // Default zone
-
-  g_old_malloc = default_zone->malloc;
-  g_old_calloc = default_zone->calloc;
-  g_old_valloc = default_zone->valloc;
-  g_old_free = default_zone->free;
-  g_old_realloc = default_zone->realloc;
-  CHECK(g_old_malloc && g_old_calloc && g_old_valloc && g_old_free &&
-        g_old_realloc)
-      << "Failed to get system allocation functions.";
-
-  default_zone->malloc = oom_killer_malloc;
-  default_zone->calloc = oom_killer_calloc;
-  default_zone->valloc = oom_killer_valloc;
-  default_zone->free = oom_killer_free;
-  default_zone->realloc = oom_killer_realloc;
-
-  if (default_zone->version >= 5) {
-    g_old_memalign = default_zone->memalign;
-    if (g_old_memalign)
-      default_zone->memalign = oom_killer_memalign;
-  }
-
-  // Purgeable zone (if it exists)
-
-  if (purgeable_zone) {
-    g_old_malloc_purgeable = purgeable_zone->malloc;
-    g_old_calloc_purgeable = purgeable_zone->calloc;
-    g_old_valloc_purgeable = purgeable_zone->valloc;
-    g_old_free_purgeable = purgeable_zone->free;
-    g_old_realloc_purgeable = purgeable_zone->realloc;
-    CHECK(g_old_malloc_purgeable && g_old_calloc_purgeable &&
-          g_old_valloc_purgeable && g_old_free_purgeable &&
-          g_old_realloc_purgeable)
-        << "Failed to get system allocation functions.";
-
-    purgeable_zone->malloc = oom_killer_malloc_purgeable;
-    purgeable_zone->calloc = oom_killer_calloc_purgeable;
-    purgeable_zone->valloc = oom_killer_valloc_purgeable;
-    purgeable_zone->free = oom_killer_free_purgeable;
-    purgeable_zone->realloc = oom_killer_realloc_purgeable;
-
-    if (purgeable_zone->version >= 5) {
-      g_old_memalign_purgeable = purgeable_zone->memalign;
-      if (g_old_memalign_purgeable)
-        purgeable_zone->memalign = oom_killer_memalign_purgeable;
-    }
-  }
-
-  // Restore protection if it was active.
-
-  if (default_reprotection_start) {
-    kern_return_t result = mach_vm_protect(mach_task_self(),
-                                           default_reprotection_start,
-                                           default_reprotection_length,
-                                           false,
-                                           default_reprotection_value);
-    MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
-  }
-
-  if (purgeable_reprotection_start) {
-    kern_return_t result = mach_vm_protect(mach_task_self(),
-                                           purgeable_reprotection_start,
-                                           purgeable_reprotection_length,
-                                           false,
-                                           purgeable_reprotection_value);
-    MACH_CHECK(result == KERN_SUCCESS, result) << "mach_vm_protect";
-  }
-#endif
-
-  // === C malloc_zone_batch_malloc ===
-
-  // batch_malloc is omitted because the default malloc zone's implementation
-  // only supports batch_malloc for "tiny" allocations from the free list. It
-  // will fail for allocations larger than "tiny", and will only allocate as
-  // many blocks as it's able to from the free list. These factors mean that it
-  // can return less than the requested memory even in a non-out-of-memory
-  // situation. There's no good way to detect whether a batch_malloc failure is
-  // due to these other factors, or due to genuine memory or address space
-  // exhaustion. The fact that it only allocates space from the "tiny" free list
-  // means that it's likely that a failure will not be due to memory exhaustion.
-  // Similarly, these constraints on batch_malloc mean that callers must always
-  // be expecting to receive less memory than was requested, even in situations
-  // where memory pressure is not a concern. Finally, the only public interface
-  // to batch_malloc is malloc_zone_batch_malloc, which is specific to the
-  // system's malloc implementation. It's unlikely that anyone's even heard of
-  // it.
-
-  // === C++ operator new ===
-
-  // Yes, operator new does call through to malloc, but this will catch failures
-  // that our imperfect handling of malloc cannot.
-
-  std::set_new_handler(oom_killer_new);
-
-#ifndef ADDRESS_SANITIZER
-  // === Core Foundation CFAllocators ===
-
-  // This will not catch allocation done by custom allocators, but will catch
-  // all allocation done by system-provided ones.
-
-  CHECK(!g_old_cfallocator_system_default && !g_old_cfallocator_malloc &&
-        !g_old_cfallocator_malloc_zone)
-      << "Old allocators unexpectedly non-null";
-
-  bool cf_allocator_internals_known = CanGetContextForCFAllocator();
-
-  if (cf_allocator_internals_known) {
-    CFAllocatorContext* context =
-        ContextForCFAllocator(kCFAllocatorSystemDefault);
-    CHECK(context) << "Failed to get context for kCFAllocatorSystemDefault.";
-    g_old_cfallocator_system_default = context->allocate;
-    CHECK(g_old_cfallocator_system_default)
-        << "Failed to get kCFAllocatorSystemDefault allocation function.";
-    context->allocate = oom_killer_cfallocator_system_default;
-
-    context = ContextForCFAllocator(kCFAllocatorMalloc);
-    CHECK(context) << "Failed to get context for kCFAllocatorMalloc.";
-    g_old_cfallocator_malloc = context->allocate;
-    CHECK(g_old_cfallocator_malloc)
-        << "Failed to get kCFAllocatorMalloc allocation function.";
-    context->allocate = oom_killer_cfallocator_malloc;
-
-    context = ContextForCFAllocator(kCFAllocatorMallocZone);
-    CHECK(context) << "Failed to get context for kCFAllocatorMallocZone.";
-    g_old_cfallocator_malloc_zone = context->allocate;
-    CHECK(g_old_cfallocator_malloc_zone)
-        << "Failed to get kCFAllocatorMallocZone allocation function.";
-    context->allocate = oom_killer_cfallocator_malloc_zone;
-  } else {
-    DLOG(WARNING) << "Internals of CFAllocator not known; out-of-memory "
-                     "failures via CFAllocator will not result in termination. "
-                     "http://crbug.com/45650";
-  }
-#endif
-
-  // === Cocoa NSObject allocation ===
-
-  // Note that both +[NSObject new] and +[NSObject alloc] call through to
-  // +[NSObject allocWithZone:].
-
-  CHECK(!g_old_allocWithZone)
-      << "Old allocator unexpectedly non-null";
-
-  Class nsobject_class = [NSObject class];
-  Method orig_method = class_getClassMethod(nsobject_class,
-                                            @selector(allocWithZone:));
-  g_old_allocWithZone = reinterpret_cast<allocWithZone_t>(
-      method_getImplementation(orig_method));
-  CHECK(g_old_allocWithZone)
-      << "Failed to get allocWithZone allocation function.";
-  method_setImplementation(orig_method,
-                           reinterpret_cast<IMP>(oom_killer_allocWithZone));
-}
-
-}  // namespace base

+ 0 - 19
src/butil/process/memory_stubs.cc

@@ -1,19 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/memory.h"
-
-namespace butil {
-
-void EnableTerminationOnOutOfMemory() {
-}
-
-void EnableTerminationOnHeapCorruption() {
-}
-
-bool AdjustOOMScore(ProcessId process, int score) {
-  return false;
-}
-
-}  // namespace butil

+ 0 - 70
src/butil/process/process.h

@@ -1,70 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_PROCESS_PROCESS_PROCESS_H_
-#define BASE_PROCESS_PROCESS_PROCESS_H_
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/process/process_handle.h"
-#include "butil/build_config.h"
-
-namespace butil {
-
-class BASE_EXPORT Process {
- public:
-  Process() : process_(kNullProcessHandle) {
-  }
-
-  explicit Process(ProcessHandle handle) : process_(handle) {
-  }
-
-  // A handle to the current process.
-  static Process Current();
-
-  static bool CanBackgroundProcesses();
-
-  // Get/Set the handle for this process. The handle will be 0 if the process
-  // is no longer running.
-  ProcessHandle handle() const { return process_; }
-  void set_handle(ProcessHandle handle) {
-    process_ = handle;
-  }
-
-  // Get the PID for this process.
-  ProcessId pid() const;
-
-  // Is the this process the current process.
-  bool is_current() const;
-
-  // Close the process handle. This will not terminate the process.
-  void Close();
-
-  // Terminates the process with extreme prejudice. The given result code will
-  // be the exit code of the process. If the process has already exited, this
-  // will do nothing.
-  void Terminate(int result_code);
-
-  // A process is backgrounded when it's priority is lower than normal.
-  // Return true if this process is backgrounded, false otherwise.
-  bool IsProcessBackgrounded() const;
-
-  // Set a process as backgrounded. If value is true, the priority
-  // of the process will be lowered. If value is false, the priority
-  // of the process will be made "normal" - equivalent to default
-  // process priority.
-  // Returns true if the priority was changed, false otherwise.
-  bool SetProcessBackgrounded(bool value);
-
-  // Returns an integer representing the priority of a process. The meaning
-  // of this value is OS dependent.
-  int GetPriority() const;
-
- private:
-  ProcessHandle process_;
-};
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_PROCESS_PROCESS_H_

+ 0 - 94
src/butil/process/process_handle.h

@@ -1,94 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_PROCESS_PROCESS_HANDLE_H_
-#define BASE_PROCESS_PROCESS_HANDLE_H_
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/files/file_path.h"
-#include "butil/build_config.h"
-
-#include <sys/types.h>
-#if defined(OS_WIN)
-#include <windows.h>
-#endif
-
-namespace butil {
-
-// ProcessHandle is a platform specific type which represents the underlying OS
-// handle to a process.
-// ProcessId is a number which identifies the process in the OS.
-#if defined(OS_WIN)
-typedef HANDLE ProcessHandle;
-typedef DWORD ProcessId;
-typedef HANDLE UserTokenHandle;
-const ProcessHandle kNullProcessHandle = NULL;
-const ProcessId kNullProcessId = 0;
-#elif defined(OS_POSIX)
-// On POSIX, our ProcessHandle will just be the PID.
-typedef pid_t ProcessHandle;
-typedef pid_t ProcessId;
-const ProcessHandle kNullProcessHandle = 0;
-const ProcessId kNullProcessId = 0;
-#endif  // defined(OS_WIN)
-
-// Returns the id of the current process.
-BASE_EXPORT ProcessId GetCurrentProcId();
-
-// Returns the ProcessHandle of the current process.
-BASE_EXPORT ProcessHandle GetCurrentProcessHandle();
-
-// Converts a PID to a process handle. This handle must be closed by
-// CloseProcessHandle when you are done with it. Returns true on success.
-BASE_EXPORT bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle);
-
-// Converts a PID to a process handle. On Windows the handle is opened
-// with more access rights and must only be used by trusted code.
-// You have to close returned handle using CloseProcessHandle. Returns true
-// on success.
-// TODO(sanjeevr): Replace all calls to OpenPrivilegedProcessHandle with the
-// more specific OpenProcessHandleWithAccess method and delete this.
-BASE_EXPORT bool OpenPrivilegedProcessHandle(ProcessId pid,
-                                             ProcessHandle* handle);
-
-// Converts a PID to a process handle using the desired access flags. Use a
-// combination of the kProcessAccess* flags defined above for |access_flags|.
-BASE_EXPORT bool OpenProcessHandleWithAccess(ProcessId pid,
-                                             uint32_t access_flags,
-                                             ProcessHandle* handle);
-
-// Closes the process handle opened by OpenProcessHandle.
-BASE_EXPORT void CloseProcessHandle(ProcessHandle process);
-
-// Returns the unique ID for the specified process. This is functionally the
-// same as Windows' GetProcessId(), but works on versions of Windows before
-// Win XP SP1 as well.
-BASE_EXPORT ProcessId GetProcId(ProcessHandle process);
-
-#if defined(OS_WIN)
-enum IntegrityLevel {
-  INTEGRITY_UNKNOWN,
-  LOW_INTEGRITY,
-  MEDIUM_INTEGRITY,
-  HIGH_INTEGRITY,
-};
-// Determine the integrity level of the specified process. Returns false
-// if the system does not support integrity levels (pre-Vista) or in the case
-// of an underlying system failure.
-BASE_EXPORT bool GetProcessIntegrityLevel(ProcessHandle process,
-                                          IntegrityLevel* level);
-#endif
-
-#if defined(OS_POSIX)
-// Returns the path to the executable of the given process.
-BASE_EXPORT FilePath GetProcessExecutablePath(ProcessHandle process);
-
-// Returns the ID for the parent of the given process.
-BASE_EXPORT ProcessId GetParentProcessId(ProcessHandle process);
-#endif
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_PROCESS_HANDLE_H_

+ 0 - 40
src/butil/process/process_handle_freebsd.cc

@@ -1,40 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_handle.h"
-
-#include <sys/sysctl.h>
-#include <sys/types.h>
-#include <sys/user.h>
-#include <unistd.h>
-
-namespace butil {
-
-ProcessId GetParentProcessId(ProcessHandle process) {
-  struct kinfo_proc info;
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process };
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return -1;
-
-  return info.ki_ppid;
-}
-
-FilePath GetProcessExecutablePath(ProcessHandle process) {
-  char pathname[PATH_MAX];
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, process };
-
-  length = sizeof(pathname);
-
-  if (sysctl(mib, arraysize(mib), pathname, &length, NULL, 0) < 0 ||
-      length == 0) {
-    return FilePath();
-  }
-
-  return FilePath(std::string(pathname));
-}
-
-}  // namespace butil

+ 0 - 30
src/butil/process/process_handle_linux.cc

@@ -1,30 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_handle.h"
-
-#include "butil/file_util.h"
-#include "butil/process/internal_linux.h"
-
-namespace butil {
-
-ProcessId GetParentProcessId(ProcessHandle process) {
-  ProcessId pid =
-      internal::ReadProcStatsAndGetFieldAsInt64(process, internal::VM_PPID);
-  if (pid)
-    return pid;
-  return -1;
-}
-
-FilePath GetProcessExecutablePath(ProcessHandle process) {
-  FilePath stat_file = internal::GetProcPidDir(process).Append("exe");
-  FilePath exe_name;
-  if (!ReadSymbolicLink(stat_file, &exe_name)) {
-    // No such process.  Happens frequently in e.g. TerminateAllChromeProcesses
-    return FilePath();
-  }
-  return exe_name;
-}
-
-}  // namespace butil

+ 0 - 36
src/butil/process/process_handle_mac.cc

@@ -1,36 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_handle.h"
-
-#include <libproc.h>
-#include <sys/sysctl.h>
-#include <sys/types.h>
-
-#include "butil/logging.h"
-
-namespace butil {
-
-ProcessId GetParentProcessId(ProcessHandle process) {
-  struct kinfo_proc info;
-  size_t length = sizeof(struct kinfo_proc);
-  int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process };
-  if (sysctl(mib, 4, &info, &length, NULL, 0) < 0) {
-    DPLOG(ERROR) << "sysctl";
-    return -1;
-  }
-  if (length == 0)
-    return -1;
-  return info.kp_eproc.e_ppid;
-}
-
-FilePath GetProcessExecutablePath(ProcessHandle process) {
-  char pathbuf[PROC_PIDPATHINFO_MAXSIZE];
-  if (!proc_pidpath(process, pathbuf, sizeof(pathbuf)))
-    return FilePath();
-
-  return FilePath(pathbuf);
-}
-
-}  // namespace butil

+ 0 - 49
src/butil/process/process_handle_openbsd.cc

@@ -1,49 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_handle.h"
-
-#include <sys/sysctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-namespace butil {
-
-ProcessId GetParentProcessId(ProcessHandle process) {
-  struct kinfo_proc info;
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process,
-                sizeof(struct kinfo_proc), 0 };
-
-  if (sysctl(mib, arraysize(mib), NULL, &length, NULL, 0) < 0)
-    return -1;
-
-  mib[5] = (length / sizeof(struct kinfo_proc));
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return -1;
-
-  return info.p_ppid;
-}
-
-FilePath GetProcessExecutablePath(ProcessHandle process) {
-  struct kinfo_proc kp;
-  size_t len;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process,
-                sizeof(struct kinfo_proc), 0 };
-
-  if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) == -1)
-    return FilePath();
-  mib[5] = (len / sizeof(struct kinfo_proc));
-  if (sysctl(mib, arraysize(mib), &kp, &len, NULL, 0) < 0)
-    return FilePath();
-  if ((kp.p_flag & P_SYSTEM) != 0)
-    return FilePath();
-  if (strcmp(kp.p_comm, "chrome") == 0)
-    return FilePath(kp.p_comm);
-
-  return FilePath();
-}
-
-}  // namespace butil

+ 0 - 49
src/butil/process/process_handle_posix.cc

@@ -1,49 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_handle.h"
-
-#include <unistd.h>
-
-namespace butil {
-
-ProcessId GetCurrentProcId() {
-  return getpid();
-}
-
-ProcessHandle GetCurrentProcessHandle() {
-  return GetCurrentProcId();
-}
-
-bool OpenProcessHandle(ProcessId pid, ProcessHandle* handle) {
-  // On Posix platforms, process handles are the same as PIDs, so we
-  // don't need to do anything.
-  *handle = pid;
-  return true;
-}
-
-bool OpenPrivilegedProcessHandle(ProcessId pid, ProcessHandle* handle) {
-  // On POSIX permissions are checked for each operation on process,
-  // not when opening a "handle".
-  return OpenProcessHandle(pid, handle);
-}
-
-bool OpenProcessHandleWithAccess(ProcessId pid,
-                                 uint32_t access_flags,
-                                 ProcessHandle* handle) {
-  // On POSIX permissions are checked for each operation on process,
-  // not when opening a "handle".
-  return OpenProcessHandle(pid, handle);
-}
-
-void CloseProcessHandle(ProcessHandle process) {
-  // See OpenProcessHandle, nothing to do.
-  return;
-}
-
-ProcessId GetProcId(ProcessHandle process) {
-  return process;
-}
-
-}  // namespace butil

+ 0 - 25
src/butil/process/process_info.h

@@ -1,25 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_PROCESS_PROCESS_PROCESS_INFO_H_
-#define BASE_PROCESS_PROCESS_PROCESS_INFO_H_
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-
-namespace butil {
-
-class Time;
-
-// Vends information about the current process.
-class BASE_EXPORT CurrentProcessInfo {
- public:
-  // Returns the time at which the process was launched. May be empty if an
-  // error occurred retrieving the information.
-  static const Time CreationTime();
-};
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_PROCESS_PROCESS_INFO_H_

+ 0 - 27
src/butil/process/process_info_linux.cc

@@ -1,27 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_info.h"
-
-#include "butil/basictypes.h"
-#include "butil/logging.h"
-#include "butil/process/internal_linux.h"
-#include "butil/process/process_handle.h"
-#include "butil/time/time.h"
-
-namespace butil {
-
-//static
-const Time CurrentProcessInfo::CreationTime() {
-  ProcessHandle pid = GetCurrentProcessHandle();
-  int64_t start_ticks =
-      internal::ReadProcStatsAndGetFieldAsInt64(pid, internal::VM_STARTTIME);
-  DCHECK(start_ticks);
-  TimeDelta start_offset = internal::ClockTicksToTimeDelta(start_ticks);
-  Time boot_time = internal::GetBootTime();
-  DCHECK(!boot_time.is_null());
-  return Time(boot_time + start_offset);
-}
-
-}  // namespace butil

+ 0 - 31
src/butil/process/process_info_mac.cc

@@ -1,31 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_info.h"
-
-#include <sys/sysctl.h>
-#include <sys/time.h>
-#include <unistd.h>
-
-#include "butil/basictypes.h"
-#include "butil/memory/scoped_ptr.h"
-#include "butil/time/time.h"
-
-namespace butil {
-
-//static
-const Time CurrentProcessInfo::CreationTime() {
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
-  size_t len = 0;
-  if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0)
-    return Time();
-
-  scoped_ptr<struct kinfo_proc, butil::FreeDeleter>
-      proc(static_cast<struct kinfo_proc*>(malloc(len)));
-  if (sysctl(mib, arraysize(mib), proc.get(), &len, NULL, 0) < 0)
-    return Time();
-  return Time::FromTimeVal(proc->kp_proc.p_un.__p_starttime);
-}
-
-}  // namespace butil

+ 0 - 65
src/butil/process/process_iterator.cc

@@ -1,65 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_iterator.h"
-
-namespace butil {
-
-#if defined(OS_POSIX)
-ProcessEntry::ProcessEntry() : pid_(0), ppid_(0), gid_(0) {}
-ProcessEntry::~ProcessEntry() {}
-#endif
-
-const ProcessEntry* ProcessIterator::NextProcessEntry() {
-  bool result = false;
-  do {
-    result = CheckForNextProcess();
-  } while (result && !IncludeEntry());
-  if (result)
-    return &entry_;
-  return NULL;
-}
-
-ProcessIterator::ProcessEntries ProcessIterator::Snapshot() {
-  ProcessEntries found;
-  while (const ProcessEntry* process_entry = NextProcessEntry()) {
-    found.push_back(*process_entry);
-  }
-  return found;
-}
-
-bool ProcessIterator::IncludeEntry() {
-  return !filter_ || filter_->Includes(entry_);
-}
-
-NamedProcessIterator::NamedProcessIterator(
-    const FilePath::StringType& executable_name,
-    const ProcessFilter* filter) : ProcessIterator(filter),
-                                   executable_name_(executable_name) {
-#if defined(OS_ANDROID)
-  // On Android, the process name contains only the last 15 characters, which
-  // is in file /proc/<pid>/stat, the string between open parenthesis and close
-  // parenthesis. Please See ProcessIterator::CheckForNextProcess for details.
-  // Now if the length of input process name is greater than 15, only save the
-  // last 15 characters.
-  if (executable_name_.size() > 15) {
-    executable_name_ = FilePath::StringType(executable_name_,
-                                            executable_name_.size() - 15, 15);
-  }
-#endif
-}
-
-NamedProcessIterator::~NamedProcessIterator() {
-}
-
-int GetProcessCount(const FilePath::StringType& executable_name,
-                    const ProcessFilter* filter) {
-  int count = 0;
-  NamedProcessIterator iter(executable_name, filter);
-  while (iter.NextProcessEntry())
-    ++count;
-  return count;
-}
-
-}  // namespace butil

+ 0 - 185
src/butil/process/process_iterator.h

@@ -1,185 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains methods to iterate over processes on the system.
-
-#ifndef BASE_PROCESS_PROCESS_ITERATOR_H_
-#define BASE_PROCESS_PROCESS_ITERATOR_H_
-
-#include <list>
-#include <string>
-#include <vector>
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/files/file_path.h"
-#include "butil/process/process.h"
-#include "butil/build_config.h"
-
-#if defined(OS_WIN)
-#include <windows.h>
-#include <tlhelp32.h>
-#elif defined(OS_MACOSX) || defined(OS_OPENBSD)
-#include <sys/sysctl.h>
-#elif defined(OS_FREEBSD)
-#include <sys/user.h>
-#elif defined(OS_POSIX)
-#include <dirent.h>
-#endif
-
-namespace butil {
-
-#if defined(OS_WIN)
-struct ProcessEntry : public PROCESSENTRY32 {
-  ProcessId pid() const { return th32ProcessID; }
-  ProcessId parent_pid() const { return th32ParentProcessID; }
-  const wchar_t* exe_file() const { return szExeFile; }
-};
-
-// Process access masks. These constants provide platform-independent
-// definitions for the standard Windows access masks.
-// See http://msdn.microsoft.com/en-us/library/ms684880(VS.85).aspx for
-// the specific semantics of each mask value.
-const uint32_t kProcessAccessTerminate              = PROCESS_TERMINATE;
-const uint32_t kProcessAccessCreateThread           = PROCESS_CREATE_THREAD;
-const uint32_t kProcessAccessSetSessionId           = PROCESS_SET_SESSIONID;
-const uint32_t kProcessAccessVMOperation            = PROCESS_VM_OPERATION;
-const uint32_t kProcessAccessVMRead                 = PROCESS_VM_READ;
-const uint32_t kProcessAccessVMWrite                = PROCESS_VM_WRITE;
-const uint32_t kProcessAccessDuplicateHandle        = PROCESS_DUP_HANDLE;
-const uint32_t kProcessAccessCreateProcess          = PROCESS_CREATE_PROCESS;
-const uint32_t kProcessAccessSetQuota               = PROCESS_SET_QUOTA;
-const uint32_t kProcessAccessSetInformation         = PROCESS_SET_INFORMATION;
-const uint32_t kProcessAccessQueryInformation       = PROCESS_QUERY_INFORMATION;
-const uint32_t kProcessAccessSuspendResume          = PROCESS_SUSPEND_RESUME;
-const uint32_t kProcessAccessQueryLimitedInfomation =
-    PROCESS_QUERY_LIMITED_INFORMATION;
-const uint32_t kProcessAccessWaitForTermination     = SYNCHRONIZE;
-#elif defined(OS_POSIX)
-struct BASE_EXPORT ProcessEntry {
-  ProcessEntry();
-  ~ProcessEntry();
-
-  ProcessId pid() const { return pid_; }
-  ProcessId parent_pid() const { return ppid_; }
-  ProcessId gid() const { return gid_; }
-  const char* exe_file() const { return exe_file_.c_str(); }
-  const std::vector<std::string>& cmd_line_args() const {
-    return cmd_line_args_;
-  }
-
-  ProcessId pid_;
-  ProcessId ppid_;
-  ProcessId gid_;
-  std::string exe_file_;
-  std::vector<std::string> cmd_line_args_;
-};
-
-// Process access masks. They are not used on Posix because access checking
-// does not happen during handle creation.
-const uint32_t kProcessAccessTerminate              = 0;
-const uint32_t kProcessAccessCreateThread           = 0;
-const uint32_t kProcessAccessSetSessionId           = 0;
-const uint32_t kProcessAccessVMOperation            = 0;
-const uint32_t kProcessAccessVMRead                 = 0;
-const uint32_t kProcessAccessVMWrite                = 0;
-const uint32_t kProcessAccessDuplicateHandle        = 0;
-const uint32_t kProcessAccessCreateProcess          = 0;
-const uint32_t kProcessAccessSetQuota               = 0;
-const uint32_t kProcessAccessSetInformation         = 0;
-const uint32_t kProcessAccessQueryInformation       = 0;
-const uint32_t kProcessAccessSuspendResume          = 0;
-const uint32_t kProcessAccessQueryLimitedInfomation = 0;
-const uint32_t kProcessAccessWaitForTermination     = 0;
-#endif  // defined(OS_POSIX)
-
-// Used to filter processes by process ID.
-class ProcessFilter {
- public:
-  // Returns true to indicate set-inclusion and false otherwise.  This method
-  // should not have side-effects and should be idempotent.
-  virtual bool Includes(const ProcessEntry& entry) const = 0;
-
- protected:
-  virtual ~ProcessFilter() {}
-};
-
-// This class provides a way to iterate through a list of processes on the
-// current machine with a specified filter.
-// To use, create an instance and then call NextProcessEntry() until it returns
-// false.
-class BASE_EXPORT ProcessIterator {
- public:
-  typedef std::list<ProcessEntry> ProcessEntries;
-
-  explicit ProcessIterator(const ProcessFilter* filter);
-  virtual ~ProcessIterator();
-
-  // If there's another process that matches the given executable name,
-  // returns a const pointer to the corresponding PROCESSENTRY32.
-  // If there are no more matching processes, returns NULL.
-  // The returned pointer will remain valid until NextProcessEntry()
-  // is called again or this NamedProcessIterator goes out of scope.
-  const ProcessEntry* NextProcessEntry();
-
-  // Takes a snapshot of all the ProcessEntry found.
-  ProcessEntries Snapshot();
-
- protected:
-  virtual bool IncludeEntry();
-  const ProcessEntry& entry() { return entry_; }
-
- private:
-  // Determines whether there's another process (regardless of executable)
-  // left in the list of all processes.  Returns true and sets entry_ to
-  // that process's info if there is one, false otherwise.
-  bool CheckForNextProcess();
-
-  // Initializes a PROCESSENTRY32 data structure so that it's ready for
-  // use with Process32First/Process32Next.
-  void InitProcessEntry(ProcessEntry* entry);
-
-#if defined(OS_WIN)
-  HANDLE snapshot_;
-  bool started_iteration_;
-#elif defined(OS_MACOSX) || defined(OS_BSD)
-  std::vector<kinfo_proc> kinfo_procs_;
-  size_t index_of_kinfo_proc_;
-#elif defined(OS_POSIX)
-  DIR* procfs_dir_;
-#endif
-  ProcessEntry entry_;
-  const ProcessFilter* filter_;
-
-  DISALLOW_COPY_AND_ASSIGN(ProcessIterator);
-};
-
-// This class provides a way to iterate through the list of processes
-// on the current machine that were started from the given executable
-// name.  To use, create an instance and then call NextProcessEntry()
-// until it returns false.
-class BASE_EXPORT NamedProcessIterator : public ProcessIterator {
- public:
-  NamedProcessIterator(const FilePath::StringType& executable_name,
-                       const ProcessFilter* filter);
-  virtual ~NamedProcessIterator();
-
- protected:
-  virtual bool IncludeEntry() OVERRIDE;
-
- private:
-  FilePath::StringType executable_name_;
-
-  DISALLOW_COPY_AND_ASSIGN(NamedProcessIterator);
-};
-
-// Returns the number of processes on the machine that are running from the
-// given executable name.  If filter is non-null, then only processes selected
-// by the filter will be counted.
-BASE_EXPORT int GetProcessCount(const FilePath::StringType& executable_name,
-                                const ProcessFilter* filter);
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_PROCESS_ITERATOR_H_

+ 0 - 126
src/butil/process/process_iterator_freebsd.cc

@@ -1,126 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_iterator.h"
-
-#include <sys/types.h>
-#include <sys/sysctl.h>
-#include <unistd.h>
-
-#include "butil/logging.h"
-#include "butil/strings/string_util.h"
-
-namespace butil {
-
-ProcessIterator::ProcessIterator(const ProcessFilter* filter)
-    : index_of_kinfo_proc_(),
-      filter_(filter) {
-
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_UID, getuid() };
-
-  bool done = false;
-  int try_num = 1;
-  const int max_tries = 10;
-
-  do {
-    size_t len = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to get the size needed for the process list";
-      kinfo_procs_.resize(0);
-      done = true;
-    } else {
-      size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-      // Leave some spare room for process table growth (more could show up
-      // between when we check and now)
-      num_of_kinfo_proc += 16;
-      kinfo_procs_.resize(num_of_kinfo_proc);
-      len = num_of_kinfo_proc * sizeof(struct kinfo_proc);
-      if (sysctl(mib, arraysize(mib), &kinfo_procs_[0], &len, NULL, 0) <0) {
-        // If we get a mem error, it just means we need a bigger buffer, so
-        // loop around again.  Anything else is a real error and give up.
-        if (errno != ENOMEM) {
-          LOG(ERROR) << "failed to get the process list";
-          kinfo_procs_.resize(0);
-          done = true;
-        }
-      } else {
-        // Got the list, just make sure we're sized exactly right
-        size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-        kinfo_procs_.resize(num_of_kinfo_proc);
-        done = true;
-      }
-    }
-  } while (!done && (try_num++ < max_tries));
-
-  if (!done) {
-    LOG(ERROR) << "failed to collect the process list in a few tries";
-    kinfo_procs_.resize(0);
-  }
-}
-
-ProcessIterator::~ProcessIterator() {
-}
-
-bool ProcessIterator::CheckForNextProcess() {
-  std::string data;
-
-  for (; index_of_kinfo_proc_ < kinfo_procs_.size(); ++index_of_kinfo_proc_) {
-    size_t length;
-    struct kinfo_proc kinfo = kinfo_procs_[index_of_kinfo_proc_];
-    int mib[] = { CTL_KERN, KERN_PROC_ARGS, kinfo.ki_pid };
-
-    if ((kinfo.ki_pid > 0) && (kinfo.ki_stat == SZOMB))
-      continue;
-
-    length = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &length, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to figure out the buffer size for a command line";
-      continue;
-    }
-
-    data.resize(length);
-
-    if (sysctl(mib, arraysize(mib), &data[0], &length, NULL, 0) < 0) {
-      LOG(ERROR) << "failed to fetch a commandline";
-      continue;
-    }
-
-    std::string delimiters;
-    delimiters.push_back('\0');
-    Tokenize(data, delimiters, &entry_.cmd_line_args_);
-
-    size_t exec_name_end = data.find('\0');
-    if (exec_name_end == std::string::npos) {
-      LOG(ERROR) << "command line data didn't match expected format";
-      continue;
-    }
-
-    entry_.pid_ = kinfo.ki_pid;
-    entry_.ppid_ = kinfo.ki_ppid;
-    entry_.gid_ = kinfo.ki_pgid;
-
-    size_t last_slash = data.rfind('/', exec_name_end);
-    if (last_slash == std::string::npos) {
-      entry_.exe_file_.assign(data, 0, exec_name_end);
-    } else {
-      entry_.exe_file_.assign(data, last_slash + 1,
-                              exec_name_end - last_slash - 1);
-    }
-
-    // Start w/ the next entry next time through
-    ++index_of_kinfo_proc_;
-
-    return true;
-  }
-  return false;
-}
-
-bool NamedProcessIterator::IncludeEntry() {
-  if (executable_name_ != entry().exe_file())
-    return false;
-
-  return ProcessIterator::IncludeEntry();
-}
-
-}  // namespace butil

+ 0 - 137
src/butil/process/process_iterator_linux.cc

@@ -1,137 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_iterator.h"
-
-#include "butil/file_util.h"
-#include "butil/logging.h"
-#include "butil/process/internal_linux.h"
-#include "butil/strings/string_util.h"
-#include "butil/threading/thread_restrictions.h"
-
-namespace butil {
-
-namespace {
-
-// Reads the |field_num|th field from |proc_stats|.
-// Returns an empty string on failure.
-// This version only handles VM_COMM and VM_STATE, which are the only fields
-// that are strings.
-std::string GetProcStatsFieldAsString(
-    const std::vector<std::string>& proc_stats,
-    internal::ProcStatsFields field_num) {
-  if (field_num < internal::VM_COMM || field_num > internal::VM_STATE) {
-    NOTREACHED();
-    return std::string();
-  }
-
-  if (proc_stats.size() > static_cast<size_t>(field_num))
-    return proc_stats[field_num];
-
-  NOTREACHED();
-  return 0;
-}
-
-// Reads /proc/<pid>/cmdline and populates |proc_cmd_line_args| with the command
-// line arguments. Returns true if successful.
-// Note: /proc/<pid>/cmdline contains command line arguments separated by single
-// null characters. We tokenize it into a vector of strings using '\0' as a
-// delimiter.
-bool GetProcCmdline(pid_t pid, std::vector<std::string>* proc_cmd_line_args) {
-  // Synchronously reading files in /proc is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  FilePath cmd_line_file = internal::GetProcPidDir(pid).Append("cmdline");
-  std::string cmd_line;
-  if (!ReadFileToString(cmd_line_file, &cmd_line))
-    return false;
-  std::string delimiters;
-  delimiters.push_back('\0');
-  Tokenize(cmd_line, delimiters, proc_cmd_line_args);
-  return true;
-}
-
-}  // namespace
-
-ProcessIterator::ProcessIterator(const ProcessFilter* filter)
-    : filter_(filter) {
-  procfs_dir_ = opendir(internal::kProcDir);
-}
-
-ProcessIterator::~ProcessIterator() {
-  if (procfs_dir_) {
-    closedir(procfs_dir_);
-    procfs_dir_ = NULL;
-  }
-}
-
-bool ProcessIterator::CheckForNextProcess() {
-  // TODO(port): skip processes owned by different UID
-
-  pid_t pid = kNullProcessId;
-  std::vector<std::string> cmd_line_args;
-  std::string stats_data;
-  std::vector<std::string> proc_stats;
-
-  // Arbitrarily guess that there will never be more than 200 non-process
-  // files in /proc.  Hardy has 53 and Lucid has 61.
-  int skipped = 0;
-  const int kSkipLimit = 200;
-  while (skipped < kSkipLimit) {
-    dirent* slot = readdir(procfs_dir_);
-    // all done looking through /proc?
-    if (!slot)
-      return false;
-
-    // If not a process, keep looking for one.
-    pid = internal::ProcDirSlotToPid(slot->d_name);
-    if (!pid) {
-      skipped++;
-      continue;
-    }
-
-    if (!GetProcCmdline(pid, &cmd_line_args))
-      continue;
-
-    if (!internal::ReadProcStats(pid, &stats_data))
-      continue;
-    if (!internal::ParseProcStats(stats_data, &proc_stats))
-      continue;
-
-    std::string runstate =
-        GetProcStatsFieldAsString(proc_stats, internal::VM_STATE);
-    if (runstate.size() != 1) {
-      NOTREACHED();
-      continue;
-    }
-
-    // Is the process in 'Zombie' state, i.e. dead but waiting to be reaped?
-    // Allowed values: D R S T Z
-    if (runstate[0] != 'Z')
-      break;
-
-    // Nope, it's a zombie; somebody isn't cleaning up after their children.
-    // (e.g. WaitForProcessesToExit doesn't clean up after dead children yet.)
-    // There could be a lot of zombies, can't really decrement i here.
-  }
-  if (skipped >= kSkipLimit) {
-    NOTREACHED();
-    return false;
-  }
-
-  entry_.pid_ = pid;
-  entry_.ppid_ = GetProcStatsFieldAsInt64(proc_stats, internal::VM_PPID);
-  entry_.gid_ = GetProcStatsFieldAsInt64(proc_stats, internal::VM_PGRP);
-  entry_.cmd_line_args_.assign(cmd_line_args.begin(), cmd_line_args.end());
-  entry_.exe_file_ = GetProcessExecutablePath(pid).BaseName().value();
-  return true;
-}
-
-bool NamedProcessIterator::IncludeEntry() {
-  if (executable_name_ != entry().exe_file())
-    return false;
-  return ProcessIterator::IncludeEntry();
-}
-
-}  // namespace butil

+ 0 - 135
src/butil/process/process_iterator_mac.cc

@@ -1,135 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_iterator.h"
-
-#include <errno.h>
-#include <sys/sysctl.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "butil/logging.h"
-#include "butil/strings/string_util.h"
-
-namespace butil {
-
-ProcessIterator::ProcessIterator(const ProcessFilter* filter)
-    : index_of_kinfo_proc_(0),
-      filter_(filter) {
-  // Get a snapshot of all of my processes (yes, as we loop it can go stale, but
-  // but trying to find where we were in a constantly changing list is basically
-  // impossible.
-
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_UID, geteuid() };
-
-  // Since more processes could start between when we get the size and when
-  // we get the list, we do a loop to keep trying until we get it.
-  bool done = false;
-  int try_num = 1;
-  const int max_tries = 10;
-  do {
-    // Get the size of the buffer
-    size_t len = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0) {
-      DLOG(ERROR) << "failed to get the size needed for the process list";
-      kinfo_procs_.resize(0);
-      done = true;
-    } else {
-      size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-      // Leave some spare room for process table growth (more could show up
-      // between when we check and now)
-      num_of_kinfo_proc += 16;
-      kinfo_procs_.resize(num_of_kinfo_proc);
-      len = num_of_kinfo_proc * sizeof(struct kinfo_proc);
-      // Load the list of processes
-      if (sysctl(mib, arraysize(mib), &kinfo_procs_[0], &len, NULL, 0) < 0) {
-        // If we get a mem error, it just means we need a bigger buffer, so
-        // loop around again.  Anything else is a real error and give up.
-        if (errno != ENOMEM) {
-          DLOG(ERROR) << "failed to get the process list";
-          kinfo_procs_.resize(0);
-          done = true;
-        }
-      } else {
-        // Got the list, just make sure we're sized exactly right
-        size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-        kinfo_procs_.resize(num_of_kinfo_proc);
-        done = true;
-      }
-    }
-  } while (!done && (try_num++ < max_tries));
-
-  if (!done) {
-    DLOG(ERROR) << "failed to collect the process list in a few tries";
-    kinfo_procs_.resize(0);
-  }
-}
-
-ProcessIterator::~ProcessIterator() {
-}
-
-bool ProcessIterator::CheckForNextProcess() {
-  std::string data;
-  for (; index_of_kinfo_proc_ < kinfo_procs_.size(); ++index_of_kinfo_proc_) {
-    kinfo_proc& kinfo = kinfo_procs_[index_of_kinfo_proc_];
-
-    // Skip processes just awaiting collection
-    if ((kinfo.kp_proc.p_pid > 0) && (kinfo.kp_proc.p_stat == SZOMB))
-      continue;
-
-    int mib[] = { CTL_KERN, KERN_PROCARGS, kinfo.kp_proc.p_pid };
-
-    // Find out what size buffer we need.
-    size_t data_len = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &data_len, NULL, 0) < 0) {
-      DVPLOG(1) << "failed to figure out the buffer size for a commandline";
-      continue;
-    }
-
-    data.resize(data_len);
-    if (sysctl(mib, arraysize(mib), &data[0], &data_len, NULL, 0) < 0) {
-      DVPLOG(1) << "failed to fetch a commandline";
-      continue;
-    }
-
-    // |data| contains all the command line parameters of the process, separated
-    // by blocks of one or more null characters. We tokenize |data| into a
-    // vector of strings using '\0' as a delimiter and populate
-    // |entry_.cmd_line_args_|.
-    std::string delimiters;
-    delimiters.push_back('\0');
-    Tokenize(data, delimiters, &entry_.cmd_line_args_);
-
-    // |data| starts with the full executable path followed by a null character.
-    // We search for the first instance of '\0' and extract everything before it
-    // to populate |entry_.exe_file_|.
-    size_t exec_name_end = data.find('\0');
-    if (exec_name_end == std::string::npos) {
-      DLOG(ERROR) << "command line data didn't match expected format";
-      continue;
-    }
-
-    entry_.pid_ = kinfo.kp_proc.p_pid;
-    entry_.ppid_ = kinfo.kp_eproc.e_ppid;
-    entry_.gid_ = kinfo.kp_eproc.e_pgid;
-    size_t last_slash = data.rfind('/', exec_name_end);
-    if (last_slash == std::string::npos)
-      entry_.exe_file_.assign(data, 0, exec_name_end);
-    else
-      entry_.exe_file_.assign(data, last_slash + 1,
-                              exec_name_end - last_slash - 1);
-    // Start w/ the next entry next time through
-    ++index_of_kinfo_proc_;
-    // Done
-    return true;
-  }
-  return false;
-}
-
-bool NamedProcessIterator::IncludeEntry() {
-  return (executable_name_ == entry().exe_file() &&
-          ProcessIterator::IncludeEntry());
-}
-
-}  // namespace butil

+ 0 - 128
src/butil/process/process_iterator_openbsd.cc

@@ -1,128 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_iterator.h"
-
-#include <errno.h>
-#include <sys/sysctl.h>
-
-#include "butil/logging.h"
-#include "butil/strings/string_util.h"
-
-namespace butil {
-
-ProcessIterator::ProcessIterator(const ProcessFilter* filter)
-    : index_of_kinfo_proc_(),
-      filter_(filter) {
-
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_UID, getuid(),
-                sizeof(struct kinfo_proc), 0 };
-
-  bool done = false;
-  int try_num = 1;
-  const int max_tries = 10;
-
-  do {
-    size_t len = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &len, NULL, 0) < 0) {
-      DLOG(ERROR) << "failed to get the size needed for the process list";
-      kinfo_procs_.resize(0);
-      done = true;
-    } else {
-      size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-      // Leave some spare room for process table growth (more could show up
-      // between when we check and now)
-      num_of_kinfo_proc += 16;
-      kinfo_procs_.resize(num_of_kinfo_proc);
-      len = num_of_kinfo_proc * sizeof(struct kinfo_proc);
-      if (sysctl(mib, arraysize(mib), &kinfo_procs_[0], &len, NULL, 0) < 0) {
-        // If we get a mem error, it just means we need a bigger buffer, so
-        // loop around again.  Anything else is a real error and give up.
-        if (errno != ENOMEM) {
-          DLOG(ERROR) << "failed to get the process list";
-          kinfo_procs_.resize(0);
-          done = true;
-        }
-      } else {
-        // Got the list, just make sure we're sized exactly right
-        size_t num_of_kinfo_proc = len / sizeof(struct kinfo_proc);
-        kinfo_procs_.resize(num_of_kinfo_proc);
-        done = true;
-      }
-    }
-  } while (!done && (try_num++ < max_tries));
-
-  if (!done) {
-    DLOG(ERROR) << "failed to collect the process list in a few tries";
-    kinfo_procs_.resize(0);
-  }
-}
-
-ProcessIterator::~ProcessIterator() {
-}
-
-bool ProcessIterator::CheckForNextProcess() {
-  std::string data;
-  for (; index_of_kinfo_proc_ < kinfo_procs_.size(); ++index_of_kinfo_proc_) {
-    kinfo_proc& kinfo = kinfo_procs_[index_of_kinfo_proc_];
-
-    // Skip processes just awaiting collection
-    if ((kinfo.p_pid > 0) && (kinfo.p_stat == SZOMB))
-      continue;
-
-    int mib[] = { CTL_KERN, KERN_PROC_ARGS, kinfo.p_pid };
-
-    // Find out what size buffer we need.
-    size_t data_len = 0;
-    if (sysctl(mib, arraysize(mib), NULL, &data_len, NULL, 0) < 0) {
-      DVPLOG(1) << "failed to figure out the buffer size for a commandline";
-      continue;
-    }
-
-    data.resize(data_len);
-    if (sysctl(mib, arraysize(mib), &data[0], &data_len, NULL, 0) < 0) {
-      DVPLOG(1) << "failed to fetch a commandline";
-      continue;
-    }
-
-    // |data| contains all the command line parameters of the process, separated
-    // by blocks of one or more null characters. We tokenize |data| into a
-    // vector of strings using '\0' as a delimiter and populate
-    // |entry_.cmd_line_args_|.
-    std::string delimiters;
-    delimiters.push_back('\0');
-    Tokenize(data, delimiters, &entry_.cmd_line_args_);
-
-    // |data| starts with the full executable path followed by a null character.
-    // We search for the first instance of '\0' and extract everything before it
-    // to populate |entry_.exe_file_|.
-    size_t exec_name_end = data.find('\0');
-    if (exec_name_end == std::string::npos) {
-      DLOG(ERROR) << "command line data didn't match expected format";
-      continue;
-    }
-
-    entry_.pid_ = kinfo.p_pid;
-    entry_.ppid_ = kinfo.p_ppid;
-    entry_.gid_ = kinfo.p__pgid;
-    size_t last_slash = data.rfind('/', exec_name_end);
-    if (last_slash == std::string::npos)
-      entry_.exe_file_.assign(data, 0, exec_name_end);
-    else
-      entry_.exe_file_.assign(data, last_slash + 1,
-                              exec_name_end - last_slash - 1);
-    // Start w/ the next entry next time through
-    ++index_of_kinfo_proc_;
-    // Done
-    return true;
-  }
-  return false;
-}
-
-bool NamedProcessIterator::IncludeEntry() {
-  return (executable_name_ == entry().exe_file() &&
-          ProcessIterator::IncludeEntry());
-}
-
-}  // namespace butil

+ 0 - 141
src/butil/process/process_linux.cc

@@ -1,141 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process.h"
-
-#include <errno.h>
-#include <sys/resource.h>
-
-#include "butil/file_util.h"
-#include "butil/lazy_instance.h"
-#include "butil/logging.h"
-#include "butil/strings/string_split.h"
-#include "butil/strings/stringprintf.h"
-#include "butil/synchronization/lock.h"
-
-namespace butil {
-
-namespace {
-const int kForegroundPriority = 0;
-
-#if defined(OS_CHROMEOS)
-// We are more aggressive in our lowering of background process priority
-// for chromeos as we have much more control over other processes running
-// on the machine.
-//
-// TODO(davemoore) Refactor this by adding support for higher levels to set
-// the foregrounding / backgrounding process so we don't have to keep
-// chrome / chromeos specific logic here.
-const int kBackgroundPriority = 19;
-const char kControlPath[] = "/sys/fs/cgroup/cpu%s/cgroup.procs";
-const char kForeground[] = "/chrome_renderers/foreground";
-const char kBackground[] = "/chrome_renderers/background";
-const char kProcPath[] = "/proc/%d/cgroup";
-
-struct CGroups {
-  // Check for cgroups files. ChromeOS supports these by default. It creates
-  // a cgroup mount in /sys/fs/cgroup and then configures two cpu task groups,
-  // one contains at most a single foreground renderer and the other contains
-  // all background renderers. This allows us to limit the impact of background
-  // renderers on foreground ones to a greater level than simple renicing.
-  bool enabled;
-  butil::FilePath foreground_file;
-  butil::FilePath background_file;
-
-  CGroups() {
-    foreground_file =
-        butil::FilePath(butil::StringPrintf(kControlPath, kForeground));
-    background_file =
-        butil::FilePath(butil::StringPrintf(kControlPath, kBackground));
-    butil::FileSystemType foreground_type;
-    butil::FileSystemType background_type;
-    enabled =
-        butil::GetFileSystemType(foreground_file, &foreground_type) &&
-        butil::GetFileSystemType(background_file, &background_type) &&
-        foreground_type == FILE_SYSTEM_CGROUP &&
-        background_type == FILE_SYSTEM_CGROUP;
-  }
-};
-
-butil::LazyInstance<CGroups> cgroups = LAZY_INSTANCE_INITIALIZER;
-#else
-const int kBackgroundPriority = 5;
-#endif
-}
-
-bool Process::IsProcessBackgrounded() const {
-  DCHECK(process_);
-
-#if defined(OS_CHROMEOS)
-  if (cgroups.Get().enabled) {
-    std::string proc;
-    if (butil::ReadFileToString(
-            butil::FilePath(StringPrintf(kProcPath, process_)),
-            &proc)) {
-      std::vector<std::string> proc_parts;
-      butil::SplitString(proc, ':', &proc_parts);
-      DCHECK(proc_parts.size() == 3);
-      bool ret = proc_parts[2] == std::string(kBackground);
-      return ret;
-    } else {
-      return false;
-    }
-  }
-#endif
-  return GetPriority() == kBackgroundPriority;
-}
-
-bool Process::SetProcessBackgrounded(bool background) {
-  DCHECK(process_);
-
-#if defined(OS_CHROMEOS)
-  if (cgroups.Get().enabled) {
-    std::string pid = StringPrintf("%d", process_);
-    const butil::FilePath file =
-        background ?
-            cgroups.Get().background_file : cgroups.Get().foreground_file;
-    return butil::WriteFile(file, pid.c_str(), pid.size()) > 0;
-  }
-#endif // OS_CHROMEOS
-
-  if (!CanBackgroundProcesses())
-    return false;
-
-  int priority = background ? kBackgroundPriority : kForegroundPriority;
-  int result = setpriority(PRIO_PROCESS, process_, priority);
-  DPCHECK(result == 0);
-  return result == 0;
-}
-
-struct CheckForNicePermission {
-  CheckForNicePermission() : can_reraise_priority(false) {
-     // NOTE(gejun): Older linux does not support RLIMIT_NICE (not defined
-     // in bits/resource.h)
-#if defined(RLIMIT_NICE)
-    // We won't be able to raise the priority if we don't have the right rlimit.
-    // The limit may be adjusted in /etc/security/limits.conf for PAM systems.
-    struct rlimit rlim;
-    if ((getrlimit(RLIMIT_NICE, &rlim) == 0) &&
-        (20 - kForegroundPriority) <= static_cast<int>(rlim.rlim_cur)) {
-        can_reraise_priority = true;
-    }
-#endif
-  };
-
-  bool can_reraise_priority;
-};
-
-// static
-bool Process::CanBackgroundProcesses() {
-#if defined(OS_CHROMEOS)
-  if (cgroups.Get().enabled)
-    return true;
-#endif
-
-  static LazyInstance<CheckForNicePermission> check_for_nice_permission =
-      LAZY_INSTANCE_INITIALIZER;
-  return check_for_nice_permission.Get().can_reraise_priority;
-}
-
-}  // namespace butil

+ 0 - 45
src/butil/process/process_metrics.cc

@@ -1,45 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include "butil/logging.h"
-
-namespace butil {
-
-SystemMetrics::SystemMetrics() {
-  committed_memory_ = 0;
-}
-
-SystemMetrics SystemMetrics::Sample() {
-  SystemMetrics system_metrics;
-
-  system_metrics.committed_memory_ = GetSystemCommitCharge();
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  GetSystemMemoryInfo(&system_metrics.memory_info_);
-  GetSystemDiskInfo(&system_metrics.disk_info_);
-#endif
-#if defined(OS_CHROMEOS)
-  GetSwapInfo(&system_metrics.swap_info_);
-#endif
-
-  return system_metrics;
-}
-
-double ProcessMetrics::GetPlatformIndependentCPUUsage() {
-#if defined(OS_WIN)
-  return GetCPUUsage() * processor_count_;
-#else
-  return GetCPUUsage();
-#endif
-}
-
-#if !defined(OS_MACOSX)
-int ProcessMetrics::GetIdleWakeupsPerSecond() {
-  NOTIMPLEMENTED();  // http://crbug.com/20488
-  return 0;
-}
-#endif  // !defined(OS_MACOSX)
-
-}  // namespace butil

+ 0 - 379
src/butil/process/process_metrics.h

@@ -1,379 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains routines for gathering resource statistics for processes
-// running on the system.
-
-#ifndef BASE_PROCESS_PROCESS_METRICS_H_
-#define BASE_PROCESS_PROCESS_METRICS_H_
-
-#include <string>
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/gtest_prod_util.h"
-#include "butil/process/process_handle.h"
-#include "butil/time/time.h"
-
-#if defined(OS_MACOSX)
-#include <mach/mach.h>
-#endif
-
-namespace butil {
-
-#if defined(OS_WIN)
-struct IoCounters : public IO_COUNTERS {
-};
-#elif defined(OS_POSIX)
-struct IoCounters {
-  uint64_t ReadOperationCount;
-  uint64_t WriteOperationCount;
-  uint64_t OtherOperationCount;
-  uint64_t ReadTransferCount;
-  uint64_t WriteTransferCount;
-  uint64_t OtherTransferCount;
-};
-#endif
-
-// Working Set (resident) memory usage broken down by
-//
-// On Windows:
-// priv (private): These pages (kbytes) cannot be shared with any other process.
-// shareable:      These pages (kbytes) can be shared with other processes under
-//                 the right circumstances.
-// shared :        These pages (kbytes) are currently shared with at least one
-//                 other process.
-//
-// On Linux:
-// priv:           Pages mapped only by this process.
-// shared:         PSS or 0 if the kernel doesn't support this.
-// shareable:      0
-
-// On ChromeOS:
-// priv:           Pages mapped only by this process.
-// shared:         PSS or 0 if the kernel doesn't support this.
-// shareable:      0
-// swapped         Pages swapped out to zram.
-//
-// On OS X: TODO(thakis): Revise.
-// priv:           Memory.
-// shared:         0
-// shareable:      0
-//
-struct WorkingSetKBytes {
-  WorkingSetKBytes() : priv(0), shareable(0), shared(0) {}
-  size_t priv;
-  size_t shareable;
-  size_t shared;
-#if defined(OS_CHROMEOS)
-  size_t swapped;
-#endif
-};
-
-// Committed (resident + paged) memory usage broken down by
-// private: These pages cannot be shared with any other process.
-// mapped:  These pages are mapped into the view of a section (backed by
-//          pagefile.sys)
-// image:   These pages are mapped into the view of an image section (backed by
-//          file system)
-struct CommittedKBytes {
-  CommittedKBytes() : priv(0), mapped(0), image(0) {}
-  size_t priv;
-  size_t mapped;
-  size_t image;
-};
-
-// Free memory (Megabytes marked as free) in the 2G process address space.
-// total : total amount in megabytes marked as free. Maximum value is 2048.
-// largest : size of the largest contiguous amount of memory found. It is
-//   always smaller or equal to FreeMBytes::total.
-// largest_ptr: starting address of the largest memory block.
-struct FreeMBytes {
-  size_t total;
-  size_t largest;
-  void* largest_ptr;
-};
-
-// Convert a POSIX timeval to microseconds.
-BASE_EXPORT int64_t TimeValToMicroseconds(const struct timeval& tv);
-
-// Provides performance metrics for a specified process (CPU usage, memory and
-// IO counters). To use it, invoke CreateProcessMetrics() to get an instance
-// for a specific process, then access the information with the different get
-// methods.
-class BASE_EXPORT ProcessMetrics {
- public:
-  ~ProcessMetrics();
-
-  // Creates a ProcessMetrics for the specified process.
-  // The caller owns the returned object.
-#if !defined(OS_MACOSX) || defined(OS_IOS)
-  static ProcessMetrics* CreateProcessMetrics(ProcessHandle process);
-#else
-  class PortProvider {
-   public:
-    virtual ~PortProvider() {}
-
-    // Should return the mach task for |process| if possible, or else
-    // |MACH_PORT_NULL|. Only processes that this returns tasks for will have
-    // metrics on OS X (except for the current process, which always gets
-    // metrics).
-    virtual mach_port_t TaskForPid(ProcessHandle process) const = 0;
-  };
-
-  // The port provider needs to outlive the ProcessMetrics object returned by
-  // this function. If NULL is passed as provider, the returned object
-  // only returns valid metrics if |process| is the current process.
-  static ProcessMetrics* CreateProcessMetrics(ProcessHandle process,
-                                              PortProvider* port_provider);
-#endif  // !defined(OS_MACOSX) || defined(OS_IOS)
-
-  // Returns the current space allocated for the pagefile, in bytes (these pages
-  // may or may not be in memory).  On Linux, this returns the total virtual
-  // memory size.
-  size_t GetPagefileUsage() const;
-  // Returns the peak space allocated for the pagefile, in bytes.
-  size_t GetPeakPagefileUsage() const;
-  // Returns the current working set size, in bytes.  On Linux, this returns
-  // the resident set size.
-  size_t GetWorkingSetSize() const;
-  // Returns the peak working set size, in bytes.
-  size_t GetPeakWorkingSetSize() const;
-  // Returns private and sharedusage, in bytes. Private bytes is the amount of
-  // memory currently allocated to a process that cannot be shared. Returns
-  // false on platform specific error conditions.  Note: |private_bytes|
-  // returns 0 on unsupported OSes: prior to XP SP2.
-  bool GetMemoryBytes(size_t* private_bytes,
-                      size_t* shared_bytes);
-  // Fills a CommittedKBytes with both resident and paged
-  // memory usage as per definition of CommittedBytes.
-  void GetCommittedKBytes(CommittedKBytes* usage) const;
-  // Fills a WorkingSetKBytes containing resident private and shared memory
-  // usage in bytes, as per definition of WorkingSetBytes.
-  bool GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const;
-
-  // Computes the current process available memory for allocation.
-  // It does a linear scan of the address space querying each memory region
-  // for its free (unallocated) status. It is useful for estimating the memory
-  // load and fragmentation.
-  bool CalculateFreeMemory(FreeMBytes* free) const;
-
-  // Returns the CPU usage in percent since the last time this method or
-  // GetPlatformIndependentCPUUsage() was called. The first time this method
-  // is called it returns 0 and will return the actual CPU info on subsequent
-  // calls. On Windows, the CPU usage value is for all CPUs. So if you have
-  // 2 CPUs and your process is using all the cycles of 1 CPU and not the other
-  // CPU, this method returns 50.
-  double GetCPUUsage();
-
-  // Returns the number of average idle cpu wakeups per second since the last
-  // call.
-  int GetIdleWakeupsPerSecond();
-
-  // Same as GetCPUUsage(), but will return consistent values on all platforms
-  // (cancelling the Windows exception mentioned above) by returning a value in
-  // the range of 0 to (100 * numCPUCores) everywhere.
-  double GetPlatformIndependentCPUUsage();
-
-  // Retrieves accounting information for all I/O operations performed by the
-  // process.
-  // If IO information is retrieved successfully, the function returns true
-  // and fills in the IO_COUNTERS passed in. The function returns false
-  // otherwise.
-  bool GetIOCounters(IoCounters* io_counters) const;
-
- private:
-#if !defined(OS_MACOSX) || defined(OS_IOS)
-  explicit ProcessMetrics(ProcessHandle process);
-#else
-  ProcessMetrics(ProcessHandle process, PortProvider* port_provider);
-#endif  // !defined(OS_MACOSX) || defined(OS_IOS)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  bool GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage) const;
-#endif
-
-#if defined(OS_CHROMEOS)
-  bool GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage) const;
-#endif
-
-  ProcessHandle process_;
-
-  int processor_count_;
-
-  // Used to store the previous times and CPU usage counts so we can
-  // compute the CPU usage between calls.
-  TimeTicks last_cpu_time_;
-  int64_t last_system_time_;
-
-  // Same thing for idle wakeups.
-  TimeTicks last_idle_wakeups_time_;
-  int64_t last_absolute_idle_wakeups_;
-
-#if !defined(OS_IOS)
-#if defined(OS_MACOSX)
-  // Queries the port provider if it's set.
-  mach_port_t TaskForPid(ProcessHandle process) const;
-
-  PortProvider* port_provider_;
-#elif defined(OS_POSIX)
-  // Jiffie count at the last_cpu_time_ we updated.
-  int last_cpu_;
-#endif  // defined(OS_POSIX)
-#endif  // !defined(OS_IOS)
-
-  DISALLOW_COPY_AND_ASSIGN(ProcessMetrics);
-};
-
-// Returns the memory committed by the system in KBytes.
-// Returns 0 if it can't compute the commit charge.
-BASE_EXPORT size_t GetSystemCommitCharge();
-
-#if defined(OS_POSIX)
-// Returns the maximum number of file descriptors that can be open by a process
-// at once. If the number is unavailable, a conservative best guess is returned.
-size_t GetMaxFds();
-
-// Sets the file descriptor soft limit to |max_descriptors| or the OS hard
-// limit, whichever is lower.
-BASE_EXPORT void SetFdLimit(unsigned int max_descriptors);
-#endif  // defined(OS_POSIX)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-// Parse the data found in /proc/<pid>/stat and return the sum of the
-// CPU-related ticks.  Returns -1 on parse error.
-// Exposed for testing.
-BASE_EXPORT int ParseProcStatCPU(const std::string& input);
-
-// Get the number of threads of |process| as available in /proc/<pid>/stat.
-// This should be used with care as no synchronization with running threads is
-// done. This is mostly useful to guarantee being single-threaded.
-// Returns 0 on failure.
-BASE_EXPORT int GetNumberOfThreads(ProcessHandle process);
-
-// /proc/self/exe refers to the current executable.
-BASE_EXPORT extern const char kProcSelfExe[];
-
-// Data from /proc/meminfo about system-wide memory consumption.
-// Values are in KB.
-struct BASE_EXPORT SystemMemoryInfoKB {
-  SystemMemoryInfoKB();
-
-  int total;
-  int free;
-  int buffers;
-  int cached;
-  int active_anon;
-  int inactive_anon;
-  int active_file;
-  int inactive_file;
-  int swap_total;
-  int swap_free;
-  int dirty;
-
-  // vmstats data.
-  int pswpin;
-  int pswpout;
-  int pgmajfault;
-
-#ifdef OS_CHROMEOS
-  int shmem;
-  int slab;
-  // Gem data will be -1 if not supported.
-  int gem_objects;
-  long long gem_size;
-#endif
-};
-
-// Parses a string containing the contents of /proc/meminfo
-// returns true on success or false for a parsing error
-BASE_EXPORT bool ParseProcMeminfo(const std::string& input,
-                                  SystemMemoryInfoKB* meminfo);
-
-// Parses a string containing the contents of /proc/vmstat
-// returns true on success or false for a parsing error
-BASE_EXPORT bool ParseProcVmstat(const std::string& input,
-                                 SystemMemoryInfoKB* meminfo);
-
-// Retrieves data from /proc/meminfo and /proc/vmstat
-// about system-wide memory consumption.
-// Fills in the provided |meminfo| structure. Returns true on success.
-// Exposed for memory debugging widget.
-BASE_EXPORT bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo);
-
-// Data from /proc/diskstats about system-wide disk I/O.
-struct BASE_EXPORT SystemDiskInfo {
-  SystemDiskInfo();
-
-  uint64_t reads;
-  uint64_t reads_merged;
-  uint64_t sectors_read;
-  uint64_t read_time;
-  uint64_t writes;
-  uint64_t writes_merged;
-  uint64_t sectors_written;
-  uint64_t write_time;
-  uint64_t io;
-  uint64_t io_time;
-  uint64_t weighted_io_time;
-};
-
-// Checks whether the candidate string is a valid disk name, [sh]d[a-z]+
-// for a generic disk or mmcblk[0-9]+ for the MMC case.
-// Names of disk partitions (e.g. sda1) are not valid.
-BASE_EXPORT bool IsValidDiskName(const std::string& candidate);
-
-// Retrieves data from /proc/diskstats about system-wide disk I/O.
-// Fills in the provided |diskinfo| structure. Returns true on success.
-BASE_EXPORT bool GetSystemDiskInfo(SystemDiskInfo* diskinfo);
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-#if defined(OS_CHROMEOS)
-// Data from files in directory /sys/block/zram0 about ZRAM usage.
-struct BASE_EXPORT SwapInfo {
-  SwapInfo()
-      : num_reads(0),
-        num_writes(0),
-        compr_data_size(0),
-        orig_data_size(0),
-        mem_used_total(0) {
-  }
-
-  uint64_t num_reads;
-  uint64_t num_writes;
-  uint64_t compr_data_size;
-  uint64_t orig_data_size;
-  uint64_t mem_used_total;
-};
-
-// In ChromeOS, reads files from /sys/block/zram0 that contain ZRAM usage data.
-// Fills in the provided |swap_data| structure.
-BASE_EXPORT void GetSwapInfo(SwapInfo* swap_info);
-#endif  // defined(OS_CHROMEOS)
-
-// Collects and holds performance metrics for system memory and disk.
-// Provides functionality to retrieve the data on various platforms and
-// to serialize the stored data.
-class SystemMetrics {
- public:
-  SystemMetrics();
-
-  static SystemMetrics Sample();
-
- private:
-  FRIEND_TEST_ALL_PREFIXES(SystemMetricsTest, SystemMetrics);
-
-  size_t committed_memory_;
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  SystemMemoryInfoKB memory_info_;
-  SystemDiskInfo disk_info_;
-#endif
-#if defined(OS_CHROMEOS)
-  SwapInfo swap_info_;
-#endif
-};
-
-}  // namespace butil
-
-#endif  // BASE_PROCESS_PROCESS_METRICS_H_

+ 0 - 122
src/butil/process/process_metrics_freebsd.cc

@@ -1,122 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <sys/sysctl.h>
-#include <sys/user.h>
-#include <unistd.h>
-
-#include "butil/sys_info.h"
-
-namespace butil {
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process),
-      last_system_time_(0),
-      last_cpu_(0) {
-  processor_count_ = butil::SysInfo::NumberOfProcessors();
-}
-
-// static
-ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
-  return new ProcessMetrics(process);
-}
-
-size_t ProcessMetrics::GetPagefileUsage() const {
-  struct kinfo_proc info;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process_ };
-  size_t length = sizeof(info);
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return 0;
-
-  return info.ki_size;
-}
-
-size_t ProcessMetrics::GetPeakPagefileUsage() const {
-  return 0;
-}
-
-size_t ProcessMetrics::GetWorkingSetSize() const {
-  struct kinfo_proc info;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process_ };
-  size_t length = sizeof(info);
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return 0;
-
-  return info.ki_rssize * getpagesize();
-}
-
-size_t ProcessMetrics::GetPeakWorkingSetSize() const {
-  return 0;
-}
-
-bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
-                                    size_t* shared_bytes) {
-  WorkingSetKBytes ws_usage;
-  if (!GetWorkingSetKBytes(&ws_usage))
-    return false;
-
-  if (private_bytes)
-    *private_bytes = ws_usage.priv << 10;
-
-  if (shared_bytes)
-    *shared_bytes = ws_usage.shared * 1024;
-
-  return true;
-}
-
-bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
-// TODO(bapt) be sure we can't be precise
-  size_t priv = GetWorkingSetSize();
-  if (!priv)
-    return false;
-  ws_usage->priv = priv / 1024;
-  ws_usage->shareable = 0;
-  ws_usage->shared = 0;
-
-  return true;
-}
-
-double ProcessMetrics::GetCPUUsage() {
-  struct kinfo_proc info;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process_ };
-  size_t length = sizeof(info);
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return 0;
-
-  return (info.ki_pctcpu / FSCALE) * 100.0;
-}
-
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  return false;
-}
-
-size_t GetSystemCommitCharge() {
-  int mib[2], pagesize;
-  unsigned long mem_total, mem_free, mem_inactive;
-  size_t length = sizeof(mem_total);
-
-  if (sysctl(mib, arraysize(mib), &mem_total, &length, NULL, 0) < 0)
-    return 0;
-
-  length = sizeof(mem_free);
-  if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL, 0) < 0)
-    return 0;
-
-  length = sizeof(mem_inactive);
-  if (sysctlbyname("vm.stats.vm.v_inactive_count", &mem_inactive, &length,
-      NULL, 0) < 0) {
-    return 0;
-  }
-
-  pagesize = getpagesize();
-
-  return mem_total - (mem_free*pagesize) - (mem_inactive*pagesize);
-}
-
-}  // namespace butil

+ 0 - 812
src/butil/process/process_metrics_linux.cc

@@ -1,812 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <dirent.h>
-#include <fcntl.h>
-#include <sys/stat.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-
-#include "butil/file_util.h"
-#include "butil/logging.h"
-#include "butil/process/internal_linux.h"
-#include "butil/strings/string_number_conversions.h"
-#include "butil/strings/string_split.h"
-#include "butil/strings/string_tokenizer.h"
-#include "butil/strings/string_util.h"
-#include "butil/sys_info.h"
-#include "butil/threading/thread_restrictions.h"
-
-namespace butil {
-
-namespace {
-
-enum ParsingState {
-  KEY_NAME,
-  KEY_VALUE
-};
-
-#ifdef OS_CHROMEOS
-// Read a file with a single number string and return the number as a uint64_t.
-static uint64_t ReadFileToUint64(const butil::FilePath file) {
-  std::string file_as_string;
-  if (!ReadFileToString(file, &file_as_string))
-    return 0;
-  butil::TrimWhitespaceASCII(file_as_string, butil::TRIM_ALL, &file_as_string);
-  uint64_t file_as_uint64 = 0;
-  if (!butil::StringToUint64(file_as_string, &file_as_uint64))
-    return 0;
-  return file_as_uint64;
-}
-#endif
-
-// Read /proc/<pid>/status and returns the value for |field|, or 0 on failure.
-// Only works for fields in the form of "Field: value kB".
-size_t ReadProcStatusAndGetFieldAsSizeT(pid_t pid, const std::string& field) {
-  FilePath stat_file = internal::GetProcPidDir(pid).Append("status");
-  std::string status;
-  {
-    // Synchronously reading files in /proc is safe.
-    ThreadRestrictions::ScopedAllowIO allow_io;
-    if (!ReadFileToString(stat_file, &status))
-      return 0;
-  }
-
-  StringTokenizer tokenizer(status, ":\n");
-  ParsingState state = KEY_NAME;
-  StringPiece last_key_name;
-  while (tokenizer.GetNext()) {
-    switch (state) {
-      case KEY_NAME:
-        last_key_name = tokenizer.token_piece();
-        state = KEY_VALUE;
-        break;
-      case KEY_VALUE:
-        DCHECK(!last_key_name.empty());
-        if (last_key_name == field) {
-          std::string value_str;
-          tokenizer.token_piece().CopyToString(&value_str);
-          std::string value_str_trimmed;
-          butil::TrimWhitespaceASCII(value_str, butil::TRIM_ALL,
-                                    &value_str_trimmed);
-          std::vector<std::string> split_value_str;
-          SplitString(value_str_trimmed, ' ', &split_value_str);
-          if (split_value_str.size() != 2 || split_value_str[1] != "kB") {
-            NOTREACHED();
-            return 0;
-          }
-          size_t value;
-          if (!StringToSizeT(split_value_str[0], &value)) {
-            NOTREACHED();
-            return 0;
-          }
-          return value;
-        }
-        state = KEY_NAME;
-        break;
-    }
-  }
-  NOTREACHED();
-  return 0;
-}
-
-// Get the total CPU of a single process.  Return value is number of jiffies
-// on success or -1 on error.
-int GetProcessCPU(pid_t pid) {
-  // Use /proc/<pid>/task to find all threads and parse their /stat file.
-  FilePath task_path = internal::GetProcPidDir(pid).Append("task");
-
-  DIR* dir = opendir(task_path.value().c_str());
-  if (!dir) {
-    DPLOG(ERROR) << "opendir(" << task_path.value() << ")";
-    return -1;
-  }
-
-  int total_cpu = 0;
-  while (struct dirent* ent = readdir(dir)) {
-    pid_t tid = internal::ProcDirSlotToPid(ent->d_name);
-    if (!tid)
-      continue;
-
-    // Synchronously reading files in /proc is safe.
-    ThreadRestrictions::ScopedAllowIO allow_io;
-
-    std::string stat;
-    FilePath stat_path =
-        task_path.Append(ent->d_name).Append(internal::kStatFile);
-    if (ReadFileToString(stat_path, &stat)) {
-      int cpu = ParseProcStatCPU(stat);
-      if (cpu > 0)
-        total_cpu += cpu;
-    }
-  }
-  closedir(dir);
-
-  return total_cpu;
-}
-
-}  // namespace
-
-// static
-ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
-  return new ProcessMetrics(process);
-}
-
-// On linux, we return vsize.
-size_t ProcessMetrics::GetPagefileUsage() const {
-  return internal::ReadProcStatsAndGetFieldAsSizeT(process_,
-                                                   internal::VM_VSIZE);
-}
-
-// On linux, we return the high water mark of vsize.
-size_t ProcessMetrics::GetPeakPagefileUsage() const {
-  return ReadProcStatusAndGetFieldAsSizeT(process_, "VmPeak") * 1024;
-}
-
-// On linux, we return RSS.
-size_t ProcessMetrics::GetWorkingSetSize() const {
-  return internal::ReadProcStatsAndGetFieldAsSizeT(process_, internal::VM_RSS) *
-      getpagesize();
-}
-
-// On linux, we return the high water mark of RSS.
-size_t ProcessMetrics::GetPeakWorkingSetSize() const {
-  return ReadProcStatusAndGetFieldAsSizeT(process_, "VmHWM") * 1024;
-}
-
-bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
-                                    size_t* shared_bytes) {
-  WorkingSetKBytes ws_usage;
-  if (!GetWorkingSetKBytes(&ws_usage))
-    return false;
-
-  if (private_bytes)
-    *private_bytes = ws_usage.priv * 1024;
-
-  if (shared_bytes)
-    *shared_bytes = ws_usage.shared * 1024;
-
-  return true;
-}
-
-bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
-#if defined(OS_CHROMEOS)
-  if (GetWorkingSetKBytesTotmaps(ws_usage))
-    return true;
-#endif
-  return GetWorkingSetKBytesStatm(ws_usage);
-}
-
-double ProcessMetrics::GetCPUUsage() {
-  TimeTicks time = TimeTicks::Now();
-
-  if (last_cpu_ == 0) {
-    // First call, just set the last values.
-    last_cpu_time_ = time;
-    last_cpu_ = GetProcessCPU(process_);
-    return 0;
-  }
-
-  int64_t time_delta = (time - last_cpu_time_).InMicroseconds();
-  DCHECK_NE(time_delta, 0);
-  if (time_delta == 0)
-    return 0;
-
-  int cpu = GetProcessCPU(process_);
-
-  // We have the number of jiffies in the time period.  Convert to percentage.
-  // Note this means we will go *over* 100 in the case where multiple threads
-  // are together adding to more than one CPU's worth.
-  TimeDelta cpu_time = internal::ClockTicksToTimeDelta(cpu);
-  TimeDelta last_cpu_time = internal::ClockTicksToTimeDelta(last_cpu_);
-  int percentage = (int)(100 * (cpu_time - last_cpu_time).InSecondsF() /
-                         TimeDelta::FromMicroseconds(time_delta).InSecondsF());
-
-  last_cpu_time_ = time;
-  last_cpu_ = cpu;
-
-  return percentage;
-}
-
-// To have /proc/self/io file you must enable CONFIG_TASK_IO_ACCOUNTING
-// in your kernel configuration.
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  // Synchronously reading files in /proc is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  std::string proc_io_contents;
-  FilePath io_file = internal::GetProcPidDir(process_).Append("io");
-  if (!ReadFileToString(io_file, &proc_io_contents))
-    return false;
-
-  (*io_counters).OtherOperationCount = 0;
-  (*io_counters).OtherTransferCount = 0;
-
-  StringTokenizer tokenizer(proc_io_contents, ": \n");
-  ParsingState state = KEY_NAME;
-  StringPiece last_key_name;
-  while (tokenizer.GetNext()) {
-    switch (state) {
-      case KEY_NAME:
-        last_key_name = tokenizer.token_piece();
-        state = KEY_VALUE;
-        break;
-      case KEY_VALUE:
-        DCHECK(!last_key_name.empty());
-        if (last_key_name == "syscr") {
-          StringToInt64(tokenizer.token_piece(),
-              reinterpret_cast<int64_t*>(&(*io_counters).ReadOperationCount));
-        } else if (last_key_name == "syscw") {
-          StringToInt64(tokenizer.token_piece(),
-              reinterpret_cast<int64_t*>(&(*io_counters).WriteOperationCount));
-        } else if (last_key_name == "rchar") {
-          StringToInt64(tokenizer.token_piece(),
-              reinterpret_cast<int64_t*>(&(*io_counters).ReadTransferCount));
-        } else if (last_key_name == "wchar") {
-          StringToInt64(tokenizer.token_piece(),
-              reinterpret_cast<int64_t*>(&(*io_counters).WriteTransferCount));
-        }
-        state = KEY_NAME;
-        break;
-    }
-  }
-  return true;
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process),
-      last_system_time_(0),
-      last_cpu_(0) {
-  processor_count_ = butil::SysInfo::NumberOfProcessors();
-}
-
-#if defined(OS_CHROMEOS)
-// Private, Shared and Proportional working set sizes are obtained from
-// /proc/<pid>/totmaps
-bool ProcessMetrics::GetWorkingSetKBytesTotmaps(WorkingSetKBytes *ws_usage)
-  const {
-  // The format of /proc/<pid>/totmaps is:
-  //
-  // Rss:                6120 kB
-  // Pss:                3335 kB
-  // Shared_Clean:       1008 kB
-  // Shared_Dirty:       4012 kB
-  // Private_Clean:         4 kB
-  // Private_Dirty:      1096 kB
-  // Referenced:          XXX kB
-  // Anonymous:           XXX kB
-  // AnonHugePages:       XXX kB
-  // Swap:                XXX kB
-  // Locked:              XXX kB
-  const size_t kPssIndex = (1 * 3) + 1;
-  const size_t kPrivate_CleanIndex = (4 * 3) + 1;
-  const size_t kPrivate_DirtyIndex = (5 * 3) + 1;
-  const size_t kSwapIndex = (9 * 3) + 1;
-
-  std::string totmaps_data;
-  {
-    FilePath totmaps_file = internal::GetProcPidDir(process_).Append("totmaps");
-    ThreadRestrictions::ScopedAllowIO allow_io;
-    bool ret = ReadFileToString(totmaps_file, &totmaps_data);
-    if (!ret || totmaps_data.length() == 0)
-      return false;
-  }
-
-  std::vector<std::string> totmaps_fields;
-  SplitStringAlongWhitespace(totmaps_data, &totmaps_fields);
-
-  DCHECK_EQ("Pss:", totmaps_fields[kPssIndex-1]);
-  DCHECK_EQ("Private_Clean:", totmaps_fields[kPrivate_CleanIndex - 1]);
-  DCHECK_EQ("Private_Dirty:", totmaps_fields[kPrivate_DirtyIndex - 1]);
-  DCHECK_EQ("Swap:", totmaps_fields[kSwapIndex-1]);
-
-  int pss = 0;
-  int private_clean = 0;
-  int private_dirty = 0;
-  int swap = 0;
-  bool ret = true;
-  ret &= StringToInt(totmaps_fields[kPssIndex], &pss);
-  ret &= StringToInt(totmaps_fields[kPrivate_CleanIndex], &private_clean);
-  ret &= StringToInt(totmaps_fields[kPrivate_DirtyIndex], &private_dirty);
-  ret &= StringToInt(totmaps_fields[kSwapIndex], &swap);
-
-  // On ChromeOS swap is to zram. We count this as private / shared, as
-  // increased swap decreases available RAM to user processes, which would
-  // otherwise create surprising results.
-  ws_usage->priv = private_clean + private_dirty + swap;
-  ws_usage->shared = pss + swap;
-  ws_usage->shareable = 0;
-  ws_usage->swapped = swap;
-  return ret;
-}
-#endif
-
-// Private and Shared working set sizes are obtained from /proc/<pid>/statm.
-bool ProcessMetrics::GetWorkingSetKBytesStatm(WorkingSetKBytes* ws_usage)
-    const {
-  // Use statm instead of smaps because smaps is:
-  // a) Large and slow to parse.
-  // b) Unavailable in the SUID sandbox.
-
-  // First we need to get the page size, since everything is measured in pages.
-  // For details, see: man 5 proc.
-  const int page_size_kb = getpagesize() / 1024;
-  if (page_size_kb <= 0)
-    return false;
-
-  std::string statm;
-  {
-    FilePath statm_file = internal::GetProcPidDir(process_).Append("statm");
-    // Synchronously reading files in /proc is safe.
-    ThreadRestrictions::ScopedAllowIO allow_io;
-    bool ret = ReadFileToString(statm_file, &statm);
-    if (!ret || statm.length() == 0)
-      return false;
-  }
-
-  std::vector<std::string> statm_vec;
-  SplitString(statm, ' ', &statm_vec);
-  if (statm_vec.size() != 7)
-    return false;  // Not the format we expect.
-
-  int statm_rss, statm_shared;
-  bool ret = true;
-  ret &= StringToInt(statm_vec[1], &statm_rss);
-  ret &= StringToInt(statm_vec[2], &statm_shared);
-
-  ws_usage->priv = (statm_rss - statm_shared) * page_size_kb;
-  ws_usage->shared = statm_shared * page_size_kb;
-
-  // Sharable is not calculated, as it does not provide interesting data.
-  ws_usage->shareable = 0;
-
-#if defined(OS_CHROMEOS)
-  // Can't get swapped memory from statm.
-  ws_usage->swapped = 0;
-#endif
-
-  return ret;
-}
-
-size_t GetSystemCommitCharge() {
-  SystemMemoryInfoKB meminfo;
-  if (!GetSystemMemoryInfo(&meminfo))
-    return 0;
-  return meminfo.total - meminfo.free - meminfo.buffers - meminfo.cached;
-}
-
-// Exposed for testing.
-int ParseProcStatCPU(const std::string& input) {
-  std::vector<std::string> proc_stats;
-  if (!internal::ParseProcStats(input, &proc_stats))
-    return -1;
-
-  if (proc_stats.size() <= internal::VM_STIME)
-    return -1;
-  int utime = GetProcStatsFieldAsInt64(proc_stats, internal::VM_UTIME);
-  int stime = GetProcStatsFieldAsInt64(proc_stats, internal::VM_STIME);
-  return utime + stime;
-}
-
-const char kProcSelfExe[] = "/proc/self/exe";
-
-int GetNumberOfThreads(ProcessHandle process) {
-  return internal::ReadProcStatsAndGetFieldAsInt64(process,
-                                                   internal::VM_NUMTHREADS);
-}
-
-namespace {
-
-// The format of /proc/diskstats is:
-//  Device major number
-//  Device minor number
-//  Device name
-//  Field  1 -- # of reads completed
-//      This is the total number of reads completed successfully.
-//  Field  2 -- # of reads merged, field 6 -- # of writes merged
-//      Reads and writes which are adjacent to each other may be merged for
-//      efficiency.  Thus two 4K reads may become one 8K read before it is
-//      ultimately handed to the disk, and so it will be counted (and queued)
-//      as only one I/O.  This field lets you know how often this was done.
-//  Field  3 -- # of sectors read
-//      This is the total number of sectors read successfully.
-//  Field  4 -- # of milliseconds spent reading
-//      This is the total number of milliseconds spent by all reads (as
-//      measured from __make_request() to end_that_request_last()).
-//  Field  5 -- # of writes completed
-//      This is the total number of writes completed successfully.
-//  Field  6 -- # of writes merged
-//      See the description of field 2.
-//  Field  7 -- # of sectors written
-//      This is the total number of sectors written successfully.
-//  Field  8 -- # of milliseconds spent writing
-//      This is the total number of milliseconds spent by all writes (as
-//      measured from __make_request() to end_that_request_last()).
-//  Field  9 -- # of I/Os currently in progress
-//      The only field that should go to zero. Incremented as requests are
-//      given to appropriate struct request_queue and decremented as they
-//      finish.
-//  Field 10 -- # of milliseconds spent doing I/Os
-//      This field increases so long as field 9 is nonzero.
-//  Field 11 -- weighted # of milliseconds spent doing I/Os
-//      This field is incremented at each I/O start, I/O completion, I/O
-//      merge, or read of these stats by the number of I/Os in progress
-//      (field 9) times the number of milliseconds spent doing I/O since the
-//      last update of this field.  This can provide an easy measure of both
-//      I/O completion time and the backlog that may be accumulating.
-
-const size_t kDiskDriveName = 2;
-const size_t kDiskReads = 3;
-const size_t kDiskReadsMerged = 4;
-const size_t kDiskSectorsRead = 5;
-const size_t kDiskReadTime = 6;
-const size_t kDiskWrites = 7;
-const size_t kDiskWritesMerged = 8;
-const size_t kDiskSectorsWritten = 9;
-const size_t kDiskWriteTime = 10;
-const size_t kDiskIO = 11;
-const size_t kDiskIOTime = 12;
-const size_t kDiskWeightedIOTime = 13;
-
-}  // namespace
-
-SystemMemoryInfoKB::SystemMemoryInfoKB() {
-  total = 0;
-  free = 0;
-  buffers = 0;
-  cached = 0;
-  active_anon = 0;
-  inactive_anon = 0;
-  active_file = 0;
-  inactive_file = 0;
-  swap_total = 0;
-  swap_free = 0;
-  dirty = 0;
-
-  pswpin = 0;
-  pswpout = 0;
-  pgmajfault = 0;
-
-#ifdef OS_CHROMEOS
-  shmem = 0;
-  slab = 0;
-  gem_objects = -1;
-  gem_size = -1;
-#endif
-}
-
-// exposed for testing
-bool ParseProcMeminfo(const std::string& meminfo_data,
-                      SystemMemoryInfoKB* meminfo) {
-  // The format of /proc/meminfo is:
-  //
-  // MemTotal:      8235324 kB
-  // MemFree:       1628304 kB
-  // Buffers:        429596 kB
-  // Cached:        4728232 kB
-  // ...
-  // There is no guarantee on the ordering or position
-  // though it doesn't appear to change very often
-
-  // As a basic sanity check, let's make sure we at least get non-zero
-  // MemTotal value
-  meminfo->total = 0;
-
-  std::vector<std::string> meminfo_lines;
-  Tokenize(meminfo_data, "\n", &meminfo_lines);
-  for (std::vector<std::string>::iterator it = meminfo_lines.begin();
-       it != meminfo_lines.end(); ++it) {
-    std::vector<std::string> tokens;
-    SplitStringAlongWhitespace(*it, &tokens);
-    // HugePages_* only has a number and no suffix so we can't rely on
-    // there being exactly 3 tokens.
-    if (tokens.size() > 1) {
-      if (tokens[0] == "MemTotal:") {
-        StringToInt(tokens[1], &meminfo->total);
-        continue;
-      } if (tokens[0] == "MemFree:") {
-        StringToInt(tokens[1], &meminfo->free);
-        continue;
-      } if (tokens[0] == "Buffers:") {
-        StringToInt(tokens[1], &meminfo->buffers);
-        continue;
-      } if (tokens[0] == "Cached:") {
-        StringToInt(tokens[1], &meminfo->cached);
-        continue;
-      } if (tokens[0] == "Active(anon):") {
-        StringToInt(tokens[1], &meminfo->active_anon);
-        continue;
-      } if (tokens[0] == "Inactive(anon):") {
-        StringToInt(tokens[1], &meminfo->inactive_anon);
-        continue;
-      } if (tokens[0] == "Active(file):") {
-        StringToInt(tokens[1], &meminfo->active_file);
-        continue;
-      } if (tokens[0] == "Inactive(file):") {
-        StringToInt(tokens[1], &meminfo->inactive_file);
-        continue;
-      } if (tokens[0] == "SwapTotal:") {
-        StringToInt(tokens[1], &meminfo->swap_total);
-        continue;
-      } if (tokens[0] == "SwapFree:") {
-        StringToInt(tokens[1], &meminfo->swap_free);
-        continue;
-      } if (tokens[0] == "Dirty:") {
-        StringToInt(tokens[1], &meminfo->dirty);
-        continue;
-#if defined(OS_CHROMEOS)
-      // Chrome OS has a tweaked kernel that allows us to query Shmem, which is
-      // usually video memory otherwise invisible to the OS.
-      } if (tokens[0] == "Shmem:") {
-        StringToInt(tokens[1], &meminfo->shmem);
-        continue;
-      } if (tokens[0] == "Slab:") {
-        StringToInt(tokens[1], &meminfo->slab);
-        continue;
-#endif
-      }
-    } else
-      DLOG(WARNING) << "meminfo: tokens: " << tokens.size()
-                    << " malformed line: " << *it;
-  }
-
-  // Make sure we got a valid MemTotal.
-  if (!meminfo->total)
-    return false;
-
-  return true;
-}
-
-// exposed for testing
-bool ParseProcVmstat(const std::string& vmstat_data,
-                     SystemMemoryInfoKB* meminfo) {
-  // The format of /proc/vmstat is:
-  //
-  // nr_free_pages 299878
-  // nr_inactive_anon 239863
-  // nr_active_anon 1318966
-  // nr_inactive_file 2015629
-  // ...
-  //
-  // We iterate through the whole file because the position of the
-  // fields are dependent on the kernel version and configuration.
-
-  std::vector<std::string> vmstat_lines;
-  Tokenize(vmstat_data, "\n", &vmstat_lines);
-  for (std::vector<std::string>::iterator it = vmstat_lines.begin();
-       it != vmstat_lines.end(); ++it) {
-    std::vector<std::string> tokens;
-    SplitString(*it, ' ', &tokens);
-    if (tokens.size() == 2) {
-      if (tokens[0] == "pswpin") {
-        StringToInt(tokens[1], &meminfo->pswpin);
-        continue;
-      } if (tokens[0] == "pswpout") {
-        StringToInt(tokens[1], &meminfo->pswpout);
-        continue;
-      } if (tokens[0] == "pgmajfault")
-        StringToInt(tokens[1], &meminfo->pgmajfault);
-    }
-  }
-
-  return true;
-}
-
-bool GetSystemMemoryInfo(SystemMemoryInfoKB* meminfo) {
-  // Synchronously reading files in /proc is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  // Used memory is: total - free - buffers - caches
-  FilePath meminfo_file("/proc/meminfo");
-  std::string meminfo_data;
-  if (!ReadFileToString(meminfo_file, &meminfo_data)) {
-    DLOG(WARNING) << "Failed to open " << meminfo_file.value();
-    return false;
-  }
-
-  if (!ParseProcMeminfo(meminfo_data, meminfo)) {
-    DLOG(WARNING) << "Failed to parse " << meminfo_file.value();
-    return false;
-  }
-
-#if defined(OS_CHROMEOS)
-  // Report on Chrome OS GEM object graphics memory. /var/run/debugfs_gpu is a
-  // bind mount into /sys/kernel/debug and synchronously reading the in-memory
-  // files in /sys is fast.
-#if defined(ARCH_CPU_ARM_FAMILY)
-  FilePath geminfo_file("/var/run/debugfs_gpu/exynos_gem_objects");
-#else
-  FilePath geminfo_file("/var/run/debugfs_gpu/i915_gem_objects");
-#endif
-  std::string geminfo_data;
-  meminfo->gem_objects = -1;
-  meminfo->gem_size = -1;
-  if (ReadFileToString(geminfo_file, &geminfo_data)) {
-    int gem_objects = -1;
-    long long gem_size = -1;
-    int num_res = sscanf(geminfo_data.c_str(),
-                         "%d objects, %lld bytes",
-                         &gem_objects, &gem_size);
-    if (num_res == 2) {
-      meminfo->gem_objects = gem_objects;
-      meminfo->gem_size = gem_size;
-    }
-  }
-
-#if defined(ARCH_CPU_ARM_FAMILY)
-  // Incorporate Mali graphics memory if present.
-  FilePath mali_memory_file("/sys/class/misc/mali0/device/memory");
-  std::string mali_memory_data;
-  if (ReadFileToString(mali_memory_file, &mali_memory_data)) {
-    long long mali_size = -1;
-    int num_res = sscanf(mali_memory_data.c_str(), "%lld bytes", &mali_size);
-    if (num_res == 1)
-      meminfo->gem_size += mali_size;
-  }
-#endif  // defined(ARCH_CPU_ARM_FAMILY)
-#endif  // defined(OS_CHROMEOS)
-
-  FilePath vmstat_file("/proc/vmstat");
-  std::string vmstat_data;
-  if (!ReadFileToString(vmstat_file, &vmstat_data)) {
-    DLOG(WARNING) << "Failed to open " << vmstat_file.value();
-    return false;
-  }
-  if (!ParseProcVmstat(vmstat_data, meminfo)) {
-    DLOG(WARNING) << "Failed to parse " << vmstat_file.value();
-    return false;
-  }
-
-  return true;
-}
-
-SystemDiskInfo::SystemDiskInfo() {
-  reads = 0;
-  reads_merged = 0;
-  sectors_read = 0;
-  read_time = 0;
-  writes = 0;
-  writes_merged = 0;
-  sectors_written = 0;
-  write_time = 0;
-  io = 0;
-  io_time = 0;
-  weighted_io_time = 0;
-}
-
-bool IsValidDiskName(const std::string& candidate) {
-  if (candidate.length() < 3)
-    return false;
-  if (candidate.substr(0,2) == "sd" || candidate.substr(0,2) == "hd") {
-    // [sh]d[a-z]+ case
-    for (size_t i = 2; i < candidate.length(); i++) {
-      if (!islower(candidate[i]))
-        return false;
-    }
-  } else {
-    if (candidate.length() < 7) {
-      return false;
-    }
-    if (candidate.substr(0,6) == "mmcblk") {
-      // mmcblk[0-9]+ case
-      for (size_t i = 6; i < candidate.length(); i++) {
-        if (!isdigit(candidate[i]))
-          return false;
-      }
-    } else {
-      return false;
-    }
-  }
-
-  return true;
-}
-
-bool GetSystemDiskInfo(SystemDiskInfo* diskinfo) {
-  // Synchronously reading files in /proc is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  FilePath diskinfo_file("/proc/diskstats");
-  std::string diskinfo_data;
-  if (!ReadFileToString(diskinfo_file, &diskinfo_data)) {
-    DLOG(WARNING) << "Failed to open " << diskinfo_file.value();
-    return false;
-  }
-
-  std::vector<std::string> diskinfo_lines;
-  size_t line_count = Tokenize(diskinfo_data, "\n", &diskinfo_lines);
-  if (line_count == 0) {
-    DLOG(WARNING) << "No lines found";
-    return false;
-  }
-
-  diskinfo->reads = 0;
-  diskinfo->reads_merged = 0;
-  diskinfo->sectors_read = 0;
-  diskinfo->read_time = 0;
-  diskinfo->writes = 0;
-  diskinfo->writes_merged = 0;
-  diskinfo->sectors_written = 0;
-  diskinfo->write_time = 0;
-  diskinfo->io = 0;
-  diskinfo->io_time = 0;
-  diskinfo->weighted_io_time = 0;
-
-  uint64_t reads = 0;
-  uint64_t reads_merged = 0;
-  uint64_t sectors_read = 0;
-  uint64_t read_time = 0;
-  uint64_t writes = 0;
-  uint64_t writes_merged = 0;
-  uint64_t sectors_written = 0;
-  uint64_t write_time = 0;
-  uint64_t io = 0;
-  uint64_t io_time = 0;
-  uint64_t weighted_io_time = 0;
-
-  for (size_t i = 0; i < line_count; i++) {
-    std::vector<std::string> disk_fields;
-    SplitStringAlongWhitespace(diskinfo_lines[i], &disk_fields);
-
-    // Fields may have overflowed and reset to zero.
-    if (IsValidDiskName(disk_fields[kDiskDriveName])) {
-      StringToUint64(disk_fields[kDiskReads], &reads);
-      StringToUint64(disk_fields[kDiskReadsMerged], &reads_merged);
-      StringToUint64(disk_fields[kDiskSectorsRead], &sectors_read);
-      StringToUint64(disk_fields[kDiskReadTime], &read_time);
-      StringToUint64(disk_fields[kDiskWrites], &writes);
-      StringToUint64(disk_fields[kDiskWritesMerged], &writes_merged);
-      StringToUint64(disk_fields[kDiskSectorsWritten], &sectors_written);
-      StringToUint64(disk_fields[kDiskWriteTime], &write_time);
-      StringToUint64(disk_fields[kDiskIO], &io);
-      StringToUint64(disk_fields[kDiskIOTime], &io_time);
-      StringToUint64(disk_fields[kDiskWeightedIOTime], &weighted_io_time);
-
-      diskinfo->reads += reads;
-      diskinfo->reads_merged += reads_merged;
-      diskinfo->sectors_read += sectors_read;
-      diskinfo->read_time += read_time;
-      diskinfo->writes += writes;
-      diskinfo->writes_merged += writes_merged;
-      diskinfo->sectors_written += sectors_written;
-      diskinfo->write_time += write_time;
-      diskinfo->io += io;
-      diskinfo->io_time += io_time;
-      diskinfo->weighted_io_time += weighted_io_time;
-    }
-  }
-
-  return true;
-}
-
-#if defined(OS_CHROMEOS)
-void GetSwapInfo(SwapInfo* swap_info) {
-  // Synchronously reading files in /sys/block/zram0 is safe.
-  ThreadRestrictions::ScopedAllowIO allow_io;
-
-  butil::FilePath zram_path("/sys/block/zram0");
-  uint64_t orig_data_size = ReadFileToUint64(zram_path.Append("orig_data_size"));
-  if (orig_data_size <= 4096) {
-    // A single page is compressed at startup, and has a high compression
-    // ratio. We ignore this as it doesn't indicate any real swapping.
-    swap_info->orig_data_size = 0;
-    swap_info->num_reads = 0;
-    swap_info->num_writes = 0;
-    swap_info->compr_data_size = 0;
-    swap_info->mem_used_total = 0;
-    return;
-  }
-  swap_info->orig_data_size = orig_data_size;
-  swap_info->num_reads = ReadFileToUint64(zram_path.Append("num_reads"));
-  swap_info->num_writes = ReadFileToUint64(zram_path.Append("num_writes"));
-  swap_info->compr_data_size =
-      ReadFileToUint64(zram_path.Append("compr_data_size"));
-  swap_info->mem_used_total =
-      ReadFileToUint64(zram_path.Append("mem_used_total"));
-}
-#endif  // defined(OS_CHROMEOS)
-
-}  // namespace butil

+ 0 - 365
src/butil/process/process_metrics_mac.cc

@@ -1,365 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <mach/mach.h>
-#include <mach/mach_vm.h>
-#include <mach/shared_region.h>
-#include <sys/sysctl.h>
-
-#include "butil/containers/hash_tables.h"
-#include "butil/logging.h"
-#include "butil/mac/mach_logging.h"
-#include "butil/mac/scoped_mach_port.h"
-#include "butil/sys_info.h"
-
-#if !defined(TASK_POWER_INFO)
-// Doesn't exist in the 10.6 or 10.7 SDKs.
-#define TASK_POWER_INFO        21
-struct task_power_info {
-        uint64_t                total_user;
-        uint64_t                total_system;
-        uint64_t                task_interrupt_wakeups;
-        uint64_t                task_platform_idle_wakeups;
-        uint64_t                task_timer_wakeups_bin_1;
-        uint64_t                task_timer_wakeups_bin_2;
-};
-typedef struct task_power_info        task_power_info_data_t;
-typedef struct task_power_info        *task_power_info_t;
-#define TASK_POWER_INFO_COUNT        ((mach_msg_type_number_t) \
-                (sizeof (task_power_info_data_t) / sizeof (natural_t)))
-#endif
-
-namespace butil {
-
-namespace {
-
-bool GetTaskInfo(mach_port_t task, task_basic_info_64* task_info_data) {
-  if (task == MACH_PORT_NULL)
-    return false;
-  mach_msg_type_number_t count = TASK_BASIC_INFO_64_COUNT;
-  kern_return_t kr = task_info(task,
-                               TASK_BASIC_INFO_64,
-                               reinterpret_cast<task_info_t>(task_info_data),
-                               &count);
-  // Most likely cause for failure: |task| is a zombie.
-  return kr == KERN_SUCCESS;
-}
-
-bool GetCPUTypeForProcess(pid_t pid, cpu_type_t* cpu_type) {
-  size_t len = sizeof(*cpu_type);
-  int result = sysctlbyname("sysctl.proc_cputype",
-                            cpu_type,
-                            &len,
-                            NULL,
-                            0);
-  if (result != 0) {
-    DPLOG(ERROR) << "sysctlbyname(""sysctl.proc_cputype"")";
-    return false;
-  }
-
-  return true;
-}
-
-bool IsAddressInSharedRegion(mach_vm_address_t addr, cpu_type_t type) {
-  if (type == CPU_TYPE_I386) {
-    return addr >= SHARED_REGION_BASE_I386 &&
-           addr < (SHARED_REGION_BASE_I386 + SHARED_REGION_SIZE_I386);
-  } else if (type == CPU_TYPE_X86_64) {
-    return addr >= SHARED_REGION_BASE_X86_64 &&
-           addr < (SHARED_REGION_BASE_X86_64 + SHARED_REGION_SIZE_X86_64);
-  } else {
-    return false;
-  }
-}
-
-}  // namespace
-
-// Getting a mach task from a pid for another process requires permissions in
-// general, so there doesn't really seem to be a way to do these (and spinning
-// up ps to fetch each stats seems dangerous to put in a base api for anyone to
-// call). Child processes ipc their port, so return something if available,
-// otherwise return 0.
-
-// static
-ProcessMetrics* ProcessMetrics::CreateProcessMetrics(
-    ProcessHandle process,
-    ProcessMetrics::PortProvider* port_provider) {
-  return new ProcessMetrics(process, port_provider);
-}
-
-size_t ProcessMetrics::GetPagefileUsage() const {
-  task_basic_info_64 task_info_data;
-  if (!GetTaskInfo(TaskForPid(process_), &task_info_data))
-    return 0;
-  return task_info_data.virtual_size;
-}
-
-size_t ProcessMetrics::GetPeakPagefileUsage() const {
-  return 0;
-}
-
-size_t ProcessMetrics::GetWorkingSetSize() const {
-  task_basic_info_64 task_info_data;
-  if (!GetTaskInfo(TaskForPid(process_), &task_info_data))
-    return 0;
-  return task_info_data.resident_size;
-}
-
-size_t ProcessMetrics::GetPeakWorkingSetSize() const {
-  return 0;
-}
-
-// This is a rough approximation of the algorithm that libtop uses.
-// private_bytes is the size of private resident memory.
-// shared_bytes is the size of shared resident memory.
-bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
-                                    size_t* shared_bytes) {
-  size_t private_pages_count = 0;
-  size_t shared_pages_count = 0;
-
-  if (!private_bytes && !shared_bytes)
-    return true;
-
-  mach_port_t task = TaskForPid(process_);
-  if (task == MACH_PORT_NULL) {
-    DLOG(ERROR) << "Invalid process";
-    return false;
-  }
-
-  cpu_type_t cpu_type;
-  if (!GetCPUTypeForProcess(process_, &cpu_type))
-    return false;
-
-  // The same region can be referenced multiple times. To avoid double counting
-  // we need to keep track of which regions we've already counted.
-  butil::hash_set<int> seen_objects;
-
-  // We iterate through each VM region in the task's address map. For shared
-  // memory we add up all the pages that are marked as shared. Like libtop we
-  // try to avoid counting pages that are also referenced by other tasks. Since
-  // we don't have access to the VM regions of other tasks the only hint we have
-  // is if the address is in the shared region area.
-  //
-  // Private memory is much simpler. We simply count the pages that are marked
-  // as private or copy on write (COW).
-  //
-  // See libtop_update_vm_regions in
-  // http://www.opensource.apple.com/source/top/top-67/libtop.c
-  mach_vm_size_t size = 0;
-  for (mach_vm_address_t address = MACH_VM_MIN_ADDRESS;; address += size) {
-    vm_region_top_info_data_t info;
-    mach_msg_type_number_t info_count = VM_REGION_TOP_INFO_COUNT;
-    mach_port_t object_name;
-    kern_return_t kr = mach_vm_region(task,
-                                      &address,
-                                      &size,
-                                      VM_REGION_TOP_INFO,
-                                      reinterpret_cast<vm_region_info_t>(&info),
-                                      &info_count,
-                                      &object_name);
-    if (kr == KERN_INVALID_ADDRESS) {
-      // We're at the end of the address space.
-      break;
-    } else if (kr != KERN_SUCCESS) {
-      MACH_DLOG(ERROR, kr) << "mach_vm_region";
-      return false;
-    }
-
-    // The kernel always returns a null object for VM_REGION_TOP_INFO, but
-    // balance it with a deallocate in case this ever changes. See 10.9.2
-    // xnu-2422.90.20/osfmk/vm/vm_map.c vm_map_region.
-    mach_port_deallocate(mach_task_self(), object_name);
-
-    if (IsAddressInSharedRegion(address, cpu_type) &&
-        info.share_mode != SM_PRIVATE)
-      continue;
-
-    if (info.share_mode == SM_COW && info.ref_count == 1)
-      info.share_mode = SM_PRIVATE;
-
-    switch (info.share_mode) {
-      case SM_PRIVATE:
-        private_pages_count += info.private_pages_resident;
-        private_pages_count += info.shared_pages_resident;
-        break;
-      case SM_COW:
-        private_pages_count += info.private_pages_resident;
-        // Fall through
-      case SM_SHARED:
-        if (seen_objects.count(info.obj_id) == 0) {
-          // Only count the first reference to this region.
-          seen_objects.insert(info.obj_id);
-          shared_pages_count += info.shared_pages_resident;
-        }
-        break;
-      default:
-        break;
-    }
-  }
-
-  if (private_bytes)
-    *private_bytes = private_pages_count * PAGE_SIZE;
-  if (shared_bytes)
-    *shared_bytes = shared_pages_count * PAGE_SIZE;
-
-  return true;
-}
-
-void ProcessMetrics::GetCommittedKBytes(CommittedKBytes* usage) const {
-}
-
-bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
-  size_t priv = GetWorkingSetSize();
-  if (!priv)
-    return false;
-  ws_usage->priv = priv / 1024;
-  ws_usage->shareable = 0;
-  ws_usage->shared = 0;
-  return true;
-}
-
-#define TIME_VALUE_TO_TIMEVAL(a, r) do {  \
-  (r)->tv_sec = (a)->seconds;             \
-  (r)->tv_usec = (a)->microseconds;       \
-} while (0)
-
-double ProcessMetrics::GetCPUUsage() {
-  mach_port_t task = TaskForPid(process_);
-  if (task == MACH_PORT_NULL)
-    return 0;
-
-  // Libtop explicitly loops over the threads (libtop_pinfo_update_cpu_usage()
-  // in libtop.c), but this is more concise and gives the same results:
-  task_thread_times_info thread_info_data;
-  mach_msg_type_number_t thread_info_count = TASK_THREAD_TIMES_INFO_COUNT;
-  kern_return_t kr = task_info(task,
-                               TASK_THREAD_TIMES_INFO,
-                               reinterpret_cast<task_info_t>(&thread_info_data),
-                               &thread_info_count);
-  if (kr != KERN_SUCCESS) {
-    // Most likely cause: |task| is a zombie.
-    return 0;
-  }
-
-  task_basic_info_64 task_info_data;
-  if (!GetTaskInfo(task, &task_info_data))
-    return 0;
-
-  /* Set total_time. */
-  // thread info contains live time...
-  struct timeval user_timeval, system_timeval, task_timeval;
-  TIME_VALUE_TO_TIMEVAL(&thread_info_data.user_time, &user_timeval);
-  TIME_VALUE_TO_TIMEVAL(&thread_info_data.system_time, &system_timeval);
-  timeradd(&user_timeval, &system_timeval, &task_timeval);
-
-  // ... task info contains terminated time.
-  TIME_VALUE_TO_TIMEVAL(&task_info_data.user_time, &user_timeval);
-  TIME_VALUE_TO_TIMEVAL(&task_info_data.system_time, &system_timeval);
-  timeradd(&user_timeval, &task_timeval, &task_timeval);
-  timeradd(&system_timeval, &task_timeval, &task_timeval);
-
-  TimeTicks time = TimeTicks::Now();
-  int64_t task_time = TimeValToMicroseconds(task_timeval);
-
-  if (last_system_time_ == 0) {
-    // First call, just set the last values.
-    last_cpu_time_ = time;
-    last_system_time_ = task_time;
-    return 0;
-  }
-
-  int64_t system_time_delta = task_time - last_system_time_;
-  int64_t time_delta = (time - last_cpu_time_).InMicroseconds();
-  DCHECK_NE(0U, time_delta);
-  if (time_delta == 0)
-    return 0;
-
-  last_cpu_time_ = time;
-  last_system_time_ = task_time;
-
-  return static_cast<double>(system_time_delta * 100.0) / time_delta;
-}
-
-int ProcessMetrics::GetIdleWakeupsPerSecond() {
-  mach_port_t task = TaskForPid(process_);
-  if (task == MACH_PORT_NULL)
-    return 0;
-
-  task_power_info power_info_data;
-  mach_msg_type_number_t power_info_count = TASK_POWER_INFO_COUNT;
-  kern_return_t kr = task_info(task,
-                               TASK_POWER_INFO,
-                               reinterpret_cast<task_info_t>(&power_info_data),
-                               &power_info_count);
-  if (kr != KERN_SUCCESS) {
-    // Most likely cause: |task| is a zombie, or this is on a pre-10.8.4 system
-    // where TASK_POWER_INFO isn't supported yet.
-    return 0;
-  }
-  uint64_t absolute_idle_wakeups = power_info_data.task_platform_idle_wakeups;
-
-  TimeTicks time = TimeTicks::Now();
-
-  if (last_absolute_idle_wakeups_ == 0) {
-    // First call, just set the last values.
-    last_idle_wakeups_time_ = time;
-    last_absolute_idle_wakeups_ = absolute_idle_wakeups;
-    return 0;
-  }
-
-  int64_t wakeups_delta = absolute_idle_wakeups - last_absolute_idle_wakeups_;
-  int64_t time_delta = (time - last_idle_wakeups_time_).InMicroseconds();
-  DCHECK_NE(0U, time_delta);
-  if (time_delta == 0)
-    return 0;
-
-  last_idle_wakeups_time_ = time;
-  last_absolute_idle_wakeups_ = absolute_idle_wakeups;
-
-  // Round to average wakeups per second.
-  const int kMicrosecondsPerSecond = 1000 * 1000;
-  return (wakeups_delta * kMicrosecondsPerSecond + time_delta/2) / time_delta;
-}
-
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  return false;
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process,
-                               ProcessMetrics::PortProvider* port_provider)
-    : process_(process),
-      last_system_time_(0),
-      last_absolute_idle_wakeups_(0),
-      port_provider_(port_provider) {
-  processor_count_ = SysInfo::NumberOfProcessors();
-}
-
-mach_port_t ProcessMetrics::TaskForPid(ProcessHandle process) const {
-  mach_port_t task = MACH_PORT_NULL;
-  if (port_provider_)
-    task = port_provider_->TaskForPid(process_);
-  if (task == MACH_PORT_NULL && process_ == getpid())
-    task = mach_task_self();
-  return task;
-}
-
-// Bytes committed by the system.
-size_t GetSystemCommitCharge() {
-  butil::mac::ScopedMachSendRight host(mach_host_self());
-  mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
-  vm_statistics_data_t data;
-  kern_return_t kr = host_statistics(host, HOST_VM_INFO,
-                                     reinterpret_cast<host_info_t>(&data),
-                                     &count);
-  if (kr != KERN_SUCCESS) {
-    MACH_DLOG(WARNING, kr) << "host_statistics";
-    return 0;
-  }
-
-  return (data.active_count * PAGE_SIZE) / 1024;
-}
-
-}  // namespace butil

+ 0 - 161
src/butil/process/process_metrics_openbsd.cc

@@ -1,161 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <sys/param.h>
-#include <sys/sysctl.h>
-
-namespace butil {
-
-// static
-ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
-  return new ProcessMetrics(process);
-}
-
-size_t ProcessMetrics::GetPagefileUsage() const {
-  struct kinfo_proc info;
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process_,
-                sizeof(struct kinfo_proc), 0 };
-
-  if (sysctl(mib, arraysize(mib), NULL, &length, NULL, 0) < 0)
-    return -1;
-
-  mib[5] = (length / sizeof(struct kinfo_proc));
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return -1;
-
-  return (info.p_vm_tsize + info.p_vm_dsize + info.p_vm_ssize);
-}
-
-size_t ProcessMetrics::GetPeakPagefileUsage() const {
-  return 0;
-}
-
-size_t ProcessMetrics::GetWorkingSetSize() const {
-  struct kinfo_proc info;
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, process_,
-                sizeof(struct kinfo_proc), 0 };
-
-  if (sysctl(mib, arraysize(mib), NULL, &length, NULL, 0) < 0)
-    return -1;
-
-  mib[5] = (length / sizeof(struct kinfo_proc));
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return -1;
-
-  return info.p_vm_rssize * getpagesize();
-}
-
-size_t ProcessMetrics::GetPeakWorkingSetSize() const {
-  return 0;
-}
-
-bool ProcessMetrics::GetMemoryBytes(size_t* private_bytes,
-                                    size_t* shared_bytes) {
-  WorkingSetKBytes ws_usage;
-
-  if (!GetWorkingSetKBytes(&ws_usage))
-    return false;
-
-  if (private_bytes)
-    *private_bytes = ws_usage.priv << 10;
-
-  if (shared_bytes)
-    *shared_bytes = ws_usage.shared * 1024;
-
-  return true;
-}
-
-bool ProcessMetrics::GetWorkingSetKBytes(WorkingSetKBytes* ws_usage) const {
-  // TODO(bapt): be sure we can't be precise
-  size_t priv = GetWorkingSetSize();
-  if (!priv)
-    return false;
-  ws_usage->priv = priv / 1024;
-  ws_usage->shareable = 0;
-  ws_usage->shared = 0;
-
-  return true;
-}
-
-bool ProcessMetrics::GetIOCounters(IoCounters* io_counters) const {
-  return false;
-}
-
-static int GetProcessCPU(pid_t pid) {
-  struct kinfo_proc info;
-  size_t length;
-  int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid,
-                sizeof(struct kinfo_proc), 0 };
-
-  if (sysctl(mib, arraysize(mib), NULL, &length, NULL, 0) < 0)
-    return -1;
-
-  mib[5] = (length / sizeof(struct kinfo_proc));
-
-  if (sysctl(mib, arraysize(mib), &info, &length, NULL, 0) < 0)
-    return 0;
-
-  return info.p_pctcpu;
-}
-
-double ProcessMetrics::GetCPUUsage() {
-  TimeTicks time = TimeTicks::Now();
-
-  if (last_cpu_ == 0) {
-    // First call, just set the last values.
-    last_cpu_time_ = time;
-    last_cpu_ = GetProcessCPU(process_);
-    return 0;
-  }
-
-  int64_t time_delta = (time - last_cpu_time_).InMicroseconds();
-  DCHECK_NE(time_delta, 0);
-
-  if (time_delta == 0)
-    return 0;
-
-  int cpu = GetProcessCPU(process_);
-
-  last_cpu_time_ = time;
-  last_cpu_ = cpu;
-
-  double percentage = static_cast<double>((cpu * 100.0) / FSCALE);
-
-  return percentage;
-}
-
-ProcessMetrics::ProcessMetrics(ProcessHandle process)
-    : process_(process),
-      last_system_time_(0),
-      last_cpu_(0) {
-
-  processor_count_ = butil::SysInfo::NumberOfProcessors();
-}
-
-size_t GetSystemCommitCharge() {
-  int mib[] = { CTL_VM, VM_METER };
-  int pagesize;
-  struct vmtotal vmtotal;
-  unsigned long mem_total, mem_free, mem_inactive;
-  size_t len = sizeof(vmtotal);
-
-  if (sysctl(mib, arraysize(mib), &vmtotal, &len, NULL, 0) < 0)
-    return 0;
-
-  mem_total = vmtotal.t_vm;
-  mem_free = vmtotal.t_free;
-  mem_inactive = vmtotal.t_vm - vmtotal.t_avm;
-
-  pagesize = getpagesize();
-
-  return mem_total - (mem_free*pagesize) - (mem_inactive*pagesize);
-}
-
-}  // namespace butil

+ 0 - 72
src/butil/process/process_metrics_posix.cc

@@ -1,72 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <sys/resource.h>
-#include <sys/time.h>
-
-#include "butil/logging.h"
-
-namespace butil {
-
-int64_t TimeValToMicroseconds(const struct timeval& tv) {
-  static const int kMicrosecondsPerSecond = 1000000;
-  int64_t ret = tv.tv_sec;  // Avoid (int * int) integer overflow.
-  ret *= kMicrosecondsPerSecond;
-  ret += tv.tv_usec;
-  return ret;
-}
-
-ProcessMetrics::~ProcessMetrics() { }
-
-#if defined(OS_LINUX)
-static const rlim_t kSystemDefaultMaxFds = 8192;
-#elif defined(OS_MACOSX)
-static const rlim_t kSystemDefaultMaxFds = 256;
-#elif defined(OS_SOLARIS)
-static const rlim_t kSystemDefaultMaxFds = 8192;
-#elif defined(OS_FREEBSD)
-static const rlim_t kSystemDefaultMaxFds = 8192;
-#elif defined(OS_OPENBSD)
-static const rlim_t kSystemDefaultMaxFds = 256;
-#elif defined(OS_ANDROID)
-static const rlim_t kSystemDefaultMaxFds = 1024;
-#endif
-
-size_t GetMaxFds() {
-  rlim_t max_fds;
-  struct rlimit nofile;
-  if (getrlimit(RLIMIT_NOFILE, &nofile)) {
-    // getrlimit failed. Take a best guess.
-    max_fds = kSystemDefaultMaxFds;
-    RAW_LOG(ERROR, "getrlimit(RLIMIT_NOFILE) failed");
-  } else {
-    max_fds = nofile.rlim_cur;
-  }
-
-  if (max_fds > INT_MAX)
-    max_fds = INT_MAX;
-
-  return static_cast<size_t>(max_fds);
-}
-
-
-void SetFdLimit(unsigned int max_descriptors) {
-  struct rlimit limits;
-  if (getrlimit(RLIMIT_NOFILE, &limits) == 0) {
-    unsigned int new_limit = max_descriptors;
-    if (limits.rlim_max > 0 && limits.rlim_max < max_descriptors) {
-      new_limit = limits.rlim_max;
-    }
-    limits.rlim_cur = new_limit;
-    if (setrlimit(RLIMIT_NOFILE, &limits) != 0) {
-      PLOG(INFO) << "Failed to set file descriptor limit";
-    }
-  } else {
-    PLOG(INFO) << "Failed to get file descriptor limit";
-  }
-}
-
-}  // namespace butil

+ 0 - 73
src/butil/process/process_posix.cc

@@ -1,73 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process.h"
-
-#include <sys/resource.h>
-#include <sys/time.h>
-#include <sys/types.h>
-
-#include "butil/logging.h"
-#include "butil/process/kill.h"
-
-namespace butil {
-
-// static
-Process Process::Current() {
-  return Process(GetCurrentProcessHandle());
-}
-
-ProcessId Process::pid() const {
-  if (process_ == 0)
-    return 0;
-
-  return GetProcId(process_);
-}
-
-bool Process::is_current() const {
-  return process_ == GetCurrentProcessHandle();
-}
-
-void Process::Close() {
-  process_ = 0;
-  // if the process wasn't terminated (so we waited) or the state
-  // wasn't already collected w/ a wait from process_utils, we're gonna
-  // end up w/ a zombie when it does finally exit.
-}
-
-void Process::Terminate(int result_code) {
-  // result_code isn't supportable.
-  if (!process_)
-    return;
-  // We don't wait here. It's the responsibility of other code to reap the
-  // child.
-  KillProcess(process_, result_code, false);
-}
-
-#if !defined(OS_LINUX)
-bool Process::IsProcessBackgrounded() const {
-  // See SetProcessBackgrounded().
-  return false;
-}
-
-bool Process::SetProcessBackgrounded(bool value) {
-  // POSIX only allows lowering the priority of a process, so if we
-  // were to lower it we wouldn't be able to raise it back to its initial
-  // priority.
-  return false;
-}
-
-// static
-bool Process::CanBackgroundProcesses() {
-  return false;
-}
-
-#endif
-
-int Process::GetPriority() const {
-  DCHECK(process_);
-  return getpriority(PRIO_PROCESS, process_);
-}
-
-}  // namespace butil

+ 0 - 56
src/butil/sys_info.cc

@@ -1,56 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include "butil/base_switches.h"
-#include "butil/command_line.h"
-#include "butil/lazy_instance.h"
-#include "butil/strings/string_number_conversions.h"
-#include "butil/sys_info_internal.h"
-#include "butil/time/time.h"
-
-namespace butil {
-
-#if !defined(OS_ANDROID)
-
-static const int kLowMemoryDeviceThresholdMB = 512;
-
-bool DetectLowEndDevice() {
-  CommandLine* command_line = CommandLine::ForCurrentProcess();
-  int int_value = 0;
-  if (command_line->HasSwitch(switches::kLowEndDeviceMode)) {
-    std::string string_value =
-      command_line->GetSwitchValueASCII(switches::kLowEndDeviceMode);
-    StringToInt(string_value, &int_value);
-  }
-  if (int_value == 1)
-    return true;
-  if (int_value != 2)
-    return false;
-
-  int ram_size_mb = SysInfo::AmountOfPhysicalMemoryMB();
-  return (ram_size_mb > 0 && ram_size_mb < kLowMemoryDeviceThresholdMB);
-}
-
-static LazyInstance<
-  internal::LazySysInfoValue<bool, DetectLowEndDevice> >::Leaky
-  g_lazy_low_end_device = LAZY_INSTANCE_INITIALIZER;
-
-// static
-bool SysInfo::IsLowEndDevice() {
-  return g_lazy_low_end_device.Get().value();
-}
-#endif
-
-// static
-int64_t SysInfo::Uptime() {
-  // This code relies on an implementation detail of TimeTicks::Now() - that
-  // its return value happens to coincide with the system uptime value in
-  // microseconds, on Win/Mac/iOS/Linux/ChromeOS and Android.
-  int64_t uptime_in_microseconds = TimeTicks::Now().ToInternalValue();
-  return uptime_in_microseconds / 1000;
-}
-
-}  // namespace butil

+ 0 - 141
src/butil/sys_info.h

@@ -1,141 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_SYS_INFO_H_
-#define BASE_SYS_INFO_H_
-
-#include <map>
-#include <string>
-
-#include "butil/base_export.h"
-#include "butil/basictypes.h"
-#include "butil/files/file_path.h"
-#include "butil/time/time.h"
-#include "butil/build_config.h"
-
-namespace butil {
-
-class BASE_EXPORT SysInfo {
- public:
-  // Return the number of logical processors/cores on the current machine.
-  static int NumberOfProcessors();
-
-  // Return the number of bytes of physical memory on the current machine.
-  static int64_t AmountOfPhysicalMemory();
-
-  // Return the number of bytes of current available physical memory on the
-  // machine.
-  static int64_t AmountOfAvailablePhysicalMemory();
-
-  // Return the number of bytes of virtual memory of this process. A return
-  // value of zero means that there is no limit on the available virtual
-  // memory.
-  static int64_t AmountOfVirtualMemory();
-
-  // Return the number of megabytes of physical memory on the current machine.
-  static int AmountOfPhysicalMemoryMB() {
-    return static_cast<int>(AmountOfPhysicalMemory() / 1024 / 1024);
-  }
-
-  // Return the number of megabytes of available virtual memory, or zero if it
-  // is unlimited.
-  static int AmountOfVirtualMemoryMB() {
-    return static_cast<int>(AmountOfVirtualMemory() / 1024 / 1024);
-  }
-
-  // Return the available disk space in bytes on the volume containing |path|,
-  // or -1 on failure.
-  static int64_t AmountOfFreeDiskSpace(const FilePath& path);
-
-  // Returns system uptime in milliseconds.
-  static int64_t Uptime();
-
-  // Returns the name of the host operating system.
-  static std::string OperatingSystemName();
-
-  // Returns the version of the host operating system.
-  static std::string OperatingSystemVersion();
-
-  // Retrieves detailed numeric values for the OS version.
-  // TODO(port): Implement a Linux version of this method and enable the
-  // corresponding unit test.
-  // DON'T USE THIS ON THE MAC OR WINDOWS to determine the current OS release
-  // for OS version-specific feature checks and workarounds. If you must use
-  // an OS version check instead of a feature check, use the butil::mac::IsOS*
-  // family from butil/mac/mac_util.h, or butil::win::GetVersion from
-  // butil/win/windows_version.h.
-  static void OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version);
-
-  // Returns the architecture of the running operating system.
-  // Exact return value may differ across platforms.
-  // e.g. a 32-bit x86 kernel on a 64-bit capable CPU will return "x86",
-  //      whereas a x86-64 kernel on the same CPU will return "x86_64"
-  static std::string OperatingSystemArchitecture();
-
-  // Avoid using this. Use butil/cpu.h to get information about the CPU instead.
-  // http://crbug.com/148884
-  // Returns the CPU model name of the system. If it can not be figured out,
-  // an empty string is returned.
-  static std::string CPUModelName();
-
-  // Return the smallest amount of memory (in bytes) which the VM system will
-  // allocate.
-  static size_t VMAllocationGranularity();
-
-#if defined(OS_POSIX) && !defined(OS_MACOSX)
-  // Returns the maximum SysV shared memory segment size, or zero if there is no
-  // limit.
-  static size_t MaxSharedMemorySize();
-#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
-
-#if defined(OS_CHROMEOS)
-  typedef std::map<std::string, std::string> LsbReleaseMap;
-
-  // Returns the contents of /etc/lsb-release as a map.
-  static const LsbReleaseMap& GetLsbReleaseMap();
-
-  // If |key| is present in the LsbReleaseMap, sets |value| and returns true.
-  static bool GetLsbReleaseValue(const std::string& key, std::string* value);
-
-  // Convenience function for GetLsbReleaseValue("CHROMEOS_RELEASE_BOARD",...).
-  // Returns "unknown" if CHROMEOS_RELEASE_BOARD is not set.
-  static std::string GetLsbReleaseBoard();
-
-  // Returns the creation time of /etc/lsb-release. (Used to get the date and
-  // time of the Chrome OS build).
-  static Time GetLsbReleaseTime();
-
-  // Returns true when actually running in a Chrome OS environment.
-  static bool IsRunningOnChromeOS();
-
-  // Test method to force re-parsing of lsb-release.
-  static void SetChromeOSVersionInfoForTest(const std::string& lsb_release,
-                                            const Time& lsb_release_time);
-#endif  // defined(OS_CHROMEOS)
-
-#if defined(OS_ANDROID)
-  // Returns the Android build's codename.
-  static std::string GetAndroidBuildCodename();
-
-  // Returns the Android build ID.
-  static std::string GetAndroidBuildID();
-
-  // Returns the device's name.
-  static std::string GetDeviceName();
-
-  static int DalvikHeapSizeMB();
-  static int DalvikHeapGrowthLimitMB();
-#endif  // defined(OS_ANDROID)
-
-  // Returns true if this is a low-end device.
-  // Low-end device refers to devices having less than 512M memory in the
-  // current implementation.
-  static bool IsLowEndDevice();
-};
-
-}  // namespace butil
-
-#endif  // BASE_SYS_INFO_H_

+ 0 - 36
src/butil/sys_info_freebsd.cc

@@ -1,36 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include <sys/sysctl.h>
-
-#include "butil/logging.h"
-
-namespace butil {
-
-int64_t SysInfo::AmountOfPhysicalMemory() {
-  int pages, page_size;
-  size_t size = sizeof(pages);
-  sysctlbyname("vm.stats.vm.v_page_count", &pages, &size, NULL, 0);
-  sysctlbyname("vm.stats.vm.v_page_size", &page_size, &size, NULL, 0);
-  if (pages == -1 || page_size == -1) {
-    NOTREACHED();
-    return 0;
-  }
-  return static_cast<int64_t>(pages) * page_size;
-}
-
-// static
-size_t SysInfo::MaxSharedMemorySize() {
-  size_t limit;
-  size_t size = sizeof(limit);
-  if (sysctlbyname("kern.ipc.shmmax", &limit, &size, NULL, 0) < 0) {
-    NOTREACHED();
-    return 0;
-  }
-  return limit;
-}
-
-}  // namespace butil

+ 0 - 34
src/butil/sys_info_internal.h

@@ -1,34 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_SYS_INFO_INTERNAL_H_
-#define BASE_SYS_INFO_INTERNAL_H_
-
-#include "butil/basictypes.h"
-
-namespace butil {
-
-namespace internal {
-
-template<typename T, T (*F)(void)>
-class LazySysInfoValue {
- public:
-  LazySysInfoValue()
-      : value_(F()) { }
-
-  ~LazySysInfoValue() { }
-
-  T value() { return value_; }
-
- private:
-  const T value_;
-
-  DISALLOW_COPY_AND_ASSIGN(LazySysInfoValue);
-};
-
-}  // namespace internal
-
-}  // namespace butil
-
-#endif  // BASE_SYS_INFO_INTERNAL_H_

+ 0 - 100
src/butil/sys_info_linux.cc

@@ -1,100 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include <limits>
-
-#include "butil/file_util.h"
-#include "butil/lazy_instance.h"
-#include "butil/logging.h"
-#include "butil/strings/string_number_conversions.h"
-#include "butil/sys_info_internal.h"
-
-namespace {
-
-int64_t AmountOfMemory(int pages_name) {
-  long pages = sysconf(pages_name);
-  long page_size = sysconf(_SC_PAGESIZE);
-  if (pages == -1 || page_size == -1) {
-    NOTREACHED();
-    return 0;
-  }
-  return static_cast<int64_t>(pages) * page_size;
-}
-
-int64_t AmountOfPhysicalMemory() {
-  return AmountOfMemory(_SC_PHYS_PAGES);
-}
-
-size_t MaxSharedMemorySize() {
-  std::string contents;
-  butil::ReadFileToString(butil::FilePath("/proc/sys/kernel/shmmax"), &contents);
-  DCHECK(!contents.empty());
-  if (!contents.empty() && contents[contents.length() - 1] == '\n') {
-    contents.erase(contents.length() - 1);
-  }
-
-  int64_t limit;
-  if (!butil::StringToInt64(contents, &limit)) {
-    limit = 0;
-  }
-  if (limit < 0 ||
-      static_cast<uint64_t>(limit) > std::numeric_limits<size_t>::max()) {
-    limit = 0;
-  }
-  DCHECK(limit > 0);
-  return static_cast<size_t>(limit);
-}
-
-butil::LazyInstance<
-    butil::internal::LazySysInfoValue<int64_t, AmountOfPhysicalMemory> >::Leaky
-    g_lazy_physical_memory = LAZY_INSTANCE_INITIALIZER;
-butil::LazyInstance<
-    butil::internal::LazySysInfoValue<size_t, MaxSharedMemorySize> >::Leaky
-    g_lazy_max_shared_memory = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-namespace butil {
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemory() {
-  return AmountOfMemory(_SC_AVPHYS_PAGES);
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemory() {
-  return g_lazy_physical_memory.Get().value();
-}
-
-// static
-size_t SysInfo::MaxSharedMemorySize() {
-  return g_lazy_max_shared_memory.Get().value();
-}
-
-// static
-std::string SysInfo::CPUModelName() {
-#if defined(OS_CHROMEOS) && defined(ARCH_CPU_ARMEL)
-  const char kCpuModelPrefix[] = "Hardware";
-#else
-  const char kCpuModelPrefix[] = "model name";
-#endif
-  std::string contents;
-  ReadFileToString(FilePath("/proc/cpuinfo"), &contents);
-  DCHECK(!contents.empty());
-  if (!contents.empty()) {
-    std::istringstream iss(contents);
-    std::string line;
-    while (std::getline(iss, line)) {
-      if (line.compare(0, strlen(kCpuModelPrefix), kCpuModelPrefix) == 0) {
-        size_t pos = line.find(": ");
-        return line.substr(pos + 2);
-      }
-    }
-  }
-  return std::string();
-}
-
-}  // namespace butil

+ 0 - 88
src/butil/sys_info_mac.cc

@@ -1,88 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include <ApplicationServices/ApplicationServices.h>
-#include <CoreServices/CoreServices.h>
-#include <mach/mach_host.h>
-#include <mach/mach_init.h>
-#include <sys/sysctl.h>
-#include <sys/types.h>
-
-#include "butil/logging.h"
-#include "butil/mac/scoped_mach_port.h"
-#include "butil/strings/stringprintf.h"
-
-namespace butil {
-
-// static
-std::string SysInfo::OperatingSystemName() {
-  return "Mac OS X";
-}
-
-// static
-std::string SysInfo::OperatingSystemVersion() {
-  int32_t major, minor, bugfix;
-  OperatingSystemVersionNumbers(&major, &minor, &bugfix);
-  return butil::StringPrintf("%d.%d.%d", major, minor, bugfix);
-}
-
-// static
-void SysInfo::OperatingSystemVersionNumbers(int32_t* major_version,
-                                            int32_t* minor_version,
-                                            int32_t* bugfix_version) {
-  Gestalt(gestaltSystemVersionMajor,
-      reinterpret_cast<SInt32*>(major_version));
-  Gestalt(gestaltSystemVersionMinor,
-      reinterpret_cast<SInt32*>(minor_version));
-  Gestalt(gestaltSystemVersionBugFix,
-      reinterpret_cast<SInt32*>(bugfix_version));
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemory() {
-  struct host_basic_info hostinfo;
-  mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
-  butil::mac::ScopedMachSendRight host(mach_host_self());
-  int result = host_info(host,
-                         HOST_BASIC_INFO,
-                         reinterpret_cast<host_info_t>(&hostinfo),
-                         &count);
-  if (result != KERN_SUCCESS) {
-    NOTREACHED();
-    return 0;
-  }
-  DCHECK_EQ(HOST_BASIC_INFO_COUNT, count);
-  return static_cast<int64_t>(hostinfo.max_mem);
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemory() {
-  butil::mac::ScopedMachSendRight host(mach_host_self());
-  vm_statistics_data_t vm_info;
-  mach_msg_type_number_t count = HOST_VM_INFO_COUNT;
-
-  if (host_statistics(host.get(),
-                      HOST_VM_INFO,
-                      reinterpret_cast<host_info_t>(&vm_info),
-                      &count) != KERN_SUCCESS) {
-    NOTREACHED();
-    return 0;
-  }
-
-  return static_cast<int64_t>(
-      vm_info.free_count - vm_info.speculative_count) * PAGE_SIZE;
-}
-
-// static
-std::string SysInfo::CPUModelName() {
-  char name[256];
-  size_t len = arraysize(name);
-  if (sysctlbyname("machdep.cpu.brand_string", &name, &len, NULL, 0) == 0)
-    return name;
-  return std::string();
-}
-
-}  // namespace butil

+ 0 - 75
src/butil/sys_info_openbsd.cc

@@ -1,75 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include <sys/param.h>
-#include <sys/shm.h>
-#include <sys/sysctl.h>
-
-#include "butil/logging.h"
-
-namespace {
-
-int64_t AmountOfMemory(int pages_name) {
-  long pages = sysconf(pages_name);
-  long page_size = sysconf(_SC_PAGESIZE);
-  if (pages == -1 || page_size == -1) {
-    NOTREACHED();
-    return 0;
-  }
-  return static_cast<int64_t>(pages) * page_size;
-}
-
-}  // namespace
-
-namespace butil {
-
-// static
-int SysInfo::NumberOfProcessors() {
-  int mib[] = { CTL_HW, HW_NCPU };
-  int ncpu;
-  size_t size = sizeof(ncpu);
-  if (sysctl(mib, arraysize(mib), &ncpu, &size, NULL, 0) < 0) {
-    NOTREACHED();
-    return 1;
-  }
-  return ncpu;
-}
-
-// static
-int64_t SysInfo::AmountOfPhysicalMemory() {
-  return AmountOfMemory(_SC_PHYS_PAGES);
-}
-
-// static
-int64_t SysInfo::AmountOfAvailablePhysicalMemory() {
-  return AmountOfMemory(_SC_AVPHYS_PAGES);
-}
-
-// static
-size_t SysInfo::MaxSharedMemorySize() {
-  int mib[] = { CTL_KERN, KERN_SHMINFO, KERN_SHMINFO_SHMMAX };
-  size_t limit;
-  size_t size = sizeof(limit);
-  if (sysctl(mib, arraysize(mib), &limit, &size, NULL, 0) < 0) {
-    NOTREACHED();
-    return 0;
-  }
-  return limit;
-}
-
-// static
-std::string SysInfo::CPUModelName() {
-  int mib[] = { CTL_HW, HW_MODEL };
-  char name[256];
-  size_t len = arraysize(name);
-  if (sysctl(mib, arraysize(mib), name, &len, NULL, 0) < 0) {
-    NOTREACHED();
-    return std::string();
-  }
-  return name;
-}
-
-}  // namespace butil

+ 0 - 133
src/butil/sys_info_posix.cc

@@ -1,133 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/sys_info.h"
-
-#include <errno.h>
-#include <string.h>
-#include <sys/param.h>
-#include <sys/resource.h>
-#include <sys/utsname.h>
-#include <unistd.h>
-
-#include "butil/basictypes.h"
-#include "butil/file_util.h"
-#include "butil/lazy_instance.h"
-#include "butil/logging.h"
-#include "butil/strings/utf_string_conversions.h"
-#include "butil/sys_info_internal.h"
-#include "butil/threading/thread_restrictions.h"
-
-#if defined(OS_ANDROID)
-#include <sys/vfs.h>
-#define statvfs statfs  // Android uses a statvfs-like statfs struct and call.
-#else
-#include <sys/statvfs.h>
-#endif
-
-namespace {
-
-#if !defined(OS_OPENBSD)
-int NumberOfProcessors() {
-  // It seems that sysconf returns the number of "logical" processors on both
-  // Mac and Linux.  So we get the number of "online logical" processors.
-  long res = sysconf(_SC_NPROCESSORS_ONLN);
-  if (res == -1) {
-    NOTREACHED();
-    return 1;
-  }
-
-  return static_cast<int>(res);
-}
-
-butil::LazyInstance<
-    butil::internal::LazySysInfoValue<int, NumberOfProcessors> >::Leaky
-    g_lazy_number_of_processors = LAZY_INSTANCE_INITIALIZER;
-#endif
-
-int64_t AmountOfVirtualMemory() {
-  struct rlimit limit;
-  int result = getrlimit(RLIMIT_DATA, &limit);
-  if (result != 0) {
-    NOTREACHED();
-    return 0;
-  }
-  return limit.rlim_cur == RLIM_INFINITY ? 0 : limit.rlim_cur;
-}
-
-butil::LazyInstance<
-    butil::internal::LazySysInfoValue<int64_t, AmountOfVirtualMemory> >::Leaky
-    g_lazy_virtual_memory = LAZY_INSTANCE_INITIALIZER;
-
-}  // namespace
-
-namespace butil {
-
-#if !defined(OS_OPENBSD)
-int SysInfo::NumberOfProcessors() {
-  return g_lazy_number_of_processors.Get().value();
-}
-#endif
-
-// static
-int64_t SysInfo::AmountOfVirtualMemory() {
-  return g_lazy_virtual_memory.Get().value();
-}
-
-// static
-int64_t SysInfo::AmountOfFreeDiskSpace(const FilePath& path) {
-  butil::ThreadRestrictions::AssertIOAllowed();
-
-  struct statvfs stats;
-  if (HANDLE_EINTR(statvfs(path.value().c_str(), &stats)) != 0)
-    return -1;
-  return static_cast<int64_t>(stats.f_bavail) * stats.f_frsize;
-}
-
-#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
-// static
-std::string SysInfo::OperatingSystemName() {
-  struct utsname info;
-  if (uname(&info) < 0) {
-    NOTREACHED();
-    return std::string();
-  }
-  return std::string(info.sysname);
-}
-#endif
-
-#if !defined(OS_MACOSX) && !defined(OS_ANDROID)
-// static
-std::string SysInfo::OperatingSystemVersion() {
-  struct utsname info;
-  if (uname(&info) < 0) {
-    NOTREACHED();
-    return std::string();
-  }
-  return std::string(info.release);
-}
-#endif
-
-// static
-std::string SysInfo::OperatingSystemArchitecture() {
-  struct utsname info;
-  if (uname(&info) < 0) {
-    NOTREACHED();
-    return std::string();
-  }
-  std::string arch(info.machine);
-  if (arch == "i386" || arch == "i486" || arch == "i586" || arch == "i686") {
-    arch = "x86";
-  } else if (arch == "amd64") {
-    arch = "x86_64";
-  }
-  return arch;
-}
-
-// static
-size_t SysInfo::VMAllocationGranularity() {
-  return getpagesize();
-}
-
-}  // namespace butil

+ 0 - 4
test/Makefile

@@ -30,7 +30,6 @@ TEST_BUTIL_SOURCES = \
     callback_list_unittest.cc \
     callback_unittest.cc \
     cancelable_callback_unittest.cc \
-    command_line_unittest.cc \
     hash_tables_unittest.cc \
     linked_list_unittest.cc \
     mru_cache_unittest.cc \
@@ -85,7 +84,6 @@ TEST_BUTIL_SOURCES = \
     condition_variable_unittest.cc \
     lock_unittest.cc \
     waitable_event_unittest.cc \
-    sys_info_unittest.cc \
     type_traits_unittest.cc \
     non_thread_safe_unittest.cc \
     platform_thread_unittest.cc \
@@ -121,9 +119,7 @@ TEST_BUTIL_SOURCES = \
     crc32c_unittest.cc \
     iobuf_unittest.cc \
     test_switches.cc \
-    test_timeouts.cc \
     scoped_locale.cc \
-    test_file_util.cc \
     test_file_util_linux.cc \
     butil_unittest_main.cpp
 

+ 0 - 11
test/butil_unittest_main.cpp

@@ -3,10 +3,8 @@
 #include <sys/resource.h>
 #include <gtest/gtest.h>
 #include <gflags/gflags.h>
-#include "butil/command_line.h"
 #include "butil/base_switches.h"
 #include "butil/at_exit.h"
-#include "test/test_timeouts.h"
 #include "test/multiprocess_func_list.h"
 
 // Disable coredumps by default to avoid generating a lot of coredumps
@@ -15,17 +13,8 @@ DEFINE_bool(disable_coredump, true, "Never core dump");
 
 int main(int argc, char** argv) {
     butil::AtExitManager at_exit;
-    butil::CommandLine::Init(argc, argv);
-    TestTimeouts::Initialize();
     testing::InitGoogleTest(&argc, argv);
     
-    std::string client_func =
-        butil::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
-        switches::kTestChildProcess);
-    // Check to see if we are being run as a client process.
-    if (!client_func.empty()) {
-        return multi_process_function_list::InvokeChildProcessTest(client_func);
-    }
     google::ParseCommandLineFlags(&argc, &argv, true);
     if (FLAGS_disable_coredump) {
         rlimit core_limit;

+ 0 - 364
test/command_line_unittest.cc

@@ -1,364 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include <string>
-#include <vector>
-
-#include "butil/basictypes.h"
-#include "butil/command_line.h"
-#include "butil/files/file_path.h"
-#include "butil/strings/utf_string_conversions.h"
-#include <gtest/gtest.h>
-
-using butil::FilePath;
-
-// To test Windows quoting behavior, we use a string that has some backslashes
-// and quotes.
-// Consider the command-line argument: q\"bs1\bs2\\bs3q\\\"
-// Here it is with C-style escapes.
-static const CommandLine::StringType kTrickyQuoted =
-    FILE_PATH_LITERAL("q\\\"bs1\\bs2\\\\bs3q\\\\\\\"");
-// It should be parsed by Windows as: q"bs1\bs2\\bs3q\"
-// Here that is with C-style escapes.
-static const CommandLine::StringType kTricky =
-    FILE_PATH_LITERAL("q\"bs1\\bs2\\\\bs3q\\\"");
-
-TEST(CommandLineTest, CommandLineConstructor) {
-  const CommandLine::CharType* argv[] = {
-      FILE_PATH_LITERAL("program"),
-      FILE_PATH_LITERAL("--foo="),
-      FILE_PATH_LITERAL("-bAr"),
-      FILE_PATH_LITERAL("-spaetzel=pierogi"),
-      FILE_PATH_LITERAL("-baz"),
-      FILE_PATH_LITERAL("flim"),
-      FILE_PATH_LITERAL("--other-switches=--dog=canine --cat=feline"),
-      FILE_PATH_LITERAL("-spaetzle=Crepe"),
-      FILE_PATH_LITERAL("-=loosevalue"),
-      FILE_PATH_LITERAL("-"),
-      FILE_PATH_LITERAL("FLAN"),
-      FILE_PATH_LITERAL("a"),
-      FILE_PATH_LITERAL("--input-translation=45--output-rotation"),
-      FILE_PATH_LITERAL("--"),
-      FILE_PATH_LITERAL("--"),
-      FILE_PATH_LITERAL("--not-a-switch"),
-      FILE_PATH_LITERAL("\"in the time of submarines...\""),
-      FILE_PATH_LITERAL("unquoted arg-with-space")};
-  CommandLine cl(arraysize(argv), argv);
-
-  EXPECT_FALSE(cl.GetCommandLineString().empty());
-  EXPECT_FALSE(cl.HasSwitch("cruller"));
-  EXPECT_FALSE(cl.HasSwitch("flim"));
-  EXPECT_FALSE(cl.HasSwitch("program"));
-  EXPECT_FALSE(cl.HasSwitch("dog"));
-  EXPECT_FALSE(cl.HasSwitch("cat"));
-  EXPECT_FALSE(cl.HasSwitch("output-rotation"));
-  EXPECT_FALSE(cl.HasSwitch("not-a-switch"));
-  EXPECT_FALSE(cl.HasSwitch("--"));
-
-  EXPECT_EQ(FilePath(FILE_PATH_LITERAL("program")).value(),
-            cl.GetProgram().value());
-
-  EXPECT_TRUE(cl.HasSwitch("foo"));
-  EXPECT_TRUE(cl.HasSwitch("bAr"));
-  EXPECT_TRUE(cl.HasSwitch("baz"));
-  EXPECT_TRUE(cl.HasSwitch("spaetzle"));
-#if defined(OS_WIN)
-  EXPECT_TRUE(cl.HasSwitch("SPAETZLE"));
-#endif
-  EXPECT_TRUE(cl.HasSwitch("other-switches"));
-  EXPECT_TRUE(cl.HasSwitch("input-translation"));
-
-  EXPECT_EQ("Crepe", cl.GetSwitchValueASCII("spaetzle"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("Foo"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("bar"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("cruller"));
-  EXPECT_EQ("--dog=canine --cat=feline", cl.GetSwitchValueASCII(
-      "other-switches"));
-  EXPECT_EQ("45--output-rotation", cl.GetSwitchValueASCII("input-translation"));
-
-  const CommandLine::StringVector& args = cl.GetArgs();
-  ASSERT_EQ(8U, args.size());
-
-  std::vector<CommandLine::StringType>::const_iterator iter = args.begin();
-  EXPECT_EQ(FILE_PATH_LITERAL("flim"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("-"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("FLAN"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("a"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("--"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("--not-a-switch"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("\"in the time of submarines...\""), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("unquoted arg-with-space"), *iter);
-  ++iter;
-  EXPECT_TRUE(iter == args.end());
-}
-
-TEST(CommandLineTest, CommandLineFromString) {
-#if defined(OS_WIN)
-  CommandLine cl = CommandLine::FromString(
-      L"program --foo= -bAr  /Spaetzel=pierogi /Baz flim "
-      L"--other-switches=\"--dog=canine --cat=feline\" "
-      L"-spaetzle=Crepe   -=loosevalue  FLAN "
-      L"--input-translation=\"45\"--output-rotation "
-      L"--quotes=" + kTrickyQuoted + L" "
-      L"-- -- --not-a-switch "
-      L"\"in the time of submarines...\"");
-
-  EXPECT_FALSE(cl.GetCommandLineString().empty());
-  EXPECT_FALSE(cl.HasSwitch("cruller"));
-  EXPECT_FALSE(cl.HasSwitch("flim"));
-  EXPECT_FALSE(cl.HasSwitch("program"));
-  EXPECT_FALSE(cl.HasSwitch("dog"));
-  EXPECT_FALSE(cl.HasSwitch("cat"));
-  EXPECT_FALSE(cl.HasSwitch("output-rotation"));
-  EXPECT_FALSE(cl.HasSwitch("not-a-switch"));
-  EXPECT_FALSE(cl.HasSwitch("--"));
-
-  EXPECT_EQ(FilePath(FILE_PATH_LITERAL("program")).value(),
-            cl.GetProgram().value());
-
-  EXPECT_TRUE(cl.HasSwitch("foo"));
-  EXPECT_TRUE(cl.HasSwitch("bar"));
-  EXPECT_TRUE(cl.HasSwitch("baz"));
-  EXPECT_TRUE(cl.HasSwitch("spaetzle"));
-  EXPECT_TRUE(cl.HasSwitch("SPAETZLE"));
-  EXPECT_TRUE(cl.HasSwitch("other-switches"));
-  EXPECT_TRUE(cl.HasSwitch("input-translation"));
-  EXPECT_TRUE(cl.HasSwitch("quotes"));
-
-  EXPECT_EQ("Crepe", cl.GetSwitchValueASCII("spaetzle"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("Foo"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("bar"));
-  EXPECT_EQ("", cl.GetSwitchValueASCII("cruller"));
-  EXPECT_EQ("--dog=canine --cat=feline", cl.GetSwitchValueASCII(
-      "other-switches"));
-  EXPECT_EQ("45--output-rotation", cl.GetSwitchValueASCII("input-translation"));
-  EXPECT_EQ(kTricky, cl.GetSwitchValueNative("quotes"));
-
-  const CommandLine::StringVector& args = cl.GetArgs();
-  ASSERT_EQ(5U, args.size());
-
-  std::vector<CommandLine::StringType>::const_iterator iter = args.begin();
-  EXPECT_EQ(FILE_PATH_LITERAL("flim"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("FLAN"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("--"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("--not-a-switch"), *iter);
-  ++iter;
-  EXPECT_EQ(FILE_PATH_LITERAL("in the time of submarines..."), *iter);
-  ++iter;
-  EXPECT_TRUE(iter == args.end());
-
-  // Check that a generated string produces an equivalent command line.
-  CommandLine cl_duplicate = CommandLine::FromString(cl.GetCommandLineString());
-  EXPECT_EQ(cl.GetCommandLineString(), cl_duplicate.GetCommandLineString());
-#endif
-}
-
-// Tests behavior with an empty input string.
-TEST(CommandLineTest, EmptyString) {
-#if defined(OS_WIN)
-  CommandLine cl_from_string = CommandLine::FromString(L"");
-  EXPECT_TRUE(cl_from_string.GetCommandLineString().empty());
-  EXPECT_TRUE(cl_from_string.GetProgram().empty());
-  EXPECT_EQ(1U, cl_from_string.argv().size());
-  EXPECT_TRUE(cl_from_string.GetArgs().empty());
-#endif
-  CommandLine cl_from_argv(0, NULL);
-  EXPECT_TRUE(cl_from_argv.GetCommandLineString().empty());
-  EXPECT_TRUE(cl_from_argv.GetProgram().empty());
-  EXPECT_EQ(1U, cl_from_argv.argv().size());
-  EXPECT_TRUE(cl_from_argv.GetArgs().empty());
-}
-
-TEST(CommandLineTest, GetArgumentsString) {
-  static const FilePath::CharType kPath1[] =
-      FILE_PATH_LITERAL("C:\\Some File\\With Spaces.ggg");
-  static const FilePath::CharType kPath2[] =
-      FILE_PATH_LITERAL("C:\\no\\spaces.ggg");
-
-  static const char kFirstArgName[] = "first-arg";
-  static const char kSecondArgName[] = "arg2";
-  static const char kThirdArgName[] = "arg with space";
-  static const char kFourthArgName[] = "nospace";
-
-  CommandLine cl(CommandLine::NO_PROGRAM);
-  cl.AppendSwitchPath(kFirstArgName, FilePath(kPath1));
-  cl.AppendSwitchPath(kSecondArgName, FilePath(kPath2));
-  cl.AppendArg(kThirdArgName);
-  cl.AppendArg(kFourthArgName);
-
-#if defined(OS_WIN)
-  CommandLine::StringType expected_first_arg(
-      butil::UTF8ToUTF16(kFirstArgName));
-  CommandLine::StringType expected_second_arg(
-      butil::UTF8ToUTF16(kSecondArgName));
-  CommandLine::StringType expected_third_arg(
-      butil::UTF8ToUTF16(kThirdArgName));
-  CommandLine::StringType expected_fourth_arg(
-      butil::UTF8ToUTF16(kFourthArgName));
-#elif defined(OS_POSIX)
-  CommandLine::StringType expected_first_arg(kFirstArgName);
-  CommandLine::StringType expected_second_arg(kSecondArgName);
-  CommandLine::StringType expected_third_arg(kThirdArgName);
-  CommandLine::StringType expected_fourth_arg(kFourthArgName);
-#endif
-
-#if defined(OS_WIN)
-#define QUOTE_ON_WIN FILE_PATH_LITERAL("\"")
-#else
-#define QUOTE_ON_WIN FILE_PATH_LITERAL("")
-#endif  // OS_WIN
-
-  CommandLine::StringType expected_str;
-  expected_str.append(FILE_PATH_LITERAL("--"))
-              .append(expected_first_arg)
-              .append(FILE_PATH_LITERAL("="))
-              .append(QUOTE_ON_WIN)
-              .append(kPath1)
-              .append(QUOTE_ON_WIN)
-              .append(FILE_PATH_LITERAL(" "))
-              .append(FILE_PATH_LITERAL("--"))
-              .append(expected_second_arg)
-              .append(FILE_PATH_LITERAL("="))
-              .append(QUOTE_ON_WIN)
-              .append(kPath2)
-              .append(QUOTE_ON_WIN)
-              .append(FILE_PATH_LITERAL(" "))
-              .append(QUOTE_ON_WIN)
-              .append(expected_third_arg)
-              .append(QUOTE_ON_WIN)
-              .append(FILE_PATH_LITERAL(" "))
-              .append(expected_fourth_arg);
-  EXPECT_EQ(expected_str, cl.GetArgumentsString());
-}
-
-// Test methods for appending switches to a command line.
-TEST(CommandLineTest, AppendSwitches) {
-  std::string switch1 = "switch1";
-  std::string switch2 = "switch2";
-  std::string value2 = "value";
-  std::string switch3 = "switch3";
-  std::string value3 = "a value with spaces";
-  std::string switch4 = "switch4";
-  std::string value4 = "\"a value with quotes\"";
-  std::string switch5 = "quotes";
-  CommandLine::StringType value5 = kTricky;
-
-  CommandLine cl(FilePath(FILE_PATH_LITERAL("Program")));
-
-  cl.AppendSwitch(switch1);
-  cl.AppendSwitchASCII(switch2, value2);
-  cl.AppendSwitchASCII(switch3, value3);
-  cl.AppendSwitchASCII(switch4, value4);
-  cl.AppendSwitchNative(switch5, value5);
-
-  EXPECT_TRUE(cl.HasSwitch(switch1));
-  EXPECT_TRUE(cl.HasSwitch(switch2));
-  EXPECT_EQ(value2, cl.GetSwitchValueASCII(switch2));
-  EXPECT_TRUE(cl.HasSwitch(switch3));
-  EXPECT_EQ(value3, cl.GetSwitchValueASCII(switch3));
-  EXPECT_TRUE(cl.HasSwitch(switch4));
-  EXPECT_EQ(value4, cl.GetSwitchValueASCII(switch4));
-  EXPECT_TRUE(cl.HasSwitch(switch5));
-  EXPECT_EQ(value5, cl.GetSwitchValueNative(switch5));
-
-#if defined(OS_WIN)
-  EXPECT_EQ(L"Program "
-            L"--switch1 "
-            L"--switch2=value "
-            L"--switch3=\"a value with spaces\" "
-            L"--switch4=\"\\\"a value with quotes\\\"\" "
-            L"--quotes=\"" + kTrickyQuoted + L"\"",
-            cl.GetCommandLineString());
-#endif
-}
-
-TEST(CommandLineTest, AppendSwitchesDashDash) {
- const CommandLine::CharType* raw_argv[] = { FILE_PATH_LITERAL("prog"),
-                                             FILE_PATH_LITERAL("--"),
-                                             FILE_PATH_LITERAL("--arg1") };
-  CommandLine cl(arraysize(raw_argv), raw_argv);
-
-  cl.AppendSwitch("switch1");
-  cl.AppendSwitchASCII("switch2", "foo");
-
-  cl.AppendArg("--arg2");
-
-  EXPECT_EQ(FILE_PATH_LITERAL("prog --switch1 --switch2=foo -- --arg1 --arg2"),
-            cl.GetCommandLineString());
-  CommandLine::StringVector cl_argv = cl.argv();
-  EXPECT_EQ(FILE_PATH_LITERAL("prog"), cl_argv[0]);
-  EXPECT_EQ(FILE_PATH_LITERAL("--switch1"), cl_argv[1]);
-  EXPECT_EQ(FILE_PATH_LITERAL("--switch2=foo"), cl_argv[2]);
-  EXPECT_EQ(FILE_PATH_LITERAL("--"), cl_argv[3]);
-  EXPECT_EQ(FILE_PATH_LITERAL("--arg1"), cl_argv[4]);
-  EXPECT_EQ(FILE_PATH_LITERAL("--arg2"), cl_argv[5]);
-}
-
-// Tests that when AppendArguments is called that the program is set correctly
-// on the target CommandLine object and the switches from the source
-// CommandLine are added to the target.
-TEST(CommandLineTest, AppendArguments) {
-  CommandLine cl1(FilePath(FILE_PATH_LITERAL("Program")));
-  cl1.AppendSwitch("switch1");
-  cl1.AppendSwitchASCII("switch2", "foo");
-
-  CommandLine cl2(CommandLine::NO_PROGRAM);
-  cl2.AppendArguments(cl1, true);
-  EXPECT_EQ(cl1.GetProgram().value(), cl2.GetProgram().value());
-  EXPECT_EQ(cl1.GetCommandLineString(), cl2.GetCommandLineString());
-
-  CommandLine c1(FilePath(FILE_PATH_LITERAL("Program1")));
-  c1.AppendSwitch("switch1");
-  CommandLine c2(FilePath(FILE_PATH_LITERAL("Program2")));
-  c2.AppendSwitch("switch2");
-
-  c1.AppendArguments(c2, true);
-  EXPECT_EQ(c1.GetProgram().value(), c2.GetProgram().value());
-  EXPECT_TRUE(c1.HasSwitch("switch1"));
-  EXPECT_TRUE(c1.HasSwitch("switch2"));
-}
-
-#if defined(OS_WIN)
-// Make sure that the command line string program paths are quoted as necessary.
-// This only makes sense on Windows and the test is basically here to guard
-// against regressions.
-TEST(CommandLineTest, ProgramQuotes) {
-  // Check that quotes are not added for paths without spaces.
-  const FilePath kProgram(L"Program");
-  CommandLine cl_program(kProgram);
-  EXPECT_EQ(kProgram.value(), cl_program.GetProgram().value());
-  EXPECT_EQ(kProgram.value(), cl_program.GetCommandLineString());
-
-  const FilePath kProgramPath(L"Program Path");
-
-  // Check that quotes are not returned from GetProgram().
-  CommandLine cl_program_path(kProgramPath);
-  EXPECT_EQ(kProgramPath.value(), cl_program_path.GetProgram().value());
-
-  // Check that quotes are added to command line string paths containing spaces.
-  CommandLine::StringType cmd_string(cl_program_path.GetCommandLineString());
-  CommandLine::StringType program_string(cl_program_path.GetProgram().value());
-  EXPECT_EQ('"', cmd_string[0]);
-  EXPECT_EQ(program_string, cmd_string.substr(1, program_string.length()));
-  EXPECT_EQ('"', cmd_string[program_string.length() + 1]);
-}
-#endif
-
-// Calling Init multiple times should not modify the previous CommandLine.
-TEST(CommandLineTest, Init) {
-  CommandLine* initial = CommandLine::ForCurrentProcess();
-  EXPECT_FALSE(CommandLine::Init(0, NULL));
-  CommandLine* current = CommandLine::ForCurrentProcess();
-  EXPECT_EQ(initial, current);
-}

+ 2 - 0
test/endpoint_unittest.cpp

@@ -81,10 +81,12 @@ TEST(EndPointTest, endpoint) {
     ASSERT_EQ(0, hostname2endpoint("localhost:65535", &p5)) << berror();
     ASSERT_EQ(0, hostname2endpoint("localhost:0", &p5));
 
+#ifdef BAIDU_INTERNAL
     butil::EndPoint p6;
     ASSERT_EQ(0, hostname2endpoint("tc-cm-et21.tc: 289 ", &p6));
     ASSERT_STREQ("10.23.249.73", butil::ip2str(p6.ip).c_str());
     ASSERT_EQ(289, p6.port);
+#endif
 }
 
 TEST(EndPointTest, hash_table) {

+ 0 - 2
test/file_util_unittest.cc

@@ -23,13 +23,11 @@
 #include <set>
 #include <vector>
 
-#include "butil/base_paths.h"
 #include "butil/file_util.h"
 #include "butil/files/file_enumerator.h"
 #include "butil/files/file_path.h"
 #include "butil/files/scoped_file.h"
 #include "butil/files/scoped_temp_dir.h"
-#include "butil/path_service.h"
 #include "butil/strings/utf_string_conversions.h"
 #include "test/test_file_util.h"
 #include "butil/threading/platform_thread.h"

+ 0 - 57
test/multiprocess_func_list.cc

@@ -1,57 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "multiprocess_func_list.h"
-
-#include <map>
-
-// Helper functions to maintain mapping of "test name"->test func.
-// The information is accessed via a global map.
-namespace multi_process_function_list {
-
-namespace {
-
-struct ProcessFunctions {
-  ProcessFunctions() : main(NULL), setup(NULL) {}
-  ProcessFunctions(TestMainFunctionPtr main, SetupFunctionPtr setup)
-      : main(main),
-        setup(setup) {
-  }
-  TestMainFunctionPtr main;
-  SetupFunctionPtr setup;
-};
-
-typedef std::map<std::string, ProcessFunctions> MultiProcessTestMap;
-
-// Retrieve a reference to the global 'func name' -> func ptr map.
-MultiProcessTestMap& GetMultiprocessFuncMap() {
-  static MultiProcessTestMap test_name_to_func_ptr_map;
-  return test_name_to_func_ptr_map;
-}
-
-}  // namespace
-
-AppendMultiProcessTest::AppendMultiProcessTest(
-    std::string test_name,
-    TestMainFunctionPtr main_func_ptr,
-    SetupFunctionPtr setup_func_ptr) {
-  GetMultiprocessFuncMap()[test_name] =
-      ProcessFunctions(main_func_ptr, setup_func_ptr);
-}
-
-int InvokeChildProcessTest(std::string test_name) {
-  MultiProcessTestMap& func_lookup_table = GetMultiprocessFuncMap();
-  MultiProcessTestMap::iterator it = func_lookup_table.find(test_name);
-  if (it != func_lookup_table.end()) {
-    const ProcessFunctions& process_functions = it->second;
-    if (process_functions.setup)
-      (*process_functions.setup)();
-    if (process_functions.main)
-      return (*process_functions.main)();
-  }
-
-  return -1;
-}
-
-}  // namespace multi_process_function_list

+ 0 - 59
test/multiprocess_test.cc

@@ -1,59 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "test/multiprocess_test.h"
-
-#include "butil/base_switches.h"
-#include "butil/command_line.h"
-
-namespace butil {
-
-#if !defined(OS_ANDROID)
-ProcessHandle SpawnMultiProcessTestChild(
-    const std::string& procname,
-    const CommandLine& base_command_line,
-    const LaunchOptions& options) {
-  CommandLine command_line(base_command_line);
-  // TODO(viettrungluu): See comment above |MakeCmdLine()| in the header file.
-  // This is a temporary hack, since |MakeCmdLine()| has to provide a full
-  // command line.
-  if (!command_line.HasSwitch(switches::kTestChildProcess))
-    command_line.AppendSwitchASCII(switches::kTestChildProcess, procname);
-
-  ProcessHandle handle = kNullProcessHandle;
-  LaunchProcess(command_line, options, &handle);
-  return handle;
-}
-#endif  // !defined(OS_ANDROID)
-
-CommandLine GetMultiProcessTestChildBaseCommandLine() {
-  return *CommandLine::ForCurrentProcess();
-}
-
-// MultiProcessTest ------------------------------------------------------------
-
-MultiProcessTest::MultiProcessTest() {
-}
-
-ProcessHandle MultiProcessTest::SpawnChild(const std::string& procname) {
-  LaunchOptions options;
-#if defined(OS_WIN)
-  options.start_hidden = true;
-#endif
-  return SpawnChildWithOptions(procname, options);
-}
-
-ProcessHandle MultiProcessTest::SpawnChildWithOptions(
-    const std::string& procname,
-    const LaunchOptions& options) {
-  return SpawnMultiProcessTestChild(procname, MakeCmdLine(procname), options);
-}
-
-CommandLine MultiProcessTest::MakeCmdLine(const std::string& procname) {
-  CommandLine command_line = GetMultiProcessTestChildBaseCommandLine();
-  command_line.AppendSwitchASCII(switches::kTestChildProcess, procname);
-  return command_line;
-}
-
-}  // namespace butil

+ 0 - 131
test/multiprocess_test.h

@@ -1,131 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_TEST_MULTIPROCESS_TEST_H_
-#define BASE_TEST_MULTIPROCESS_TEST_H_
-
-#include <string>
-#include <gtest/gtest.h>
-#include "butil/basictypes.h"
-#include "butil/process/launch.h"
-#include "butil/process/process_handle.h"
-#include "butil/build_config.h"
-
-namespace butil {
-
-class CommandLine;
-
-// Helpers to spawn a child for a multiprocess test and execute a designated
-// function. Use these when you already have another base class for your test
-// fixture, but you want (some) of your tests to be multiprocess (otherwise you
-// may just want to derive your fixture from |MultiProcessTest|, below).
-//
-// Use these helpers as follows:
-//
-//   TEST_F(MyTest, ATest) {
-//     CommandLine command_line(
-//         butil::GetMultiProcessTestChildBaseCommandLine());
-//     // Maybe add our own switches to |command_line|....
-//
-//     LaunchOptions options;
-//     // Maybe set some options (e.g., |start_hidden| on Windows)....
-//
-//     // Start a child process and run |a_test_func|.
-//     butil::ProcessHandle test_child_handle =
-//         butil::SpawnMultiProcessTestChild("a_test_func", command_line,
-//                                          options);
-//
-//     // Do stuff involving |test_child_handle| and the child process....
-//
-//     int rv = -1;
-//     ASSERT_TRUE(butil::WaitForExitCodeWithTimeout(
-//         test_child_handle, &rv, TestTimeouts::action_timeout()));
-//     butil::CloseProcessHandle(test_child_handle);
-//     EXPECT_EQ(0, rv);
-//   }
-//
-//   // Note: |MULTIPROCESS_TEST_MAIN()| is defined in
-//   // test/multi_process_function_list.h.
-//   MULTIPROCESS_TEST_MAIN(a_test_func) {
-//     // Code here runs in a child process....
-//     return 0;
-//   }
-
-// Spawns a child process and executes the function |procname| declared using
-// |MULTIPROCESS_TEST_MAIN()| or |MULTIPROCESS_TEST_MAIN_WITH_SETUP()|.
-// |command_line| should be as provided by
-// |GetMultiProcessTestChildBaseCommandLine()| (below), possibly with arguments
-// added. Note: On Windows, you probably want to set |options.start_hidden|.
-ProcessHandle SpawnMultiProcessTestChild(
-    const std::string& procname,
-    const CommandLine& command_line,
-    const LaunchOptions& options);
-
-// Gets the base command line for |SpawnMultiProcessTestChild()|. To this, you
-// may add any flags needed for your child process.
-CommandLine GetMultiProcessTestChildBaseCommandLine();
-
-// MultiProcessTest ------------------------------------------------------------
-
-// A MultiProcessTest is a test class which makes it easier to
-// write a test which requires code running out of process.
-//
-// To create a multiprocess test simply follow these steps:
-//
-// 1) Derive your test from MultiProcessTest. Example:
-//
-//    class MyTest : public MultiProcessTest {
-//    };
-//
-//    TEST_F(MyTest, TestCaseName) {
-//      ...
-//    }
-//
-// 2) Create a mainline function for the child processes and include
-//    test/multiprocess_func_list.h.
-//    See the declaration of the MULTIPROCESS_TEST_MAIN macro
-//    in that file for an example.
-// 3) Call SpawnChild("foo"), where "foo" is the name of
-//    the function you wish to run in the child processes.
-// That's it!
-class MultiProcessTest : public testing::Test {
- public:
-  MultiProcessTest();
-
- protected:
-  // Run a child process.
-  // 'procname' is the name of a function which the child will
-  // execute.  It must be exported from this library in order to
-  // run.
-  //
-  // Example signature:
-  //    extern "C" int __declspec(dllexport) FooBar() {
-  //         // do client work here
-  //    }
-  //
-  // Returns the handle to the child, or NULL on failure
-  ProcessHandle SpawnChild(const std::string& procname);
-
-  // Run a child process using the given launch options.
-  //
-  // Note: On Windows, you probably want to set |options.start_hidden|.
-  ProcessHandle SpawnChildWithOptions(const std::string& procname,
-                                      const LaunchOptions& options);
-
-  // Set up the command line used to spawn the child process.
-  // Override this to add things to the command line (calling this first in the
-  // override).
-  // Note that currently some tests rely on this providing a full command line,
-  // which they then use directly with |LaunchProcess()|.
-  // TODO(viettrungluu): Remove this and add a virtual
-  // |ModifyChildCommandLine()|; make the two divergent uses more sane.
-  virtual CommandLine MakeCmdLine(const std::string& procname);
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(MultiProcessTest);
-};
-
-}  // namespace butil
-
-#endif  // BASE_TEST_MULTIPROCESS_TEST_H_

+ 0 - 250
test/path_service_unittest.cc

@@ -1,250 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/path_service.h"
-
-#include "butil/basictypes.h"
-#include "butil/file_util.h"
-#include "butil/files/file_path.h"
-#include "butil/files/scoped_temp_dir.h"
-#include "butil/strings/string_util.h"
-#include "butil/build_config.h"
-#include <gtest/gtest-spi.h>
-#include <gtest/gtest.h>
-#include <gtest/gtest.h>
-
-#if defined(OS_WIN)
-#include <userenv.h>
-#include "butil/win/windows_version.h"
-// userenv.dll is required for GetDefaultUserProfileDirectory().
-#pragma comment(lib, "userenv.lib")
-#endif
-
-namespace {
-
-// Returns true if PathService::Get returns true and sets the path parameter
-// to non-empty for the given PathService::DirType enumeration value.
-bool ALLOW_UNUSED ReturnsValidPath(int dir_type) {
-  butil::FilePath path;
-  bool result = PathService::Get(dir_type, &path);
-
-  // Some paths might not exist on some platforms in which case confirming
-  // |result| is true and !path.empty() is the best we can do.
-  bool check_path_exists = true;
-#if defined(OS_POSIX)
-  // If chromium has never been started on this account, the cache path may not
-  // exist.
-  if (dir_type == butil::DIR_CACHE)
-    check_path_exists = false;
-#endif
-#if defined(OS_LINUX)
-  // On the linux try-bots: a path is returned (e.g. /home/chrome-bot/Desktop),
-  // but it doesn't exist.
-  if (dir_type == butil::DIR_USER_DESKTOP)
-    check_path_exists = false;
-#endif
-#if defined(OS_WIN)
-  if (dir_type == butil::DIR_DEFAULT_USER_QUICK_LAUNCH) {
-    // On Windows XP, the Quick Launch folder for the "Default User" doesn't
-    // exist by default. At least confirm that the path returned begins with the
-    // Default User's profile path.
-    if (butil::win::GetVersion() < butil::win::VERSION_VISTA) {
-      wchar_t default_profile_path[MAX_PATH];
-      DWORD size = arraysize(default_profile_path);
-      return (result &&
-              ::GetDefaultUserProfileDirectory(default_profile_path, &size) &&
-              StartsWith(path.value(), default_profile_path, false));
-    }
-  } else if (dir_type == butil::DIR_TASKBAR_PINS) {
-    // There is no pinned-to-taskbar shortcuts prior to Win7.
-    if (butil::win::GetVersion() < butil::win::VERSION_WIN7)
-      check_path_exists = false;
-  }
-#endif
-#if defined(OS_MACOSX)
-  if (dir_type != butil::DIR_EXE && dir_type != butil::DIR_MODULE &&
-      dir_type != butil::FILE_EXE && dir_type != butil::FILE_MODULE) {
-    if (path.ReferencesParent())
-      return false;
-  }
-#else
-  if (path.ReferencesParent())
-    return false;
-#endif
-  return result && !path.empty() && (!check_path_exists ||
-                                     butil::PathExists(path));
-}
-
-#if defined(OS_WIN)
-// Function to test any directory keys that are not supported on some versions
-// of Windows. Checks that the function fails and that the returned path is
-// empty.
-bool ReturnsInvalidPath(int dir_type) {
-  butil::FilePath path;
-  bool result = PathService::Get(dir_type, &path);
-  return !result && path.empty();
-}
-#endif
-
-}  // namespace
-
-// On the Mac this winds up using some autoreleased objects, so we need to
-// be a testing::Test.
-typedef testing::Test PathServiceTest;
-
-// FIXME(gejun): Fail due to
-// [0710/142222:FATAL:path_service.cc(212)] Check failed: path.empty(). provider should not have modified path
-#if defined(FixedPathServiceTestGet)
-// Test that all PathService::Get calls return a value and a true result
-// in the development environment.  (This test was created because a few
-// later changes to Get broke the semantics of the function and yielded the
-// correct value while returning false.)
-TEST_F(PathServiceTest, Get) {
-  for (int key = butil::PATH_START + 1; key < butil::PATH_END; ++key) {
-#if defined(OS_ANDROID)
-    if (key == butil::FILE_MODULE || key == butil::DIR_USER_DESKTOP ||
-        key == butil::DIR_HOME)
-      continue;  // Android doesn't implement these.
-#elif defined(OS_IOS)
-    if (key == butil::DIR_USER_DESKTOP)
-      continue;  // iOS doesn't implement DIR_USER_DESKTOP;
-#endif
-    EXPECT_PRED1(ReturnsValidPath, key);
-  }
-#if defined(OS_WIN)
-  for (int key = butil::PATH_WIN_START + 1; key < butil::PATH_WIN_END; ++key) {
-    bool valid = true;
-    switch(key) {
-      case butil::DIR_LOCAL_APP_DATA_LOW:
-        // DIR_LOCAL_APP_DATA_LOW is not supported prior Vista and is expected
-        // to fail.
-        valid = butil::win::GetVersion() >= butil::win::VERSION_VISTA;
-        break;
-      case butil::DIR_APP_SHORTCUTS:
-        // DIR_APP_SHORTCUTS is not supported prior Windows 8 and is expected to
-        // fail.
-        valid = butil::win::GetVersion() >= butil::win::VERSION_WIN8;
-        break;
-    }
-
-    if (valid)
-      EXPECT_TRUE(ReturnsValidPath(key)) << key;
-    else
-      EXPECT_TRUE(ReturnsInvalidPath(key)) << key;
-  }
-#elif defined(OS_MACOSX)
-  for (int key = butil::PATH_MAC_START + 1; key < butil::PATH_MAC_END; ++key) {
-    EXPECT_PRED1(ReturnsValidPath, key);
-  }
-#elif defined(OS_ANDROID)
-  for (int key = butil::PATH_ANDROID_START + 1; key < butil::PATH_ANDROID_END;
-       ++key) {
-    EXPECT_PRED1(ReturnsValidPath, key);
-  }
-#elif defined(OS_POSIX)
-  for (int key = butil::PATH_POSIX_START + 1; key < butil::PATH_POSIX_END;
-       ++key) {
-    EXPECT_PRED1(ReturnsValidPath, key);
-  }
-#endif
-}
-#endif
-
-// Test that all versions of the Override function of PathService do what they
-// are supposed to do.
-TEST_F(PathServiceTest, Override) {
-  int my_special_key = 666;
-  butil::ScopedTempDir temp_dir;
-  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
-  butil::FilePath fake_cache_dir(temp_dir.path().AppendASCII("cache"));
-  // PathService::Override should always create the path provided if it doesn't
-  // exist.
-  EXPECT_TRUE(PathService::Override(my_special_key, fake_cache_dir));
-  EXPECT_TRUE(butil::PathExists(fake_cache_dir));
-
-  butil::FilePath fake_cache_dir2(temp_dir.path().AppendASCII("cache2"));
-  // PathService::OverrideAndCreateIfNeeded should obey the |create| parameter.
-  PathService::OverrideAndCreateIfNeeded(my_special_key,
-                                         fake_cache_dir2,
-                                         false,
-                                         false);
-  EXPECT_FALSE(butil::PathExists(fake_cache_dir2));
-  EXPECT_TRUE(PathService::OverrideAndCreateIfNeeded(my_special_key,
-                                                     fake_cache_dir2,
-                                                     false,
-                                                     true));
-  EXPECT_TRUE(butil::PathExists(fake_cache_dir2));
-
-#if defined(OS_POSIX)
-  butil::FilePath non_existent(
-      butil::MakeAbsoluteFilePath(temp_dir.path()).AppendASCII("non_existent"));
-  EXPECT_TRUE(non_existent.IsAbsolute());
-  EXPECT_FALSE(butil::PathExists(non_existent));
-#if !defined(OS_ANDROID)
-  // This fails because MakeAbsoluteFilePath fails for non-existent files.
-  // Earlier versions of Bionic libc don't fail for non-existent files, so
-  // skip this check on Android.
-  EXPECT_FALSE(PathService::OverrideAndCreateIfNeeded(my_special_key,
-                                                      non_existent,
-                                                      false,
-                                                      false));
-#endif
-  // This works because indicating that |non_existent| is absolute skips the
-  // internal MakeAbsoluteFilePath call.
-  EXPECT_TRUE(PathService::OverrideAndCreateIfNeeded(my_special_key,
-                                                     non_existent,
-                                                     true,
-                                                     false));
-  // Check that the path has been overridden and no directory was created.
-  EXPECT_FALSE(butil::PathExists(non_existent));
-  butil::FilePath path;
-  EXPECT_TRUE(PathService::Get(my_special_key, &path));
-  EXPECT_EQ(non_existent, path);
-#endif
-}
-
-// Check if multiple overrides can co-exist.
-TEST_F(PathServiceTest, OverrideMultiple) {
-  int my_special_key = 666;
-  butil::ScopedTempDir temp_dir;
-  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
-  butil::FilePath fake_cache_dir1(temp_dir.path().AppendASCII("1"));
-  EXPECT_TRUE(PathService::Override(my_special_key, fake_cache_dir1));
-  EXPECT_TRUE(butil::PathExists(fake_cache_dir1));
-  ASSERT_EQ(1, butil::WriteFile(fake_cache_dir1.AppendASCII("t1"), ".", 1));
-
-  butil::FilePath fake_cache_dir2(temp_dir.path().AppendASCII("2"));
-  EXPECT_TRUE(PathService::Override(my_special_key + 1, fake_cache_dir2));
-  EXPECT_TRUE(butil::PathExists(fake_cache_dir2));
-  ASSERT_EQ(1, butil::WriteFile(fake_cache_dir2.AppendASCII("t2"), ".", 1));
-
-  butil::FilePath result;
-  EXPECT_TRUE(PathService::Get(my_special_key, &result));
-  // Override might have changed the path representation but our test file
-  // should be still there.
-  EXPECT_TRUE(butil::PathExists(result.AppendASCII("t1")));
-  EXPECT_TRUE(PathService::Get(my_special_key + 1, &result));
-  EXPECT_TRUE(butil::PathExists(result.AppendASCII("t2")));
-}
-
-TEST_F(PathServiceTest, RemoveOverride) {
-  // Before we start the test we have to call RemoveOverride at least once to
-  // clear any overrides that might have been left from other tests.
-  PathService::RemoveOverride(butil::DIR_TEMP);
-
-  butil::FilePath original_user_data_dir;
-  EXPECT_TRUE(PathService::Get(butil::DIR_TEMP, &original_user_data_dir));
-  EXPECT_FALSE(PathService::RemoveOverride(butil::DIR_TEMP));
-
-  butil::ScopedTempDir temp_dir;
-  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
-  EXPECT_TRUE(PathService::Override(butil::DIR_TEMP, temp_dir.path()));
-  butil::FilePath new_user_data_dir;
-  EXPECT_TRUE(PathService::Get(butil::DIR_TEMP, &new_user_data_dir));
-  EXPECT_NE(original_user_data_dir, new_user_data_dir);
-
-  EXPECT_TRUE(PathService::RemoveOverride(butil::DIR_TEMP));
-  EXPECT_TRUE(PathService::Get(butil::DIR_TEMP, &new_user_data_dir));
-  EXPECT_EQ(original_user_data_dir, new_user_data_dir);
-}

+ 0 - 368
test/process_metrics_unittest.cc

@@ -1,368 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "butil/process/process_metrics.h"
-
-#include <sstream>
-#include <string>
-
-#include <gtest/gtest.h>
-
-
-namespace butil {
-namespace debug {
-
-// Tests for SystemMetrics.
-// Exists as a class so it can be a friend of SystemMetrics.
-class SystemMetricsTest : public testing::Test {
- public:
-  SystemMetricsTest() {}
-
- private:
-  DISALLOW_COPY_AND_ASSIGN(SystemMetricsTest);
-};
-
-/////////////////////////////////////////////////////////////////////////////
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-TEST_F(SystemMetricsTest, IsValidDiskName) {
-  std::string invalid_input1 = "";
-  std::string invalid_input2 = "s";
-  std::string invalid_input3 = "sdz+";
-  std::string invalid_input4 = "hda0";
-  std::string invalid_input5 = "mmcbl";
-  std::string invalid_input6 = "mmcblka";
-  std::string invalid_input7 = "mmcblkb";
-  std::string invalid_input8 = "mmmblk0";
-
-  EXPECT_FALSE(IsValidDiskName(invalid_input1));
-  EXPECT_FALSE(IsValidDiskName(invalid_input2));
-  EXPECT_FALSE(IsValidDiskName(invalid_input3));
-  EXPECT_FALSE(IsValidDiskName(invalid_input4));
-  EXPECT_FALSE(IsValidDiskName(invalid_input5));
-  EXPECT_FALSE(IsValidDiskName(invalid_input6));
-  EXPECT_FALSE(IsValidDiskName(invalid_input7));
-  EXPECT_FALSE(IsValidDiskName(invalid_input8));
-
-  std::string valid_input1 = "sda";
-  std::string valid_input2 = "sdaaaa";
-  std::string valid_input3 = "hdz";
-  std::string valid_input4 = "mmcblk0";
-  std::string valid_input5 = "mmcblk999";
-
-  EXPECT_TRUE(IsValidDiskName(valid_input1));
-  EXPECT_TRUE(IsValidDiskName(valid_input2));
-  EXPECT_TRUE(IsValidDiskName(valid_input3));
-  EXPECT_TRUE(IsValidDiskName(valid_input4));
-  EXPECT_TRUE(IsValidDiskName(valid_input5));
-}
-
-TEST_F(SystemMetricsTest, ParseMeminfo) {
-  struct SystemMemoryInfoKB meminfo;
-  std::string invalid_input1 = "abc";
-  std::string invalid_input2 = "MemTotal:";
-  // Partial file with no MemTotal
-  std::string invalid_input3 =
-    "MemFree:         3913968 kB\n"
-    "Buffers:         2348340 kB\n"
-    "Cached:         49071596 kB\n"
-    "SwapCached:           12 kB\n"
-    "Active:         36393900 kB\n"
-    "Inactive:       21221496 kB\n"
-    "Active(anon):    5674352 kB\n"
-    "Inactive(anon):   633992 kB\n";
-  EXPECT_FALSE(ParseProcMeminfo(invalid_input1, &meminfo));
-  EXPECT_FALSE(ParseProcMeminfo(invalid_input2, &meminfo));
-  EXPECT_FALSE(ParseProcMeminfo(invalid_input3, &meminfo));
-
-  std::string valid_input1 =
-    "MemTotal:        3981504 kB\n"
-    "MemFree:          140764 kB\n"
-    "Buffers:          116480 kB\n"
-    "Cached:           406160 kB\n"
-    "SwapCached:        21304 kB\n"
-    "Active:          3152040 kB\n"
-    "Inactive:         472856 kB\n"
-    "Active(anon):    2972352 kB\n"
-    "Inactive(anon):   270108 kB\n"
-    "Active(file):     179688 kB\n"
-    "Inactive(file):   202748 kB\n"
-    "Unevictable:           0 kB\n"
-    "Mlocked:               0 kB\n"
-    "SwapTotal:       5832280 kB\n"
-    "SwapFree:        3672368 kB\n"
-    "Dirty:               184 kB\n"
-    "Writeback:             0 kB\n"
-    "AnonPages:       3101224 kB\n"
-    "Mapped:           142296 kB\n"
-    "Shmem:            140204 kB\n"
-    "Slab:              54212 kB\n"
-    "SReclaimable:      30936 kB\n"
-    "SUnreclaim:        23276 kB\n"
-    "KernelStack:        2464 kB\n"
-    "PageTables:        24812 kB\n"
-    "NFS_Unstable:          0 kB\n"
-    "Bounce:                0 kB\n"
-    "WritebackTmp:          0 kB\n"
-    "CommitLimit:     7823032 kB\n"
-    "Committed_AS:    7973536 kB\n"
-    "VmallocTotal:   34359738367 kB\n"
-    "VmallocUsed:      375940 kB\n"
-    "VmallocChunk:   34359361127 kB\n"
-    "DirectMap4k:       72448 kB\n"
-    "DirectMap2M:     4061184 kB\n";
-  // output from a much older kernel where the Active and Inactive aren't
-  // broken down into anon and file and Huge Pages are enabled
-  std::string valid_input2 =
-    "MemTotal:       255908 kB\n"
-    "MemFree:         69936 kB\n"
-    "Buffers:         15812 kB\n"
-    "Cached:         115124 kB\n"
-    "SwapCached:          0 kB\n"
-    "Active:          92700 kB\n"
-    "Inactive:        63792 kB\n"
-    "HighTotal:           0 kB\n"
-    "HighFree:            0 kB\n"
-    "LowTotal:       255908 kB\n"
-    "LowFree:         69936 kB\n"
-    "SwapTotal:      524280 kB\n"
-    "SwapFree:       524200 kB\n"
-    "Dirty:               4 kB\n"
-    "Writeback:           0 kB\n"
-    "Mapped:          42236 kB\n"
-    "Slab:            25912 kB\n"
-    "Committed_AS:   118680 kB\n"
-    "PageTables:       1236 kB\n"
-    "VmallocTotal:  3874808 kB\n"
-    "VmallocUsed:      1416 kB\n"
-    "VmallocChunk:  3872908 kB\n"
-    "HugePages_Total:     0\n"
-    "HugePages_Free:      0\n"
-    "Hugepagesize:     4096 kB\n";
-
-  EXPECT_TRUE(ParseProcMeminfo(valid_input1, &meminfo));
-  EXPECT_TRUE(meminfo.total == 3981504);
-  EXPECT_TRUE(meminfo.free == 140764);
-  EXPECT_TRUE(meminfo.buffers == 116480);
-  EXPECT_TRUE(meminfo.cached == 406160);
-  EXPECT_TRUE(meminfo.active_anon == 2972352);
-  EXPECT_TRUE(meminfo.active_file == 179688);
-  EXPECT_TRUE(meminfo.inactive_anon == 270108);
-  EXPECT_TRUE(meminfo.inactive_file == 202748);
-  EXPECT_TRUE(meminfo.swap_total == 5832280);
-  EXPECT_TRUE(meminfo.swap_free == 3672368);
-  EXPECT_TRUE(meminfo.dirty == 184);
-#if defined(OS_CHROMEOS)
-  EXPECT_TRUE(meminfo.shmem == 140204);
-  EXPECT_TRUE(meminfo.slab == 54212);
-#endif
-  EXPECT_TRUE(ParseProcMeminfo(valid_input2, &meminfo));
-  EXPECT_TRUE(meminfo.total == 255908);
-  EXPECT_TRUE(meminfo.free == 69936);
-  EXPECT_TRUE(meminfo.buffers == 15812);
-  EXPECT_TRUE(meminfo.cached == 115124);
-  EXPECT_TRUE(meminfo.swap_total == 524280);
-  EXPECT_TRUE(meminfo.swap_free == 524200);
-  EXPECT_TRUE(meminfo.dirty == 4);
-}
-
-TEST_F(SystemMetricsTest, ParseVmstat) {
-  struct SystemMemoryInfoKB meminfo;
-  // part of vmstat from a 3.2 kernel with numa enabled
-  std::string valid_input1 =
-    "nr_free_pages 905104\n"
-    "nr_inactive_anon 142478"
-    "nr_active_anon 1520046\n"
-    "nr_inactive_file 4481001\n"
-    "nr_active_file 8313439\n"
-    "nr_unevictable 5044\n"
-    "nr_mlock 5044\n"
-    "nr_anon_pages 1633780\n"
-    "nr_mapped 104742\n"
-    "nr_file_pages 12828218\n"
-    "nr_dirty 245\n"
-    "nr_writeback 0\n"
-    "nr_slab_reclaimable 831609\n"
-    "nr_slab_unreclaimable 41164\n"
-    "nr_page_table_pages 31470\n"
-    "nr_kernel_stack 1735\n"
-    "nr_unstable 0\n"
-    "nr_bounce 0\n"
-    "nr_vmscan_write 406\n"
-    "nr_vmscan_immediate_reclaim 281\n"
-    "nr_writeback_temp 0\n"
-    "nr_isolated_anon 0\n"
-    "nr_isolated_file 0\n"
-    "nr_shmem 28820\n"
-    "nr_dirtied 84674644\n"
-    "nr_written 75307109\n"
-    "nr_anon_transparent_hugepages 0\n"
-    "nr_dirty_threshold 1536206\n"
-    "nr_dirty_background_threshold 768103\n"
-    "pgpgin 30777108\n"
-    "pgpgout 319023278\n"
-    "pswpin 179\n"
-    "pswpout 406\n"
-    "pgalloc_dma 0\n"
-    "pgalloc_dma32 20833399\n"
-    "pgalloc_normal 1622609290\n"
-    "pgalloc_movable 0\n"
-    "pgfree 1644355583\n"
-    "pgactivate 75391882\n"
-    "pgdeactivate 4121019\n"
-    "pgfault 2542879679\n"
-    "pgmajfault 487192\n";
-  std::string valid_input2 =
-    "nr_free_pages 180125\n"
-    "nr_inactive_anon 51\n"
-    "nr_active_anon 38832\n"
-    "nr_inactive_file 50171\n"
-    "nr_active_file 47510\n"
-    "nr_unevictable 0\n"
-    "nr_mlock 0\n"
-    "nr_anon_pages 38825\n"
-    "nr_mapped 24043\n"
-    "nr_file_pages 97733\n"
-    "nr_dirty 0\n"
-    "nr_writeback 0\n"
-    "nr_slab_reclaimable 4032\n"
-    "nr_slab_unreclaimable 2848\n"
-    "nr_page_table_pages 1505\n"
-    "nr_kernel_stack 626\n"
-    "nr_unstable 0\n"
-    "nr_bounce 0\n"
-    "nr_vmscan_write 0\n"
-    "nr_vmscan_immediate_reclaim 0\n"
-    "nr_writeback_temp 0\n"
-    "nr_isolated_anon 0\n"
-    "nr_isolated_file 0\n"
-    "nr_shmem 58\n"
-    "nr_dirtied 435358\n"
-    "nr_written 401258\n"
-    "nr_anon_transparent_hugepages 0\n"
-    "nr_dirty_threshold 18566\n"
-    "nr_dirty_background_threshold 4641\n"
-    "pgpgin 299464\n"
-    "pgpgout 2437788\n"
-    "pswpin 12\n"
-    "pswpout 901\n"
-    "pgalloc_normal 144213030\n"
-    "pgalloc_high 164501274\n"
-    "pgalloc_movable 0\n"
-    "pgfree 308894908\n"
-    "pgactivate 239320\n"
-    "pgdeactivate 1\n"
-    "pgfault 716044601\n"
-    "pgmajfault 2023\n"
-    "pgrefill_normal 0\n"
-    "pgrefill_high 0\n"
-    "pgrefill_movable 0\n";
-  EXPECT_TRUE(ParseProcVmstat(valid_input1, &meminfo));
-  EXPECT_TRUE(meminfo.pswpin == 179);
-  EXPECT_TRUE(meminfo.pswpout == 406);
-  EXPECT_TRUE(meminfo.pgmajfault == 487192);
-  EXPECT_TRUE(ParseProcVmstat(valid_input2, &meminfo));
-  EXPECT_TRUE(meminfo.pswpin == 12);
-  EXPECT_TRUE(meminfo.pswpout == 901);
-  EXPECT_TRUE(meminfo.pgmajfault == 2023);
-}
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-TEST(SystemMetrics2Test, GetSystemMemoryInfo) {
-  butil::SystemMemoryInfoKB info;
-  EXPECT_TRUE(butil::GetSystemMemoryInfo(&info));
-
-  // Ensure each field received a value.
-  EXPECT_GT(info.total, 0);
-  EXPECT_GT(info.free, 0);
-  EXPECT_GT(info.buffers, 0);
-  EXPECT_GT(info.cached, 0);
-  EXPECT_GT(info.active_anon, 0);
-  EXPECT_GT(info.inactive_anon, 0);
-  EXPECT_GT(info.active_file, 0);
-  EXPECT_GT(info.inactive_file, 0);
-
-  // All the values should be less than the total amount of memory.
-  EXPECT_LT(info.free, info.total);
-  EXPECT_LT(info.buffers, info.total);
-  EXPECT_LT(info.cached, info.total);
-  EXPECT_LT(info.active_anon, info.total);
-  EXPECT_LT(info.inactive_anon, info.total);
-  EXPECT_LT(info.active_file, info.total);
-  EXPECT_LT(info.inactive_file, info.total);
-
-#if defined(OS_CHROMEOS)
-  // Chrome OS exposes shmem.
-  EXPECT_GT(info.shmem, 0);
-  EXPECT_LT(info.shmem, info.total);
-  // Chrome unit tests are not run on actual Chrome OS hardware, so gem_objects
-  // and gem_size cannot be tested here.
-#endif
-}
-#endif  // defined(OS_LINUX) || defined(OS_ANDROID)
-
-#if defined(OS_WIN)
-// TODO(estade): if possible, port this test.
-TEST(ProcessMetricsTest, CalcFreeMemory) {
-  scoped_ptr<butil::ProcessMetrics> metrics(
-      butil::ProcessMetrics::CreateProcessMetrics(::GetCurrentProcess()));
-  ASSERT_TRUE(NULL != metrics.get());
-
-  bool using_tcmalloc = false;
-
-  // Typical values here is ~1900 for total and ~1000 for largest. Obviously
-  // it depends in what other tests have done to this process.
-  butil::FreeMBytes free_mem1 = {0};
-  EXPECT_TRUE(metrics->CalculateFreeMemory(&free_mem1));
-  EXPECT_LT(10u, free_mem1.total);
-  EXPECT_LT(10u, free_mem1.largest);
-  EXPECT_GT(2048u, free_mem1.total);
-  EXPECT_GT(2048u, free_mem1.largest);
-  EXPECT_GE(free_mem1.total, free_mem1.largest);
-  EXPECT_TRUE(NULL != free_mem1.largest_ptr);
-
-  // Allocate 20M and check again. It should have gone down.
-  const int kAllocMB = 20;
-  scoped_ptr<char[]> alloc(new char[kAllocMB * 1024 * 1024]);
-  size_t expected_total = free_mem1.total - kAllocMB;
-  size_t expected_largest = free_mem1.largest;
-
-  butil::FreeMBytes free_mem2 = {0};
-  EXPECT_TRUE(metrics->CalculateFreeMemory(&free_mem2));
-  EXPECT_GE(free_mem2.total, free_mem2.largest);
-  // This test is flaky when using tcmalloc, because tcmalloc
-  // allocation strategy sometimes results in less than the
-  // full drop of 20Mb of free memory.
-  if (!using_tcmalloc)
-    EXPECT_GE(expected_total, free_mem2.total);
-  EXPECT_GE(expected_largest, free_mem2.largest);
-  EXPECT_TRUE(NULL != free_mem2.largest_ptr);
-}
-#endif  // defined(OS_WIN)
-
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-TEST(ProcessMetricsTest, ParseProcStatCPU) {
-  // /proc/self/stat for a process running "top".
-  const char kTopStat[] = "960 (top) S 16230 960 16230 34818 960 "
-      "4202496 471 0 0 0 "
-      "12 16 0 0 "  // <- These are the goods.
-      "20 0 1 0 121946157 15077376 314 18446744073709551615 4194304 "
-      "4246868 140733983044336 18446744073709551615 140244213071219 "
-      "0 0 0 138047495 0 0 0 17 1 0 0 0 0 0";
-  EXPECT_EQ(12 + 16, butil::ParseProcStatCPU(kTopStat));
-
-  // cat /proc/self/stat on a random other machine I have.
-  const char kSelfStat[] = "5364 (cat) R 5354 5364 5354 34819 5364 "
-      "0 142 0 0 0 "
-      "0 0 0 0 "  // <- No CPU, apparently.
-      "16 0 1 0 1676099790 2957312 114 4294967295 134512640 134528148 "
-      "3221224832 3221224344 3086339742 0 0 0 0 0 0 0 17 0 0 0";
-
-  EXPECT_EQ(0, butil::ParseProcStatCPU(kSelfStat));
-}
-#endif // defined(OS_LINUX) || defined(OS_ANDROID)
-
-}  // namespace debug
-}  // namespace butil

+ 0 - 883
test/process_util_unittest.cc

@@ -1,883 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#define _CRT_SECURE_NO_WARNINGS
-
-#include <limits>
-
-#include "butil/command_line.h"
-#include "butil/debug/alias.h"
-#include "butil/debug/stack_trace.h"
-#include "butil/files/file_path.h"
-#include "butil/logging.h"
-#include "butil/memory/scoped_ptr.h"
-#include "butil/path_service.h"
-#include "butil/posix/eintr_wrapper.h"
-#include "butil/process/kill.h"
-#include "butil/process/launch.h"
-#include "butil/process/memory.h"
-#include "butil/process/process.h"
-#include "butil/process/process_metrics.h"
-#include "butil/strings/string_number_conversions.h"
-#include "butil/strings/utf_string_conversions.h"
-#include "butil/synchronization/waitable_event.h"
-#include "test/multiprocess_test.h"
-#include "test/test_timeouts.h"
-#include "butil/third_party/dynamic_annotations/dynamic_annotations.h"
-#include "butil/threading/platform_thread.h"
-#include <gtest/gtest.h>
-#include "test/multiprocess_func_list.h"
-
-#if defined(OS_LINUX)
-#include <malloc.h>
-#include <sched.h>
-#endif
-#if defined(OS_POSIX)
-#include <dlfcn.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <signal.h>
-#include <sys/resource.h>
-#include <sys/socket.h>
-#include <sys/wait.h>
-#endif
-#if defined(OS_WIN)
-#include <windows.h>
-#include "butil/win/windows_version.h"
-#endif
-#if defined(OS_MACOSX)
-#include <mach/vm_param.h>
-#include <malloc/malloc.h>
-#endif
-
-using butil::FilePath;
-
-namespace {
-
-#if defined(OS_ANDROID)
-const char kShellPath[] = "/system/bin/sh";
-const char kPosixShell[] = "sh";
-#else
-const char kShellPath[] = "/bin/sh";
-const char kPosixShell[] = "bash";
-#endif
-
-const char kSignalFileSlow[] = "SlowChildProcess.die";
-const char kSignalFileKill[] = "KilledChildProcess.die";
-
-#if defined(OS_WIN)
-const int kExpectedStillRunningExitCode = 0x102;
-const int kExpectedKilledExitCode = 1;
-#else
-const int kExpectedStillRunningExitCode = 0;
-#endif
-
-// Sleeps until file filename is created.
-void WaitToDie(const char* filename) {
-  FILE* fp;
-  do {
-    butil::PlatformThread::Sleep(butil::TimeDelta::FromMilliseconds(10));
-    fp = fopen(filename, "r");
-  } while (!fp);
-  fclose(fp);
-}
-
-// Signals children they should die now.
-void SignalChildren(const char* filename) {
-  FILE* fp = fopen(filename, "w");
-  fclose(fp);
-}
-
-// Using a pipe to the child to wait for an event was considered, but
-// there were cases in the past where pipes caused problems (other
-// libraries closing the fds, child deadlocking). This is a simple
-// case, so it's not worth the risk.  Using wait loops is discouraged
-// in most instances.
-butil::TerminationStatus WaitForChildTermination(butil::ProcessHandle handle,
-                                                int* exit_code) {
-  // Now we wait until the result is something other than STILL_RUNNING.
-  butil::TerminationStatus status = butil::TERMINATION_STATUS_STILL_RUNNING;
-  const butil::TimeDelta kInterval = butil::TimeDelta::FromMilliseconds(20);
-  butil::TimeDelta waited;
-  do {
-    status = butil::GetTerminationStatus(handle, exit_code);
-    butil::PlatformThread::Sleep(kInterval);
-    waited += kInterval;
-  } while (status == butil::TERMINATION_STATUS_STILL_RUNNING &&
-// Waiting for more time for process termination on android devices.
-#if defined(OS_ANDROID)
-           waited < TestTimeouts::large_test_timeout());
-#else
-           waited < TestTimeouts::action_max_timeout());
-#endif
-
-  return status;
-}
-
-}  // namespace
-
-class ProcessUtilTest : public butil::MultiProcessTest {
- public:
-#if defined(OS_POSIX)
-  // Spawn a child process that counts how many file descriptors are open.
-  int CountOpenFDsInChild();
-#endif
-  // Converts the filename to a platform specific filepath.
-  // On Android files can not be created in arbitrary directories.
-  static std::string GetSignalFilePath(const char* filename);
-};
-
-std::string ProcessUtilTest::GetSignalFilePath(const char* filename) {
-#if !defined(OS_ANDROID)
-  return filename;
-#else
-  FilePath tmp_dir;
-  PathService::Get(butil::DIR_CACHE, &tmp_dir);
-  tmp_dir = tmp_dir.Append(filename);
-  return tmp_dir.value();
-#endif
-}
-
-MULTIPROCESS_TEST_MAIN(SimpleChildProcess) {
-  return 0;
-}
-
-// TODO(viettrungluu): This should be in a "MultiProcessTestTest".
-TEST_F(ProcessUtilTest, SpawnChild) {
-  butil::ProcessHandle handle = SpawnChild("SimpleChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-  EXPECT_TRUE(butil::WaitForSingleProcess(
-                  handle, TestTimeouts::action_max_timeout()));
-  butil::CloseProcessHandle(handle);
-}
-
-MULTIPROCESS_TEST_MAIN(SlowChildProcess) {
-  WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileSlow).c_str());
-  return 0;
-}
-
-TEST_F(ProcessUtilTest, KillSlowChild) {
-  const std::string signal_file =
-      ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
-  remove(signal_file.c_str());
-  butil::ProcessHandle handle = SpawnChild("SlowChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-  SignalChildren(signal_file.c_str());
-  EXPECT_TRUE(butil::WaitForSingleProcess(
-                  handle, TestTimeouts::action_max_timeout()));
-  butil::CloseProcessHandle(handle);
-  remove(signal_file.c_str());
-}
-
-// Times out on Linux and Win, flakes on other platforms, http://crbug.com/95058
-TEST_F(ProcessUtilTest, DISABLED_GetTerminationStatusExit) {
-  const std::string signal_file =
-      ProcessUtilTest::GetSignalFilePath(kSignalFileSlow);
-  remove(signal_file.c_str());
-  butil::ProcessHandle handle = SpawnChild("SlowChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-
-  int exit_code = 42;
-  EXPECT_EQ(butil::TERMINATION_STATUS_STILL_RUNNING,
-            butil::GetTerminationStatus(handle, &exit_code));
-  EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
-
-  SignalChildren(signal_file.c_str());
-  exit_code = 42;
-  butil::TerminationStatus status =
-      WaitForChildTermination(handle, &exit_code);
-  EXPECT_EQ(butil::TERMINATION_STATUS_NORMAL_TERMINATION, status);
-  EXPECT_EQ(0, exit_code);
-  butil::CloseProcessHandle(handle);
-  remove(signal_file.c_str());
-}
-
-#if defined(OS_WIN)
-// TODO(cpu): figure out how to test this in other platforms.
-TEST_F(ProcessUtilTest, GetProcId) {
-  butil::ProcessId id1 = butil::GetProcId(GetCurrentProcess());
-  EXPECT_NE(0ul, id1);
-  butil::ProcessHandle handle = SpawnChild("SimpleChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-  butil::ProcessId id2 = butil::GetProcId(handle);
-  EXPECT_NE(0ul, id2);
-  EXPECT_NE(id1, id2);
-  butil::CloseProcessHandle(handle);
-}
-#endif
-
-#if !defined(OS_MACOSX)
-// This test is disabled on Mac, since it's flaky due to ReportCrash
-// taking a variable amount of time to parse and load the debug and
-// symbol data for this unit test's executable before firing the
-// signal handler.
-//
-// TODO(gspencer): turn this test process into a very small program
-// with no symbols (instead of using the multiprocess testing
-// framework) to reduce the ReportCrash overhead.
-const char kSignalFileCrash[] = "CrashingChildProcess.die";
-
-MULTIPROCESS_TEST_MAIN(CrashingChildProcess) {
-  WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileCrash).c_str());
-#if defined(OS_POSIX)
-  // Have to disable to signal handler for segv so we can get a crash
-  // instead of an abnormal termination through the crash dump handler.
-  ::signal(SIGSEGV, SIG_DFL);
-#endif
-  // Make this process have a segmentation fault.
-  volatile int* oops = NULL;
-  *oops = 0xDEAD;
-  return 1;
-}
-
-// This test intentionally crashes, so we don't need to run it under
-// AddressSanitizer.
-#if defined(ADDRESS_SANITIZER) || defined(SYZYASAN)
-#define MAYBE_GetTerminationStatusCrash DISABLED_GetTerminationStatusCrash
-#else
-#define MAYBE_GetTerminationStatusCrash GetTerminationStatusCrash
-#endif
-TEST_F(ProcessUtilTest, MAYBE_GetTerminationStatusCrash) {
-  const std::string signal_file =
-    ProcessUtilTest::GetSignalFilePath(kSignalFileCrash);
-  remove(signal_file.c_str());
-  butil::ProcessHandle handle = SpawnChild("CrashingChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-
-  int exit_code = 42;
-  EXPECT_EQ(butil::TERMINATION_STATUS_STILL_RUNNING,
-            butil::GetTerminationStatus(handle, &exit_code));
-  EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
-
-  SignalChildren(signal_file.c_str());
-  exit_code = 42;
-  butil::TerminationStatus status =
-      WaitForChildTermination(handle, &exit_code);
-  EXPECT_EQ(butil::TERMINATION_STATUS_PROCESS_CRASHED, status);
-
-#if defined(OS_WIN)
-  EXPECT_EQ(0xc0000005, exit_code);
-#elif defined(OS_POSIX)
-  int signaled = WIFSIGNALED(exit_code);
-  EXPECT_NE(0, signaled);
-  int signal = WTERMSIG(exit_code);
-  EXPECT_EQ(SIGSEGV, signal);
-#endif
-  butil::CloseProcessHandle(handle);
-
-  // Reset signal handlers back to "normal".
-  butil::debug::EnableInProcessStackDumping();
-  remove(signal_file.c_str());
-}
-#endif  // !defined(OS_MACOSX)
-
-MULTIPROCESS_TEST_MAIN(KilledChildProcess) {
-  WaitToDie(ProcessUtilTest::GetSignalFilePath(kSignalFileKill).c_str());
-#if defined(OS_WIN)
-  // Kill ourselves.
-  HANDLE handle = ::OpenProcess(PROCESS_ALL_ACCESS, 0, ::GetCurrentProcessId());
-  ::TerminateProcess(handle, kExpectedKilledExitCode);
-#elif defined(OS_POSIX)
-  // Send a SIGKILL to this process, just like the OOM killer would.
-  ::kill(getpid(), SIGKILL);
-#endif
-  return 1;
-}
-
-TEST_F(ProcessUtilTest, GetTerminationStatusKill) {
-  const std::string signal_file =
-    ProcessUtilTest::GetSignalFilePath(kSignalFileKill);
-  remove(signal_file.c_str());
-  butil::ProcessHandle handle = SpawnChild("KilledChildProcess");
-  ASSERT_NE(butil::kNullProcessHandle, handle);
-
-  int exit_code = 42;
-  EXPECT_EQ(butil::TERMINATION_STATUS_STILL_RUNNING,
-            butil::GetTerminationStatus(handle, &exit_code));
-  EXPECT_EQ(kExpectedStillRunningExitCode, exit_code);
-
-  SignalChildren(signal_file.c_str());
-  exit_code = 42;
-  butil::TerminationStatus status =
-      WaitForChildTermination(handle, &exit_code);
-  EXPECT_EQ(butil::TERMINATION_STATUS_PROCESS_WAS_KILLED, status);
-#if defined(OS_WIN)
-  EXPECT_EQ(kExpectedKilledExitCode, exit_code);
-#elif defined(OS_POSIX)
-  int signaled = WIFSIGNALED(exit_code);
-  EXPECT_NE(0, signaled);
-  int signal = WTERMSIG(exit_code);
-  EXPECT_EQ(SIGKILL, signal);
-#endif
-  butil::CloseProcessHandle(handle);
-  remove(signal_file.c_str());
-}
-
-// Ensure that the priority of a process is restored correctly after
-// backgrounding and restoring.
-// Note: a platform may not be willing or able to lower the priority of
-// a process. The calls to SetProcessBackground should be noops then.
-TEST_F(ProcessUtilTest, SetProcessBackgrounded) {
-  butil::ProcessHandle handle = SpawnChild("SimpleChildProcess");
-  butil::Process process(handle);
-  int old_priority = process.GetPriority();
-#if defined(OS_WIN)
-  EXPECT_TRUE(process.SetProcessBackgrounded(true));
-  EXPECT_TRUE(process.IsProcessBackgrounded());
-  EXPECT_TRUE(process.SetProcessBackgrounded(false));
-  EXPECT_FALSE(process.IsProcessBackgrounded());
-#else
-  process.SetProcessBackgrounded(true);
-  process.SetProcessBackgrounded(false);
-#endif
-  int new_priority = process.GetPriority();
-  EXPECT_EQ(old_priority, new_priority);
-}
-
-// Same as SetProcessBackgrounded but to this very process. It uses
-// a different code path at least for Windows.
-TEST_F(ProcessUtilTest, SetProcessBackgroundedSelf) {
-  butil::Process process(butil::Process::Current().handle());
-  int old_priority = process.GetPriority();
-#if defined(OS_WIN)
-  EXPECT_TRUE(process.SetProcessBackgrounded(true));
-  EXPECT_TRUE(process.IsProcessBackgrounded());
-  EXPECT_TRUE(process.SetProcessBackgrounded(false));
-  EXPECT_FALSE(process.IsProcessBackgrounded());
-#else
-  process.SetProcessBackgrounded(true);
-  process.SetProcessBackgrounded(false);
-#endif
-  int new_priority = process.GetPriority();
-  EXPECT_EQ(old_priority, new_priority);
-}
-
-#if defined(OS_WIN)
-// TODO(estade): if possible, port this test.
-TEST_F(ProcessUtilTest, GetAppOutput) {
-  // Let's create a decently long message.
-  std::string message;
-  for (int i = 0; i < 1025; i++) {  // 1025 so it does not end on a kilo-byte
-                                    // boundary.
-    message += "Hello!";
-  }
-  // cmd.exe's echo always adds a \r\n to its output.
-  std::string expected(message);
-  expected += "\r\n";
-
-  FilePath cmd(L"cmd.exe");
-  CommandLine cmd_line(cmd);
-  cmd_line.AppendArg("/c");
-  cmd_line.AppendArg("echo " + message + "");
-  std::string output;
-  ASSERT_TRUE(butil::GetAppOutput(cmd_line, &output));
-  EXPECT_EQ(expected, output);
-
-  // Let's make sure stderr is ignored.
-  CommandLine other_cmd_line(cmd);
-  other_cmd_line.AppendArg("/c");
-  // http://msdn.microsoft.com/library/cc772622.aspx
-  cmd_line.AppendArg("echo " + message + " >&2");
-  output.clear();
-  ASSERT_TRUE(butil::GetAppOutput(other_cmd_line, &output));
-  EXPECT_EQ("", output);
-}
-
-// TODO(estade): if possible, port this test.
-TEST_F(ProcessUtilTest, LaunchAsUser) {
-  butil::UserTokenHandle token;
-  ASSERT_TRUE(OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, &token));
-  butil::LaunchOptions options;
-  options.as_user = token;
-  EXPECT_TRUE(butil::LaunchProcess(MakeCmdLine("SimpleChildProcess"), options,
-                                  NULL));
-}
-
-static const char kEventToTriggerHandleSwitch[] = "event-to-trigger-handle";
-
-MULTIPROCESS_TEST_MAIN(TriggerEventChildProcess) {
-  std::string handle_value_string =
-      CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
-          kEventToTriggerHandleSwitch);
-  CHECK(!handle_value_string.empty());
-
-  uint64_t handle_value_uint64;
-  CHECK(butil::StringToUint64(handle_value_string, &handle_value_uint64));
-  // Give ownership of the handle to |event|.
-  butil::WaitableEvent event(reinterpret_cast<HANDLE>(handle_value_uint64));
-
-  event.Signal();
-
-  return 0;
-}
-
-TEST_F(ProcessUtilTest, InheritSpecifiedHandles) {
-  // Manually create the event, so that it can be inheritable.
-  SECURITY_ATTRIBUTES security_attributes = {};
-  security_attributes.nLength = static_cast<DWORD>(sizeof(security_attributes));
-  security_attributes.lpSecurityDescriptor = NULL;
-  security_attributes.bInheritHandle = true;
-
-  // Takes ownership of the event handle.
-  butil::WaitableEvent event(
-      CreateEvent(&security_attributes, true, false, NULL));
-  butil::HandlesToInheritVector handles_to_inherit;
-  handles_to_inherit.push_back(event.handle());
-  butil::LaunchOptions options;
-  options.handles_to_inherit = &handles_to_inherit;
-
-  CommandLine cmd_line = MakeCmdLine("TriggerEventChildProcess");
-  cmd_line.AppendSwitchASCII(kEventToTriggerHandleSwitch,
-      butil::Uint64ToString(reinterpret_cast<uint64_t>(event.handle())));
-
-  // This functionality actually requires Vista or later. Make sure that it
-  // fails properly on XP.
-  if (butil::win::GetVersion() < butil::win::VERSION_VISTA) {
-    EXPECT_FALSE(butil::LaunchProcess(cmd_line, options, NULL));
-    return;
-  }
-
-  // Launch the process and wait for it to trigger the event.
-  ASSERT_TRUE(butil::LaunchProcess(cmd_line, options, NULL));
-  EXPECT_TRUE(event.TimedWait(TestTimeouts::action_max_timeout()));
-}
-#endif  // defined(OS_WIN)
-
-#if defined(OS_POSIX)
-
-namespace {
-
-// Returns the maximum number of files that a process can have open.
-// Returns 0 on error.
-int GetMaxFilesOpenInProcess() {
-  struct rlimit rlim;
-  if (getrlimit(RLIMIT_NOFILE, &rlim) != 0) {
-    return 0;
-  }
-
-  // rlim_t is a uint64_t - clip to maxint. We do this since FD #s are ints
-  // which are all 32 bits on the supported platforms.
-  rlim_t max_int = static_cast<rlim_t>(std::numeric_limits<int32_t>::max());
-  if (rlim.rlim_cur > max_int) {
-    return max_int;
-  }
-
-  return rlim.rlim_cur;
-}
-
-const int kChildPipe = 20;  // FD # for write end of pipe in child process.
-
-}  // namespace
-
-MULTIPROCESS_TEST_MAIN(ProcessUtilsLeakFDChildProcess) {
-  // This child process counts the number of open FDs, it then writes that
-  // number out to a pipe connected to the parent.
-  int num_open_files = 0;
-  int write_pipe = kChildPipe;
-  int max_files = GetMaxFilesOpenInProcess();
-  for (int i = STDERR_FILENO + 1; i < max_files; i++) {
-    if (i != kChildPipe) {
-      int fd;
-      if ((fd = HANDLE_EINTR(dup(i))) != -1) {
-        close(fd);
-        num_open_files += 1;
-      }
-    }
-  }
-
-  int written = HANDLE_EINTR(write(write_pipe, &num_open_files,
-                                   sizeof(num_open_files)));
-  DCHECK_EQ(static_cast<size_t>(written), sizeof(num_open_files));
-  int ret = IGNORE_EINTR(close(write_pipe));
-  DPCHECK(ret == 0);
-
-  return 0;
-}
-
-int ProcessUtilTest::CountOpenFDsInChild() {
-  int fds[2];
-  if (pipe(fds) < 0)
-    NOTREACHED();
-
-  butil::FileHandleMappingVector fd_mapping_vec;
-  fd_mapping_vec.push_back(std::pair<int, int>(fds[1], kChildPipe));
-  butil::LaunchOptions options;
-  options.fds_to_remap = &fd_mapping_vec;
-  butil::ProcessHandle handle =
-      SpawnChildWithOptions("ProcessUtilsLeakFDChildProcess", options);
-  CHECK(handle);
-  int ret = IGNORE_EINTR(close(fds[1]));
-  DPCHECK(ret == 0);
-
-  // Read number of open files in client process from pipe;
-  int num_open_files = -1;
-  ssize_t bytes_read =
-      HANDLE_EINTR(read(fds[0], &num_open_files, sizeof(num_open_files)));
-  CHECK_EQ(bytes_read, static_cast<ssize_t>(sizeof(num_open_files)));
-
-#if defined(THREAD_SANITIZER)
-  // Compiler-based ThreadSanitizer makes this test slow.
-  CHECK(butil::WaitForSingleProcess(handle, butil::TimeDelta::FromSeconds(3)));
-#else
-  CHECK(butil::WaitForSingleProcess(handle, butil::TimeDelta::FromSeconds(1)));
-#endif
-  butil::CloseProcessHandle(handle);
-  ret = IGNORE_EINTR(close(fds[0]));
-  DPCHECK(ret == 0);
-
-  return num_open_files;
-}
-
-#if defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER)
-// ProcessUtilTest.FDRemapping is flaky when ran under xvfb-run on Precise.
-// The problem is 100% reproducible with both ASan and TSan.
-// See http://crbug.com/136720.
-#define MAYBE_FDRemapping DISABLED_FDRemapping
-#else
-#define MAYBE_FDRemapping FDRemapping
-#endif
-TEST_F(ProcessUtilTest, MAYBE_FDRemapping) {
-  int fds_before = CountOpenFDsInChild();
-
-  // open some dummy fds to make sure they don't propagate over to the
-  // child process.
-  int dev_null = open("/dev/null", O_RDONLY);
-  int sockets[2];
-  socketpair(AF_UNIX, SOCK_STREAM, 0, sockets);
-
-  int fds_after = CountOpenFDsInChild();
-
-  ASSERT_EQ(fds_after, fds_before);
-
-  int ret;
-  ret = IGNORE_EINTR(close(sockets[0]));
-  DPCHECK(ret == 0);
-  ret = IGNORE_EINTR(close(sockets[1]));
-  DPCHECK(ret == 0);
-  ret = IGNORE_EINTR(close(dev_null));
-  DPCHECK(ret == 0);
-}
-
-namespace {
-
-std::string TestLaunchProcess(const std::vector<std::string>& args,
-                              const butil::EnvironmentMap& env_changes,
-                              const bool clear_environ,
-                              const int clone_flags) {
-  butil::FileHandleMappingVector fds_to_remap;
-
-  int fds[2];
-  PCHECK(pipe(fds) == 0);
-
-  fds_to_remap.push_back(std::make_pair(fds[1], 1));
-  butil::LaunchOptions options;
-  options.wait = true;
-  options.environ = env_changes;
-  options.clear_environ = clear_environ;
-  options.fds_to_remap = &fds_to_remap;
-#if defined(OS_LINUX)
-  options.clone_flags = clone_flags;
-#else
-  CHECK_EQ(0, clone_flags);
-#endif  // OS_LINUX
-  EXPECT_TRUE(butil::LaunchProcess(args, options, NULL));
-  PCHECK(IGNORE_EINTR(close(fds[1])) == 0);
-
-  char buf[512];
-  const ssize_t n = HANDLE_EINTR(read(fds[0], buf, sizeof(buf)));
-
-  PCHECK(IGNORE_EINTR(close(fds[0])) == 0);
-
-  return std::string(buf, n);
-}
-
-const char kLargeString[] =
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789"
-    "0123456789012345678901234567890123456789012345678901234567890123456789";
-
-}  // namespace
-
-TEST_F(ProcessUtilTest, LaunchProcess) {
-  butil::EnvironmentMap env_changes;
-  std::vector<std::string> echo_base_test;
-  echo_base_test.push_back(kPosixShell);
-  echo_base_test.push_back("-c");
-  echo_base_test.push_back("echo $BASE_TEST");
-
-  std::vector<std::string> print_env;
-  print_env.push_back("/usr/bin/env");
-  const int no_clone_flags = 0;
-  const bool no_clear_environ = false;
-
-  const char kBaseTest[] = "BASE_TEST";
-
-  env_changes[kBaseTest] = "bar";
-  EXPECT_EQ("bar\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-  env_changes.clear();
-
-  EXPECT_EQ(0, setenv(kBaseTest, "testing", 1 /* override */));
-  EXPECT_EQ("testing\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-
-  env_changes[kBaseTest] = std::string();
-  EXPECT_EQ("\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-
-  env_changes[kBaseTest] = "foo";
-  EXPECT_EQ("foo\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-
-  env_changes.clear();
-  EXPECT_EQ(0, setenv(kBaseTest, kLargeString, 1 /* override */));
-  EXPECT_EQ(std::string(kLargeString) + "\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-
-  env_changes[kBaseTest] = "wibble";
-  EXPECT_EQ("wibble\n",
-            TestLaunchProcess(
-                echo_base_test, env_changes, no_clear_environ, no_clone_flags));
-
-#if defined(OS_LINUX)
-  // Test a non-trival value for clone_flags.
-  // Don't test on Valgrind as it has limited support for clone().
-  if (!RunningOnValgrind()) {
-    EXPECT_EQ(
-        "wibble\n",
-        TestLaunchProcess(
-            echo_base_test, env_changes, no_clear_environ, CLONE_FS | SIGCHLD));
-  }
-
-  EXPECT_EQ(
-      "BASE_TEST=wibble\n",
-      TestLaunchProcess(
-          print_env, env_changes, true /* clear_environ */, no_clone_flags));
-  env_changes.clear();
-  EXPECT_EQ(
-      "",
-      TestLaunchProcess(
-          print_env, env_changes, true /* clear_environ */, no_clone_flags));
-#endif
-}
-
-TEST_F(ProcessUtilTest, GetAppOutput) {
-  std::string output;
-
-#if defined(OS_ANDROID)
-  std::vector<std::string> argv;
-  argv.push_back("sh");  // Instead of /bin/sh, force path search to find it.
-  argv.push_back("-c");
-
-  argv.push_back("exit 0");
-  EXPECT_TRUE(butil::GetAppOutput(CommandLine(argv), &output));
-  EXPECT_STREQ("", output.c_str());
-
-  argv[2] = "exit 1";
-  EXPECT_FALSE(butil::GetAppOutput(CommandLine(argv), &output));
-  EXPECT_STREQ("", output.c_str());
-
-  argv[2] = "echo foobar42";
-  EXPECT_TRUE(butil::GetAppOutput(CommandLine(argv), &output));
-  EXPECT_STREQ("foobar42\n", output.c_str());
-#else
-  EXPECT_TRUE(butil::GetAppOutput(CommandLine(FilePath("true")), &output));
-  EXPECT_STREQ("", output.c_str());
-
-  EXPECT_FALSE(butil::GetAppOutput(CommandLine(FilePath("false")), &output));
-
-  std::vector<std::string> argv;
-  argv.push_back("/bin/echo");
-  argv.push_back("-n");
-  argv.push_back("foobar42");
-  EXPECT_TRUE(butil::GetAppOutput(CommandLine(argv), &output));
-  EXPECT_STREQ("foobar42", output.c_str());
-#endif  // defined(OS_ANDROID)
-}
-
-// Flakes on Android, crbug.com/375840
-#if defined(OS_ANDROID)
-#define MAYBE_GetAppOutputRestricted DISABLED_GetAppOutputRestricted
-#else
-#define MAYBE_GetAppOutputRestricted GetAppOutputRestricted
-#endif
-TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestricted) {
-  // Unfortunately, since we can't rely on the path, we need to know where
-  // everything is. So let's use /bin/sh, which is on every POSIX system, and
-  // its built-ins.
-  std::vector<std::string> argv;
-  argv.push_back(std::string(kShellPath));  // argv[0]
-  argv.push_back("-c");  // argv[1]
-
-  // On success, should set |output|. We use |/bin/sh -c 'exit 0'| instead of
-  // |true| since the location of the latter may be |/bin| or |/usr/bin| (and we
-  // need absolute paths).
-  argv.push_back("exit 0");   // argv[2]; equivalent to "true"
-  std::string output = "abc";
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 100));
-  EXPECT_STREQ("", output.c_str());
-
-  argv[2] = "exit 1";  // equivalent to "false"
-  output = "before";
-  EXPECT_FALSE(butil::GetAppOutputRestricted(CommandLine(argv),
-                                            &output, 100));
-  EXPECT_STREQ("", output.c_str());
-
-  // Amount of output exactly equal to space allowed.
-  argv[2] = "echo 123456789";  // (the sh built-in doesn't take "-n")
-  output.clear();
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 10));
-  EXPECT_STREQ("123456789\n", output.c_str());
-
-  // Amount of output greater than space allowed.
-  output.clear();
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 5));
-  EXPECT_STREQ("12345", output.c_str());
-
-  // Amount of output less than space allowed.
-  output.clear();
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 15));
-  EXPECT_STREQ("123456789\n", output.c_str());
-
-  // Zero space allowed.
-  output = "abc";
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 0));
-  EXPECT_STREQ("", output.c_str());
-}
-
-#if !defined(OS_MACOSX) && !defined(OS_OPENBSD)
-// TODO(benwells): GetAppOutputRestricted should terminate applications
-// with SIGPIPE when we have enough output. http://crbug.com/88502
-TEST_F(ProcessUtilTest, GetAppOutputRestrictedSIGPIPE) {
-  std::vector<std::string> argv;
-  std::string output;
-
-  argv.push_back(std::string(kShellPath));  // argv[0]
-  argv.push_back("-c");
-#if defined(OS_ANDROID)
-  argv.push_back("while echo 12345678901234567890; do :; done");
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 10));
-  EXPECT_STREQ("1234567890", output.c_str());
-#else
-  argv.push_back("yes");
-  EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 10));
-  EXPECT_STREQ("y\ny\ny\ny\ny\n", output.c_str());
-#endif
-}
-#endif
-
-#if defined(ADDRESS_SANITIZER) && defined(OS_MACOSX) && \
-    defined(ARCH_CPU_64_BITS)
-// Times out under AddressSanitizer on 64-bit OS X, see
-// http://crbug.com/298197.
-#define MAYBE_GetAppOutputRestrictedNoZombies \
-    DISABLED_GetAppOutputRestrictedNoZombies
-#else
-#define MAYBE_GetAppOutputRestrictedNoZombies GetAppOutputRestrictedNoZombies
-#endif
-TEST_F(ProcessUtilTest, MAYBE_GetAppOutputRestrictedNoZombies) {
-  std::vector<std::string> argv;
-
-  argv.push_back(std::string(kShellPath));  // argv[0]
-  argv.push_back("-c");  // argv[1]
-  argv.push_back("echo 123456789012345678901234567890");  // argv[2]
-
-  // Run |GetAppOutputRestricted()| 300 (> default per-user processes on Mac OS
-  // 10.5) times with an output buffer big enough to capture all output.
-  for (int i = 0; i < 300; i++) {
-    std::string output;
-    EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 100));
-    EXPECT_STREQ("123456789012345678901234567890\n", output.c_str());
-  }
-
-  // Ditto, but with an output buffer too small to capture all output.
-  for (int i = 0; i < 300; i++) {
-    std::string output;
-    EXPECT_TRUE(butil::GetAppOutputRestricted(CommandLine(argv), &output, 10));
-    EXPECT_STREQ("1234567890", output.c_str());
-  }
-}
-
-TEST_F(ProcessUtilTest, GetAppOutputWithExitCode) {
-  // Test getting output from a successful application.
-  std::vector<std::string> argv;
-  std::string output;
-  int exit_code;
-  argv.push_back(std::string(kShellPath));  // argv[0]
-  argv.push_back("-c");  // argv[1]
-  argv.push_back("echo foo");  // argv[2];
-  EXPECT_TRUE(butil::GetAppOutputWithExitCode(CommandLine(argv), &output,
-                                             &exit_code));
-  EXPECT_STREQ("foo\n", output.c_str());
-  EXPECT_EQ(exit_code, 0);
-
-  // Test getting output from an application which fails with a specific exit
-  // code.
-  output.clear();
-  argv[2] = "echo foo; exit 2";
-  EXPECT_TRUE(butil::GetAppOutputWithExitCode(CommandLine(argv), &output,
-                                             &exit_code));
-  EXPECT_STREQ("foo\n", output.c_str());
-  EXPECT_EQ(exit_code, 2);
-}
-
-TEST_F(ProcessUtilTest, GetParentProcessId) {
-  butil::ProcessId ppid = butil::GetParentProcessId(butil::GetCurrentProcId());
-  EXPECT_EQ(ppid, getppid());
-}
-
-// TODO(port): port those unit tests.
-bool IsProcessDead(butil::ProcessHandle child) {
-  // waitpid() will actually reap the process which is exactly NOT what we
-  // want to test for.  The good thing is that if it can't find the process
-  // we'll get a nice value for errno which we can test for.
-  const pid_t result = HANDLE_EINTR(waitpid(child, NULL, WNOHANG));
-  return result == -1 && errno == ECHILD;
-}
-
-TEST_F(ProcessUtilTest, DelayedTermination) {
-  butil::ProcessHandle child_process = SpawnChild("process_util_test_never_die");
-  ASSERT_TRUE(child_process);
-  butil::EnsureProcessTerminated(child_process);
-  butil::WaitForSingleProcess(child_process, butil::TimeDelta::FromSeconds(5));
-
-  // Check that process was really killed.
-  EXPECT_TRUE(IsProcessDead(child_process));
-  butil::CloseProcessHandle(child_process);
-}
-
-MULTIPROCESS_TEST_MAIN(process_util_test_never_die) {
-  while (1) {
-    sleep(500);
-  }
-  return 0;
-}
-
-TEST_F(ProcessUtilTest, ImmediateTermination) {
-  butil::ProcessHandle child_process =
-      SpawnChild("process_util_test_die_immediately");
-  ASSERT_TRUE(child_process);
-  // Give it time to die.
-  sleep(2);
-  butil::EnsureProcessTerminated(child_process);
-
-  // Check that process was really killed.
-  EXPECT_TRUE(IsProcessDead(child_process));
-  butil::CloseProcessHandle(child_process);
-}
-
-MULTIPROCESS_TEST_MAIN(process_util_test_die_immediately) {
-  return 0;
-}
-
-#endif  // defined(OS_POSIX)

+ 0 - 1
test/singleton_unittest.cc

@@ -4,7 +4,6 @@
 
 #include "butil/at_exit.h"
 #include "butil/memory/singleton.h"
-#include "butil/path_service.h"
 #include <gtest/gtest.h>
 
 namespace {

+ 0 - 28
test/stack_trace_unittest.cc

@@ -8,24 +8,13 @@
 
 #include "butil/debug/stack_trace.h"
 #include "butil/logging.h"
-#include "butil/process/kill.h"
-#include "butil/process/process_handle.h"
 #include "test/test_timeouts.h"
 #include <gtest/gtest.h>
-#include "test/multiprocess_func_list.h"
-
-#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_IOS)
-#include "test/multiprocess_test.h"
-#endif
 
 namespace butil {
 namespace debug {
 
-#if defined(OS_POSIX) && !defined(OS_ANDROID) && !defined(OS_IOS)
-typedef MultiProcessTest StackTraceTest;
-#else
 typedef testing::Test StackTraceTest;
-#endif
 
 // Note: On Linux, this test currently only fully works on Debug builds.
 // See comments in the #ifdef soup if you intend to change this.
@@ -134,23 +123,6 @@ TEST_F(StackTraceTest, DebugPrintBacktrace) {
 #endif  // !defined(__UCLIBC__)
 
 #if defined(OS_POSIX) && !defined(OS_ANDROID)
-#if !defined(OS_IOS)
-MULTIPROCESS_TEST_MAIN(MismatchedMallocChildProcess) {
-  char* pointer = new char[10];
-  delete pointer;
-  return 2;
-}
-
-// Regression test for StackDumpingSignalHandler async-signal unsafety.
-// Combined with tcmalloc's debugallocation, that signal handler
-// and e.g. mismatched new[]/delete would cause a hang because
-// of re-entering malloc.
-TEST_F(StackTraceTest, AsyncSignalUnsafeSignalHandlerHang) {
-  ProcessHandle child = SpawnChild("MismatchedMallocChildProcess");
-  ASSERT_NE(kNullProcessHandle, child);
-  ASSERT_TRUE(WaitForSingleProcess(child, TestTimeouts::action_timeout()));
-}
-#endif  // !defined(OS_IOS)
 
 namespace {
 

+ 0 - 23
test/test_file_util.cc

@@ -1,23 +0,0 @@
-// Copyright (c) 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "test/test_file_util.h"
-
-#include "test/test_timeouts.h"
-#include "butil/threading/platform_thread.h"
-
-namespace butil {
-
-bool EvictFileFromSystemCacheWithRetry(const FilePath& path) {
-  const int kCycles = 10;
-  const TimeDelta kDelay = TestTimeouts::action_timeout() / kCycles;
-  for (int i = 0; i < kCycles; i++) {
-    if (EvictFileFromSystemCache(path))
-      return true;
-    PlatformThread::Sleep(kDelay);
-  }
-  return false;
-}
-
-}  // namespace butil

+ 0 - 91
test/test_file_util.h

@@ -1,91 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_TEST_TEST_FILE_UTIL_H_
-#define BASE_TEST_TEST_FILE_UTIL_H_
-
-// File utility functions used only by tests.
-
-#include <string>
-
-#include "butil/compiler_specific.h"
-#include "butil/files/file_path.h"
-
-#if defined(OS_ANDROID)
-#include <jni.h>
-#include "butil/basictypes.h"
-#endif
-
-namespace butil {
-
-class FilePath;
-
-// Clear a specific file from the system cache like EvictFileFromSystemCache,
-// but on failure it will sleep and retry. On the Windows buildbots, eviction
-// can fail if the file is marked in use, and this will throw off timings that
-// rely on uncached files.
-bool EvictFileFromSystemCacheWithRetry(const FilePath& file);
-
-// Wrapper over butil::Delete. On Windows repeatedly invokes Delete in case
-// of failure to workaround Windows file locking semantics. Returns true on
-// success.
-bool DieFileDie(const FilePath& file, bool recurse);
-
-// Clear a specific file from the system cache. After this call, trying
-// to access this file will result in a cold load from the hard drive.
-bool EvictFileFromSystemCache(const FilePath& file);
-
-#if defined(OS_WIN)
-// Returns true if the volume supports Alternate Data Streams.
-bool VolumeSupportsADS(const FilePath& path);
-
-// Returns true if the ZoneIdentifier is correctly set to "Internet" (3).
-// Note that this function must be called from the same process as
-// the one that set the zone identifier.  I.e. don't use it in UI/automation
-// based tests.
-bool HasInternetZoneIdentifier(const FilePath& full_path);
-#endif  // defined(OS_WIN)
-
-}  // namespace butil
-
-// TODO(brettw) move all of this to namespace butil.
-namespace file_util {
-
-// In general it's not reliable to convert a FilePath to a wstring and we use
-// string16 elsewhere for Unicode strings, but in tests it is frequently
-// convenient to be able to compare paths to literals like L"foobar".
-std::wstring FilePathAsWString(const butil::FilePath& path);
-butil::FilePath WStringAsFilePath(const std::wstring& path);
-
-// For testing, make the file unreadable or unwritable.
-// In POSIX, this does not apply to the root user.
-bool MakeFileUnreadable(const butil::FilePath& path) WARN_UNUSED_RESULT;
-bool MakeFileUnwritable(const butil::FilePath& path) WARN_UNUSED_RESULT;
-
-#if defined(OS_ANDROID)
-// Register the ContentUriTestUrils JNI bindings.
-bool RegisterContentUriTestUtils(JNIEnv* env);
-
-// Insert an image file into the MediaStore, and retrieve the content URI for
-// testing purpose.
-butil::FilePath InsertImageIntoMediaStore(const butil::FilePath& path);
-#endif  // defined(OS_ANDROID)
-
-// Saves the current permissions for a path, and restores it on destruction.
-class PermissionRestorer {
- public:
-  explicit PermissionRestorer(const butil::FilePath& path);
-  ~PermissionRestorer();
-
- private:
-  const butil::FilePath path_;
-  void* info_;  // The opaque stored permission information.
-  size_t length_;  // The length of the stored permission information.
-
-  DISALLOW_COPY_AND_ASSIGN(PermissionRestorer);
-};
-
-}  // namespace file_util
-
-#endif  // BASE_TEST_TEST_FILE_UTIL_H_

+ 0 - 111
test/test_timeouts.cc

@@ -1,111 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "test/test_timeouts.h"
-
-#include <algorithm>
-
-#include "butil/command_line.h"
-#include "butil/debug/debugger.h"
-#include "butil/logging.h"
-#include "butil/strings/string_number_conversions.h"
-#include "test/test_switches.h"
-
-namespace {
-
-// ASan/TSan/MSan instrument each memory access. This may slow the execution
-// down significantly.
-#if defined(MEMORY_SANITIZER)
-static const int kTimeoutMultiplier = 3;
-#elif defined(ADDRESS_SANITIZER) || defined(THREAD_SANITIZER) || \
-    defined(SYZYASAN)
-static const int kTimeoutMultiplier = 2;
-#else
-static const int kTimeoutMultiplier = 1;
-#endif
-
-const int kAlmostInfiniteTimeoutMs = 100000000;
-
-// Sets value to the greatest of:
-// 1) value's current value multiplied by kTimeoutMultiplier (assuming
-// InitializeTimeout is called only once per value).
-// 2) min_value.
-// 3) the numerical value given by switch_name on the command line multiplied
-// by kTimeoutMultiplier.
-void InitializeTimeout(const char* switch_name, int min_value, int* value) {
-  DCHECK(value);
-  if (CommandLine::ForCurrentProcess()->HasSwitch(switch_name)) {
-    std::string string_value(
-        CommandLine::ForCurrentProcess()->GetSwitchValueASCII(switch_name));
-    int timeout;
-    butil::StringToInt(string_value, &timeout);
-    *value = std::max(*value, timeout);
-  }
-  *value *= kTimeoutMultiplier;
-  *value = std::max(*value, min_value);
-}
-
-// Sets value to the greatest of:
-// 1) value's current value multiplied by kTimeoutMultiplier.
-// 2) 0
-// 3) the numerical value given by switch_name on the command line multiplied
-// by kTimeoutMultiplier.
-void InitializeTimeout(const char* switch_name, int* value) {
-  InitializeTimeout(switch_name, 0, value);
-}
-
-}  // namespace
-
-// static
-bool TestTimeouts::initialized_ = false;
-
-// The timeout values should increase in the order they appear in this block.
-// static
-int TestTimeouts::tiny_timeout_ms_ = 100;
-int TestTimeouts::action_timeout_ms_ = 10000;
-#ifndef NDEBUG
-int TestTimeouts::action_max_timeout_ms_ = 45000;
-#else
-int TestTimeouts::action_max_timeout_ms_ = 30000;
-#endif  // NDEBUG
-int TestTimeouts::large_test_timeout_ms_ = 10 * 60 * 1000;
-
-int TestTimeouts::test_launcher_timeout_ms_ = 45000;
-
-// static
-void TestTimeouts::Initialize() {
-  if (initialized_) {
-    NOTREACHED();
-    return;
-  }
-  initialized_ = true;
-
-  if (butil::debug::BeingDebugged()) {
-    fprintf(stdout,
-        "Detected presence of a debugger, running without test timeouts.\n");
-  }
-
-  // Note that these timeouts MUST be initialized in the correct order as
-  // per the CHECKS below.
-  InitializeTimeout(switches::kTestTinyTimeout, &tiny_timeout_ms_);
-  InitializeTimeout(switches::kUiTestActionTimeout,
-                    butil::debug::BeingDebugged() ? kAlmostInfiniteTimeoutMs
-                                                 : tiny_timeout_ms_,
-                    &action_timeout_ms_);
-  InitializeTimeout(switches::kUiTestActionMaxTimeout, action_timeout_ms_,
-                    &action_max_timeout_ms_);
-  InitializeTimeout(switches::kTestLargeTimeout, action_max_timeout_ms_,
-                    &large_test_timeout_ms_);
-
-  // Test launcher timeout is independent from anything above action timeout.
-  InitializeTimeout(switches::kTestLauncherTimeout, action_timeout_ms_,
-                    &test_launcher_timeout_ms_);
-
-  // The timeout values should be increasing in the right order.
-  CHECK(tiny_timeout_ms_ <= action_timeout_ms_);
-  CHECK(action_timeout_ms_ <= action_max_timeout_ms_);
-  CHECK(action_max_timeout_ms_ <= large_test_timeout_ms_);
-
-  CHECK(action_timeout_ms_ <= test_launcher_timeout_ms_);
-}

+ 0 - 66
test/test_timeouts.h

@@ -1,66 +0,0 @@
-// Copyright (c) 2012 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef BASE_TEST_TEST_TIMEOUTS_H_
-#define BASE_TEST_TEST_TIMEOUTS_H_
-
-#include "butil/basictypes.h"
-#include "butil/logging.h"
-#include "butil/time/time.h"
-
-// Returns common timeouts to use in tests. Makes it possible to adjust
-// the timeouts for different environments (like Valgrind).
-class TestTimeouts {
- public:
-  // Initializes the timeouts. Non thread-safe. Should be called exactly once
-  // by the test suite.
-  static void Initialize();
-
-  // Timeout for actions that are expected to finish "almost instantly".
-  static butil::TimeDelta tiny_timeout() {
-    DCHECK(initialized_);
-    return butil::TimeDelta::FromMilliseconds(tiny_timeout_ms_);
-  }
-
-  // Timeout to wait for something to happen. If you are not sure
-  // which timeout to use, this is the one you want.
-  static butil::TimeDelta action_timeout() {
-    DCHECK(initialized_);
-    return butil::TimeDelta::FromMilliseconds(action_timeout_ms_);
-  }
-
-  // Timeout longer than the above, but still suitable to use
-  // multiple times in a single test. Use if the timeout above
-  // is not sufficient.
-  static butil::TimeDelta action_max_timeout() {
-    DCHECK(initialized_);
-    return butil::TimeDelta::FromMilliseconds(action_max_timeout_ms_);
-  }
-
-  // Timeout for a large test that may take a few minutes to run.
-  static butil::TimeDelta large_test_timeout() {
-    DCHECK(initialized_);
-    return butil::TimeDelta::FromMilliseconds(large_test_timeout_ms_);
-  }
-
-  // Timeout for a single test launched used built-in test launcher.
-  // Do not use outside of the test launcher.
-  static butil::TimeDelta test_launcher_timeout() {
-    DCHECK(initialized_);
-    return butil::TimeDelta::FromMilliseconds(test_launcher_timeout_ms_);
-  }
-
- private:
-  static bool initialized_;
-
-  static int tiny_timeout_ms_;
-  static int action_timeout_ms_;
-  static int action_max_timeout_ms_;
-  static int large_test_timeout_ms_;
-  static int test_launcher_timeout_ms_;
-
-  DISALLOW_IMPLICIT_CONSTRUCTORS(TestTimeouts);
-};
-
-#endif  // BASE_TEST_TEST_TIMEOUTS_H_